MNIST 进阶原文 这篇主要是让我们利用TensorFlow快捷地搭建、训练和评估一个复杂一点儿的深度学习模型,这里其实有两个模型,一个是Softmax 回归模型,一个是卷积神经网络
# -*- coding: utf-8 -*-
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
# InteractiveSession能让你在运行图的时候,插入一些计算图,这些计算图是由某些操作(operations)构成的
sess = tf.InteractiveSession()
# **************构建Softmax 回归模型**************
# 占位符(placeholder)的shape参数是可选的,但有了它,TensorFlow能够自动捕捉因数据维度不一致导致的错误。
# 通过为输入图像和目标输出类别创建节点,来开始构建计算图。
# 输入图片x是一个2维的浮点数张量。这里,分配给它的shape为[None, 784],
# 其中784是一张展平的MNIST图片的维度。None表示其值大小不定,
# 在这里作为第一个维度值,用以指代batch的大小,意即x的数量不定。
x = tf.placeholder("float", shape=[None, 784])
# 输出类别值y_也是一个2维张量,其中每一行为一个10维的one-hot向量,用于代表对应某一MNIST图片的类别。
y_ = tf.placeholder("float", shape=[None, 10])
# 变量代表着TensorFlow计算图中的一个值,能够在计算过程中使用,甚至进行修改。
# 在机器学习的应用过程中,模型参数一般用Variable来表示。
# W是一个784x10的矩阵(因为我们有784个特征和10个输出值)。
W = tf.Variable(tf.zeros([784, 10]))
# b是一个10维的向量(因为我们有10个分类)。
b = tf.Variable(tf.zeros([10]))
# 初始化变量(本例当中是全为零),并将其分配给每个变量,可以一次性为所有变量完成此操作。
sess.run(tf.global_variables_initializer())
# 类别预测与损失函数
# 把向量化后的图片x和权重矩阵W相乘,加上偏置b,然后计算每个分类的softmax概率值。
y = tf.nn.softmax(tf.matmul(x, W) + b)
# 损失函数是目标类别和预测类别之间的交叉熵。
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
# 梯度下降算法(gradient descent algorithm)以0.01的学习速率最小化交叉熵
# 当然TensorFlow也提供了其他许多优化算法:只要简单地调整一行代码就可以使用其他的算法。
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
for i in range(1000):
# 每次加载50个训练样本
batch = mnist.train.next_batch(50)
# 执行一次训练,通过feed_dict将x 和 y_张量占位符用训练训练数据替代。
train_step.run(feed_dict={x: batch[0], y_: batch[1]})
# 评估模型
# tf.argmax 是一个非常有用的函数,它能给出某个tensor对象在某一维上的其数据最大值所在的索引值。
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
# 将布尔值转换为浮点数来代表对、错,然后取平均值。
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
# 计算出在测试数据上的准确率,大概是91%
result = accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})
print("Softmax 回归模型的准确率: {0}".format(result))
# **************构建Softmax 回归模型end**************
# **************构建一个多层卷积网络**************
# 权重初始化
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
# 卷积和池化
def conv2d(xc, wc):
return tf.nn.conv2d(xc, wc, strides=[1, 1, 1, 1], padding="SAME")
def max_pool_2x2(xm):
return tf.nn.max_pool(xm, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
# 第一层卷积
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1, 28, 28, 1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
# 第二层卷积
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
# 密集连接层
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# Dropout
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 输出层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
# 训练和评估模型
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
sess.run(tf.global_variables_initializer())
for i in range(20000):
batch = mnist.train.next_batch(50)
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
print("step: {0}, training accuracy {1}".format(i, train_accuracy))
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
print("多层卷积网络的准确率:{0}".format(accuracy.eval(feed_dict={x: mnist.test.images,
y_: mnist.test.labels, keep_prob: 1.0})))
多层卷积网络,运行的时间有点儿久,毕竟要训练20000次。
如果你在运行过程当中有碰到任何问题,请在下方评论留言,将在第一时间为你解决!
The End!