本文将使用Tensorflow实现一个简单的卷积神经网络,使用的数据集为MNIST,预期可以达到99.2%的准确率。
直接上代码。
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 = 100
# 计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size
2.定义神经网络参数模型方法
# 定义神经网络模型参数初始化方法
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)
3.定义卷积层函数
# 卷积层
def conv2d(x,W):
'''
:param x: input tensor of shape [batch,in_height,in_width,in_channels]
:param W: filter/kernel tensor of shape [filter_h,filter_w,in_channels,out_channels]
:return:
'''
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
4.定义池化层函数
# 池化层
def max_pool_2x2(x):
'''
:param x: x代表输入,一般池化层接在卷积层后面,所以输入通常为feature map
ksize: 池化窗大小,一般为[1,height,width,1]
:return:
'''
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
5.正式设计结构之前先定义输入的placeholder,x是特征,y是真实label
# 定义两个placeholder
with tf.name_scope('input'):
x = tf.placeholder(tf.float32, [None, 784],name='x-input')
y = tf.placeholder(tf.float32, [None, 10],name='y-input')
# 改变x的格式,将1D的输入向量转为2D的图片结构 ,从1x784 ==> 28x28
# 格式为[batch,in_height,in_width,in_channels] ,-1代表样本数量不固定,1代表颜色通道
x_image = tf.reshape(x,[-1,28,28,1])
6.定义第一个卷积层
# 初始化第一个卷积层的权值和偏置 W_conv1 = weight_variable([5,5,1,32]) # 5x5的卷积核尺寸窗口,32个卷积核从1个平面提取特征 b_conv1 = bias_variable([32]) # 每一个卷积核一个偏置值 # 使用conv2d函数对x_image和权值向量进行卷积操作,并加上偏置 # 再使用ReLU激活函数进行非线性处理 h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1) + b_conv1) # 使用最大池化函数对卷积的输出结果进行池化操作 h_pool1 = max_pool_2x2(h_conv1)
7.定义第二个卷积层
# 定义第二个卷积层
# 64个卷积核从32个平面抽取特征,上层卷积有32个输出通道,所以本层卷积的输入通道也为32
W_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64]) # 每一个卷积核一个偏置值
# 使用conv2d函数对h_pool1和权值向量进行卷积操作,并加上偏置
# 再使用ReLU激活函数进行非线性处理
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2) + b_conv2)
# 使用最大池化函数对卷积的输出结果进行池化操作
h_pool2 = max_pool_2x2(h_conv2)
''' 28x28的图片第一次卷积后还是28x28,第一次池化后变为14x14 第二次卷积后是14,第二次池化后变为7x7 通过上面的操作后得到64个7x7的平面,其输出tensor 为7x7x64 '''
8.定义第一个全连接层
# 初始化第一个全连接层
W_fc1 = weight_variable([7*7*64,1024]) # 上一层7*7*64个神经元,全连接层1024个神经元
b_fc1 = bias_variable([1024]) # 1024个节点
# 对上面第二个卷积层的输出tensor进行变形,转化为1D向量
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)
9.使用一个Dropout层
# 为了减轻过拟合,下面使用一个Dropout层
# 通过一个placeholder传入keep_prob比率来控制神经元的输出概率
keep_prob = tf.placeholder(tf.float32)
# 训练时随机丢弃一部分节点的数据来减轻过拟合,预测时则保留全部数据来追求最好的性能预测
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
10.定义全连接层
# 初始化第二个全连接层,将dropout层的输出连接一个Softmax层,得到最后的概率输出
W_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10])
# 计算输出
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2) + b_fc2)
11.定义损失函数为交叉熵并选择优化器
# 交叉熵代价函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
#选择优化器进行优化
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
12.定义评测准确率
# 初始化变量
init = tf.global_variables_initializer()
with tf.name_scope('accuracy'):
# 结果存放在一个布尔型列表中
with tf.name_scope('correct_prediction'):
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1)) # argmax返回一维张量中最大的值所在的位置
# 求准确率
with tf.name_scope('accuracy_in'):
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
13.开始训练并输出
with tf.Session() as sess:
sess.run(init)
train_writer = tf.summary.FileWriter("logs/",sess.graph)
for epoch in range(21):
for batch in range(n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys,keep_prob:0.5})
acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels,keep_prob:1.0})
print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))
这个CNN模型可以得到约99.2%的准确率,基本可以满足对手写数字识别准确率的要求。相比MLP的2%错误率,CNN错误率下降了大约60%。这其中主要的性能提升来自于更优秀的网络设计,即卷积网络对图像特征的提取和抽象能力。依靠卷积核的权值共享,CNN的参数量并没有爆炸,降低了计算量的同时,也减轻了过拟合,因此整个模型的性能有较大的提升。