天天看點

(四)使用TensorFlow完成mnist資料集手寫數字識别

目錄

1、導包

2、下載下傳并加載資料集

3、可以先來看看資料集中的手寫數字到底是什麼樣的

4、定義模型

5、定義測試準确率tensor及其他資料

6、開啟session,疊代訓練并驗證準确率

7、運作檢視結果

8、完整代碼

手寫數字識别在tensorflow中的地位就像學習python、java過程中的Hello,World一樣,本文預設你已經了解了mnist資料集相關的内容。代碼裡的注釋都很詳細了,可以直接一步一步的看代碼和注釋,文末有完整代碼

1、導包

# -*- coding: UTF-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import matplotlib.pyplot as plt
           

2、下載下傳并加載資料集

# 自動下載下傳mnist資料集,并轉化為one_hot編碼
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
           

3、可以先來看看資料集中的手寫數字到底是什麼樣的

# 檢視資料中的label和image
print(mnist.train.images.shape)
print(mnist.train.labels.shape)
print(mnist.test.images.shape)
print(mnist.test.images.shape)
print(np.argmax(mnist.train.labels[1]))
plt.imshow(mnist.train.images[1].reshape(28,28))
plt.show()

輸出:
(55000, 784)
(55000, 10)
(10000, 784)
(10000, 784)
3
           
(四)使用TensorFlow完成mnist資料集手寫數字識别

4、定義模型

# 定義placeholder
X = tf.placeholder(dtype=tf.float32, shape=[None, 784])
Y = tf.placeholder(dtype=tf.float32, shape=[None, 10])
# 定義模型變量
W = tf.Variable(tf.truncated_normal([784, 10]), dtype=tf.float32)
b = tf.Variable(tf.constant(0.1, shape=([10])))
# 定義前向傳播
output = tf.matmul(X, W) + b
# 将激活函數作用于預測值,使用softmax激活函數的原因是因為我們要進行多分類
prediction = tf.nn.softmax(output)
# 反向傳播結構
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(prediction), reduction_indices=1))
train = tf.train.GradientDescentOptimizer(1e-2).minimize(cost)
           

5、定義測試準确率tensor及其他資料

# 将模型訓練好了之後,我們要用測試集的資料進行測試
# 将預測值和測試集的labels進行比較,看看是否相等,使用tf.math.argmax()取出最大值,
# axis=1是因為prediction的shape為[None,10],我們取的是第二個次元裡的最大值,故axis取1
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.math.argmax(prediction, axis=1), tf.math.argmax(Y, axis=1)), tf.float32))
init = tf.global_variables_initializer()
saver = tf.train.Saver(max_to_keep=1)
training_epochs = 100
batch_size = 100
batch_num = int(mnist.train.num_examples / batch_size)
print("每次疊代共将資料劃分為{}批,每批資料為100份".format(batch_num))
           

6、開啟session,疊代訓練并驗證準确率

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(training_epochs):
        loss = 0.
        # 在單次疊代訓練中,每次取batch_size大小的資料,共取的次數就是batch_num
        for _ in range(batch_num):
            x, y = mnist.train.next_batch(batch_size)
            _, _cost = sess.run([train, cost], feed_dict={X: x, Y: y})
            loss += _cost
        print("epoch:", epoch, "loss:", loss / batch_num)
    print("train finished! waiting for saving model")
    saver.save(sess, "model/mnist_1.ckpt")
    print("model has been saved")
    print("start test and verify")
    _acc = sess.run(accuracy, feed_dict={X: mnist.test.images, Y: mnist.test.labels})
    print("the accuracy is :", _acc)
           

7、運作檢視結果

訓練一百次後在測試集上的準确率達到了接近90%

(四)使用TensorFlow完成mnist資料集手寫數字識别

8、完整代碼

# -*- coding: UTF-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import matplotlib.pyplot as plt

"""
訓練樣本:共55000個
驗證樣本:共5000個 
測試樣本:共10000個
圖檔大小為28x28
"""
# 自動下載下傳mnist資料集,并轉化為one_hot編碼
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 檢視資料中的label和image
print(mnist.train.images.shape)
print(mnist.train.labels.shape)
print(mnist.test.images.shape)
print(mnist.test.images.shape)
print(np.argmax(mnist.train.labels[1]))
plt.imshow(mnist.train.images[1].reshape(28,28))
plt.show()

# 定義placeholder
X = tf.placeholder(dtype=tf.float32, shape=[None, 784])
Y = tf.placeholder(dtype=tf.float32, shape=[None, 10])
# 定義模型變量
W = tf.Variable(tf.truncated_normal([784, 10]), dtype=tf.float32)
b = tf.Variable(tf.constant(0.1, shape=([10])))
# 定義前向傳播
output = tf.matmul(X, W) + b
# 将激活函數作用于預測值,使用softmax激活函數的原因是因為我們要進行多分類
prediction = tf.nn.softmax(output)
# 反向傳播結構
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(prediction), reduction_indices=1))
train = tf.train.GradientDescentOptimizer(1e-2).minimize(cost)
# 定義測試準确率tensor
# 将模型訓練好了之後,我們要用測試集的資料進行測試
# 将預測值和測試集的labels進行比較,看看是否相等,使用tf.math.argmax()取出最大值,
# axis=1是因為prediction的shape為[None,10],我們取的是第二個次元裡的最大值,故axis取1
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.math.argmax(prediction, axis=1), tf.math.argmax(Y, axis=1)), tf.float32))
init = tf.global_variables_initializer()
saver = tf.train.Saver(max_to_keep=1)
training_epochs = 100
batch_size = 100
batch_num = int(mnist.train.num_examples / batch_size)
print("每次疊代共将資料劃分為{}批,每批資料為100份".format(batch_num))
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(training_epochs):
        loss = 0.
        # 在單次疊代訓練中,每次取batch_size大小的資料,共取的次數就是batch_num
        for _ in range(batch_num):
            x, y = mnist.train.next_batch(batch_size)
            _, _cost = sess.run([train, cost], feed_dict={X: x, Y: y})
            loss += _cost
        print("epoch:", epoch, "loss:", loss / batch_num)
    print("train finished! waiting for saving model")
    saver.save(sess, "model/mnist_1.ckpt")
    print("model has been saved")
    print("start test and verify")
    _acc = sess.run(accuracy, feed_dict={X: mnist.test.images, Y: mnist.test.labels})
    print("the accuracy is :", _acc)