前两天,我们已经知道了TensorFlow的安装,以及基础语法,今天我们用这些来实现一个MNIST,也就是手写数字识别的神经网络。前情回顾:
TensorFlow学习笔记(一)基础入门
TensorFlow学习笔记(二)ReLU、Softmax、Cross Entropy
【深度学习 Hello World系列(一)】 用TFLearn实现MNIST
这里,我们用TensorFlow实现一个3层,即输入层、隐藏层、输出层的神经网络。
引入相关模块
# tensorflow 自带mnist模块
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(".", one_hot=True, reshape=False)
import tensorflow as tf
这里有个one_hot=True,one_hot表示独热编码,可以看下面的图片理解意思:
参数设置
learning_rate = 0.001
training_epochs = 20
batch_size = 128
display_step = 1 # 设置日志显示次数用的
n_input = 784 # 输入的大小
n_classes = 10 # 最后分成10个类别
learning rate是学习的速度,每次更新参数时的步长(速度),太小会造成学习速度太慢,太大会造成无法拟合的结果。
一个 epoch(代)是指整个数据集正向反向训练一次。
batch size 是一次拿多少数据去训练,具体可以参考What is a batch in TensorFlow? - Stack Overflow。
# 隐藏层节点(特征)数
n_hidden_layer = 256
# y = wx + b 中的w
weights = {
'hidden_layer': tf.Variable(tf.random_normal([n_input, n_hidden_layer])),
'out': tf.Variable(tf.random_normal([n_hidden_layer, n_classes]))
}
# y = wx + b 中的b
biases = {
'hidden_layer': tf.Variable(tf.random_normal([n_hidden_layer])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# 输入的x
x = tf.placeholder("float", [None, 28, 28, 1])
# 输出的y
y = tf.placeholder("float", [None, n_classes])
# 把x转成一行784列的tensor
x_flat = tf.reshape(x, [-1, n_input])
这里有个奇怪的地方,tf.reshaple()里面有个参数是-1,这里官方文档特别给出了解释:
If one component of shape is the special value -1, the size of that dimension is computed so that the total size remains constant. In particular, a shape of [-1] flattens into 1-D. At most one component of shape can be -1.
定义模型
# 隐藏层 layer_1,下面的代码就表示 y = wx + b
layer_1 = tf.add(tf.matmul(x_flat, weights['hidden_layer']),\
biases['hidden_layer'])
#用ReLU作为激活函数
layer_1 = tf.nn.relu(layer_1)
# 输出层,这里输出层没有搞非线性激活函数
logits = tf.add(tf.matmul(layer_1, weights['out']), biases['out'])
# 损失函数
cost = tf.reduce_mean(\
tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
# 优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\
.minimize(cost)
Session
# 初始化变量,每次都要有
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# 循环训练
for epoch in range(training_epochs):
total_batch = int(mnist.train.num_examples/batch_size)
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
# 运行优化器进行反向传导、计算 cost(获取 loss 值)
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
完整代码可以在这里下载。
训练结果
ps.本文是优达学城深度学习课程的学习笔记,更多内容可以直接查看优达学城的课程,以下链接也有可能有帮助:
Aymeric Damien 的 GitHub repository
https://github.com/udacity/cn-deep-learning
https://www.tensorflow.org/get_started/