本博客将建立一个简单的卷积神经网络,可以把MNIST手写字符的识别准确率提高到99%。具体如下:
程序的开头是导入TensorFlow
import tensorflow as tf
import numpy as np
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"#指定GPU
#从tensorflow.examples.tutorials.mnist引入模块
from tensorflow.examples.tutorials.mnist import input_data
查看训练集、验证集、测试集的数据大小
#查看训练数据的大小
print(mnist.train.images.shape) # (55000, 784)
print(mnist.train.labels.shape) # (55000, 10)
#查看验证数据的大小
print(mnist.validation.images.shape) # (5000, 784)
print(mnist.validation.labels.shape) # (5000, 10)
#查看测试数据的大小
print(mnist.test.images.shape) # (10000, 784)
print(mnist.test.labels.shape) # (10000, 10)
#打印出第0幅图片的向量表示
print(mnist.train.images[0, :])
#打印出第0幅图片的标签
print(mnist.train.labels[0, :])
#查看前20张训练图片的label
for i in range(20):
#得到one-hot表示,形如(0, 1, 0, 0, 0, 0, 0, 0, 0, 0)
one_hot_label = mnist.train.labels[i, :]
# 通过np.argmax我们可以直接获得原始的label
# 因为只有1位为1,其他都是0
label = np.argmax(one_hot_label)
print('mnist_train_%d.jpg label: %d' % (i, label))
完整代码为
import tensorflow as tf
import numpy as np
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"#指定GPU
#从tensorflow.examples.tutorials.mnist引入模块
from tensorflow.examples.tutorials.mnist import input_data
#从MNIST_data/中读取MNIST数据,当数据不存在时,会自动执行下载
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
#查看训练数据的大小
print(mnist.train.images.shape) # (55000, 784)
print(mnist.train.labels.shape) # (55000, 10)
#查看验证数据的大小
print(mnist.validation.images.shape) # (5000, 784)
print(mnist.validation.labels.shape) # (5000, 10)
#查看测试数据的大小
print(mnist.test.images.shape) # (10000, 784)
print(mnist.test.labels.shape) # (10000, 10)
#打印出第0幅图片的向量表示
print(mnist.train.images[0, :])
#打印出第0幅图片的标签
print(mnist.train.labels[0, :])
#查看前20张训练图片的label
for i in range(20):
#得到one-hot表示,形如(0, 1, 0, 0, 0, 0, 0, 0, 0, 0)
one_hot_label = mnist.train.labels[i, :]
# 通过np.argmax我们可以直接获得原始的label
# 因为只有1位为1,其他都是0
label = np.argmax(one_hot_label)
print('mnist_train_%d.jpg label: %d' % (i, label))
#定义权重
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)
#卷积层,步长为1
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
#最大池化层,步长为2
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
if __name__ == '__main__':
#x为训练图像的占位符,输入图像是28*28=784
x = tf.placeholder(tf.float32, [None, 784])
#y_为训练图像标签的占位符,输出类别是10类
y_ = tf.placeholder(tf.float32, [None, 10])
#将单张图片从784维向量重新还原为28x28的矩阵图片
x_image = tf.reshape(x, [-1, 28, 28, 1])
with tf.variable_scope("conv1"):
#第一层卷积层和池化层,卷积核大小为5*5,卷积核个数为32,
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
with tf.variable_scope("conv2"):
#第二层卷积层和池化层,卷积核大小为5*5,卷积核个数为64
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)
with tf.variable_scope("fc1"):
#全连接层,输出为1024维的向量
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是一个占位符,训练时为0.5,测试时为1
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
#把1024维的向量转换成10维,对应10个类别
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
with tf.variable_scope("loss"):
#不采用先Softmax再计算交叉熵的方法,而是直接用tf.nn.softmax_cross_entropy_with_logits直接计算
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
with tf.variable_scope("optimizer"):
#同样定义train_step
train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)
with tf.variable_scope("acc"):
#定义测试的准确率,tf.argmax(y,1)、tf.argmax(y_,1)的功能是取出数组中最大值的下标
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#收集变量,单个数字值收集
#记录loss,accuracy变化曲线
tf.summary.scalar("losses",loss)
tf.summary.scalar("acc",accuracy)
#高纬度变量收集
tf.summary.histogram('weightes',W_conv1)
tf.summary.histogram('biases',b_conv1)
#创建Session和变量初始化
init_op = tf.global_variables_initializer()
#定义一个合并变量的op
merged = tf.summary.merge_all()
with tf.Session() as sess:
#初始化所有变量
sess.run(init_op)
#建立events文件,然后写入
filewriter = tf.summary.FileWriter('./tensorboard/',graph=sess.graph)
#训练20000步
for i in range(20000):
batch = mnist.train.next_batch(64)
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
#写入每步训练的值
summary = sess.run(merged,feed_dict={x:batch[0], y_:batch[1], keep_prob: 0.5})
filewriter.add_summary(summary,i)
#每100步显示一次在验证集上的准确度
if i % 100 == 0:
#显示训练时的准确率
train_accuracy = accuracy.eval(feed_dict={
x: batch[0], y_: batch[1], keep_prob: 1.0})
print("step %d, training accuracy %g" % (i, train_accuracy))
#在验证集上的准确度
print("validation accuracy %g" % accuracy.eval(feed_dict={
x: mnist.validation.images, y_: mnist.validation.labels, keep_prob: 1.0}))
#训练结束后报告在测试集上的准确度
print("test accuracy %g" % accuracy.eval(feed_dict={
x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
运行结果如下图所示
图
损失函数变化曲线
准确率变化曲线