- 手写数字识别
MNIST是一个非常有名的手写体数字识别数据集,在很多资料中,这个数据集都会被用作深度学习的入门样例。而TensorFlow的封装让使用MNIST数据集变得更加方便。MNIST数据集是NIST数据集的一个子集,它包含了60000张图片作为训练数据,10000张图片作为测试数据。在MNIST数据集中的每一张图片都代表了0~9中的一个数字。图片的大小都为28*28,且数字都会出现在图片的正中间,如下图所示:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
表示下载数据集,如果网速不好可以先下载到对应的文件夹下。one_hot=True 是使用one-hot编码
MNIST程序1:
# 手写数字识别
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 载入数据集
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 每个批次的大小
batch_size = 50
# 计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size
# 定义两个placeholder
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
# 创建一个简单的神经网络
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
predition = tf.nn.softmax(tf.matmul(x, W) + b)
# 二次代价函数
loss = tf.reduce_mean(tf.square(y - predition))
# 使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
init = tf.global_variables_initializer()
# 求准确率的方法
# tf.argmax(y,1)判断最大概率的标签(位置
correct_predtion = tf.equal(tf.argmax(y, 1), tf.argmax(predition, 1))
# 求准确率
# tf.cast类型转化
accuracy = tf.reduce_mean(tf.cast(correct_predtion, tf.float32))
# 进行训练
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(21): # 整体循环21次训练
for batch in range(n_batch): # 整体执行一次图片循环
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
print(batch_xs)
print('\n')
print(batch_ys)
sess.run(train_step, feed_dict={
x: batch_xs,
y: batch_ys
})
acc = sess.run(accuracy, feed_dict={
x: mnist.test.images,
y: mnist.test.labels
})
print("Iter " + str(epoch) + " ,Test Accuracy:" + str(acc))
输出结果:Iter 20 ,Test Accuracy:0.92050016
函数解析:
- 分batch训练
为什么分batch训练:
(此部分转自:https://blog.csdn.net/weixin_43202635/article/details/84204180)
极端一: