TensorFlow——MNIST手寫數據集

MNIST數據集介紹html

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編碼。session

MNIST數據集中的圖片是28*28的,每張圖被轉化爲一個行向量,長度是28*28=784,每個值表明一個像素點。數據集中共有60000張手寫數據圖片,其中55000張訓練數據,5000張測試數據。dom

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

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

下面定義了一個簡單的網絡對數據集進行訓練,代碼以下:spa

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()
相關文章
相關標籤/搜索