1. 程式人生 > >TensorFlow——MNIST手寫資料集

TensorFlow——MNIST手寫資料集

MNIST資料集介紹

MNIST資料集中包含了各種各樣的手寫數字圖片,資料集的官網是:http://yann.lecun.com/exdb/mnist/index.html,我們可以從這裡下載資料集。使用如下的程式碼對資料集進行載入:

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

執行上述程式碼會自動下載資料集並將檔案解壓在MNIST_data資料夾下面。程式碼中的one_hot=True,表示將樣本的標籤轉化為one_hot編碼。

MNIST資料集中的圖片是28*28的,每張圖被轉化為一個行向量,長度是28*28=784,每一個值代表一個畫素點。資料集中共有60000張手寫資料圖片,其中55000張訓練資料,5000張測試資料。

在MNIST中,mnist.train.images是一個形狀為[55000, 784]的張量,其中的第一個維度是用來索引圖片,第二個維度圖片中的畫素。MNIST資料集包含有三部分,訓練資料集,驗證資料集,測試資料集(mnist.validation)。

標籤是介於0-9之間的數字,用於描述圖片中的數字,轉化為one-hot向量即表示的數字對應的下標為1,其餘的值為0。標籤的訓練資料是[55000,10]的數字矩陣。

下面定義了一個簡單的網路對資料集進行訓練,程式碼如下:

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

tf.reset_default_graph()

x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])

w = tf.Variable(tf.random_normal([784, 10]))
b = tf.Variable(tf.zeros([10]))

pred = tf.matmul(x, w) + b
pred = tf.nn.softmax(pred)

cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred), reduction_indices=1))

learning_rate = 0.01

optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

training_epochs = 25
batch_size = 100

display_step = 1

save_path = 'model/'

saver = tf.train.Saver()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(training_epochs):
        avg_cost = 0
        total_batch = int(mnist.train.num_examples/batch_size)
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            _, c = sess.run([optimizer, cost], feed_dict={x:batch_xs, y:batch_ys})
            avg_cost += c / total_batch

        if (epoch + 1) % display_step == 0:
            print('epoch= ', epoch+1, ' cost= ', avg_cost)
    print('finished')

    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print('accuracy: ', accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))

    save = saver.save(sess, save_path=save_path+'mnist.cpkt')

print(" starting 2nd session ...... ")

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver.restore(sess, save_path=save_path+'mnist.cpkt')

    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print('accuracy: ', accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

    output = tf.argmax(pred, 1)
    batch_xs, batch_ys = mnist.test.next_batch(2)
    outputval= sess.run([output], feed_dict={x:batch_xs, y:batch_ys})
    print(outputval)

    im = batch_xs[0]
    im = im.reshape(-1, 28)

    plt.imshow(im, cmap='gray')
    plt.show()

    im = batch_xs[1]
    im = im.reshape(-1, 28)
    plt.imshow(im, cmap='gray')
    plt.show()

&n