天天看点

(四)使用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)