利用卷积神经网络进行手写数字识别详解

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

‘’‘可分别用这两个函数创建卷积核(kernel)与偏置(bias)’’’
#返回一个给定形状的变量,并自动以截断正态分布初始化
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev = 0.1)
return tf.Variable(initial)

#返回一个给定形状的变量,初始化时所有值是0.1
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)

‘’‘strides表示在卷积时在图像每一维的步长,这是一个一维的向量,长度4’’’
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides = [1, 1, 1, 1], padding=‘SAME’)

‘’‘池化窗口的大小,取一个四维向量,一般是[1, height, width, 1],
因为我们不想在batch和channels上做池化,所以这两个维度设为了1
和卷积类似,窗口在每一个维度上滑动的步长,一般也是[1, stride,stride, 1]
padding=’VALID’时,无自动填充。padding=’SAME’时,自动填充,池化后保持shape不变’’’
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=‘SAME’)

‘’‘当.py文件被直接运行时,if name == ‘main’之下的代码块将被运行;
当.py文件以模块形式被导入时,name == 模块名,if name == ‘main’之下的代码块不被运行’’’
if name == ‘main’:
# 读入数据
mnist = input_data.read_data_sets(“MNIST_data/”, one_hot=True)
# x为训练图像的占位符,y_为训练图像标签的占位符
x = tf.placeholder(tf.float32, [None, 784])
y
= tf.placeholder(tf.float32, [None, 10])
# 将单张图片从784维向量重新还原为2828的矩阵图片,最后一个维度是颜色通道数
# -1表示形状第一维的大小是根据x自动确定的
x_image = tf.reshape(x, [-1, 28, 28, 1])
#第一层卷积,5
5大小的窗口,颜色通道数为1,数量为32个
W_conv1 = weight_variable([5, 5, 1, 32])
#维度为32的向量
b_conv1 = bias_variable([32])
#进行卷积计算,卷积计算之后选用ReLU作为激活函数
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
#进行第一次池化操作
h_pool1 = max_pool_2x2(h_conv1)
#第二层卷积,上一层生成的个数为32,所以为32通道,这一层生成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)
#全连接层,输出为1024维的向量,两次池化之后变成7*7的矩阵,全连接层设置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)
#加入Dropout,防止过拟合
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
#最后,再加入一个全连接层,把上一步得到的h_fc1_drop转换为10个类别的打分
#把1024维的向量转换为10维,对应10个类别
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
#y_conv相当于Softmax模型中的Logit
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
#不采用先Softmax再计算交叉熵的方法
#而是用tf.nn.softmax_cross_entropy_with_logits直接计算,logits:就是神经网络最后一层的输出,labels:实际的标签,大小同上
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y
, logits = y_conv))
#同样定义trian_step,这里步长设置为1e-4,优化算法使用AdamOptimizer,来最优化损失函数
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, tf.float32))
‘’‘创建Session,对变量初始化,tf.InteractiveSession():它能让你在运行图的时候,插入一些计算图
tf.Session():需要在启动session之前构建整个计算图,然后启动该计算图’’’
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
#训练20000步
for i in range(20000):
# 在mnist.train中提取50个训练数据
batch = mnist.train.next_batch(50) #batch有两个参数
#每100步报告一次在验证集上的准确率
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_:batch[1], keep_prob:1.0}) #如果是Tensor对象时,eval与run的效果一样,测试效果
print(“step %d, training accuracy %g” %(i, train_accuracy))
train_step.run(feed_dict={x:batch[0], y_:batch[1], keep_prob:0.5})
#训练结束后报告在测试集上的准确率
print(“test accuracy %g” % accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0}))

猜你喜欢

转载自blog.csdn.net/qq_38817009/article/details/84928122