tensorflow学习之路 八:使用卷积神经网络进行手写数字识别。
前面的文章使用了传统神经网络对手写数字进行识别,为了学习卷积神经网络,继续使用手写识别这个案例,不过这里使用卷积神经网络代替传统神经网络。通过案例学习到,如何使用卷积神经网络替代传统神经网络完成手写识别方法。学习如何定义以及使用卷积神经。
结构:
这里整个模型的结构是:2层卷积层以及2层全连接层。2层卷积层中卷积核的大小均是5×5大小的卷积核。
接下来我们一点一点完成代码的解释:
1.palceholder定义:这里和前面的placeholder定义方法相同。
#定义两个placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
2.定义初始化卷积核权值和偏置值方法:
#初始化权值
def weight_variable(shape):
inital = tf.truncated_normal(shape,stddev=0.1)#生成一个截断的正态分布
return tf.Variable(inital)
#初始化偏置值
def bias_variable(shape):
inital = tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(inital)
shape:表示输入的形状,让他们的初始化形状符合正太分布,这里先这样定义,根据下面代码,返回来理解shape的作用会更加清晰。
3.定义卷积层:
def conv2d(x,W):
# x: input a tensor of shape [batch,in_height,in_width,in_channels]
batch: 批次大小
in_weight,in_width:输入x的长和宽
in_channels:表述通道数量,黑白图片通道为1,彩色为3
# W: 一个滤波器(卷积核) tensor of shape[filter_height,filter_width,in_channels,out_channels]
shape[卷积核长,卷积核宽,输入通道数,输出通道数]
#strides[0] = strides[3] == 1 strides[1]代表x方向步长,strides【2】代表y方向的步长
#padding A string from ‘SAME’‘VALID’
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
其实只有一句话,就是定义的权值语输入的x进行卷积运算,运算使用的是tensorflow定义好的函数。
4.定义池化层:
#池化层
def max_pool_2x2(x):
#ksize: 表示池化窗口2,2表示x和y方向长度
#stride:2,2表示x和y方向的步长
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
前面已经定义好了所有的前置条件,接下来开始一步一步的:
输入-->卷积-->池化-->卷积-->池化-->全连接-->全连接-->输出
1.输入的每一个图片是一个784维的向量:[1×784],首先先改成[28×28]形状,形象的理解成现在有了一个方形的图片。
#改变x的格式为4D的向量[batch,in_height,in_width,in_channels]
x_image = tf.reshape(x,[-1,28,28,1])
2.卷积:先通过上面定义的权值和偏置值函数,初始化第一个卷积层需要的权值和偏置,输入单通道,输出32通道,理解为通过 一张图片生成32张不同特征图片。
#初始化第一个卷积层的权值和偏置
W_conv1 = weight_variable([5,5,1,32])#5*5的采样窗口,32个卷积核从1个平面抽取特征,输入通道32
b_conv1 = bias_variable([32])#每个卷积核一个偏置值
#x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1
3.池化:将卷积的输入进行池化,这里采用最大池化方法,如何定义池化上面已经介绍
h_pool1 = max_pool_2x2(h_conv1)#进行max—pooling
4.继续上面的方法,继续一次卷积和池化操作
#初始化第二个卷积层的权值和偏置
W_conv2 = weight_variable([5,5,32,64])#5*5的采样窗口,32个卷积核从1个平面抽取特征
b_conv2 = bias_variable([64])#每个卷积核一个偏置值
#h_pool1和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
h_pool2 = max_pool_2x2(h_conv2)#进行max—pooling
完成2次卷积和两次池化之后,原图片shape变为了【28×28×1】--->【14×14×32】--->【7×7×64】
5.接下来进入第一个全连接层,第一个全连接层含有1024个神经元。回想下传统神经网络,传统神经网络中,如果是一个神经元,那么输入大小就是1输出大小就是1024。通过上面两个卷积池化层,输出的是7×7,64张特征图片,一共就是7×7×64个神经元需要输入。(注意的是,要把池化层的输出进行reshape)
#初始化第一个全连接层的权值
W_fc1 = weight_variable([7*7*64,1024])#上一场有7*7*64个神经元,全连接层有1024个神经元
b_fc1 = bias_variable([1024])
#把池化层2的输出扁平化为1维
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)
这里的-1,可以理解成未知参数,加入将100图片进行训练,-1就会改成100,这里是5000张图片进行的训练,-1就是5000,【-1,7*7*64】n张图片,每张图片7*7*64个特征
6.为防止过拟合情况发生,添加drop out方法。
#keep_prob用来表示神经元的输出概率
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
7.接下来就是第二层的全连接层。直接看代码。
#初始化第二个全连接层
W_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10])
#求第二个全连接层的输出
h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop,W_fc2) + b_fc2)
#计算输出
prediction = tf.nn.softmax(h_fc2)
prediction为对每个0-9数字预测的概率
8.使用交叉熵代价函数和AdmOptimizer进行优化
#交叉熵代价函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y,logits=prediction))
#使用AdmOptimizer进行优化
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
后面的步骤,像如何求准确率方法,显示每次迭代准确率方法,都和传统神经网络实现手写数字识别代码相同。
最后附上完整代码:
"""
卷积神经网络
传统神经网络存在问题:
1.权值太多,计算量太大
2.权值太多,需要大量样本进行训练
"""
import tensorflow as tf
old_v = tf.logging.get_verbosity()
tf.logging.set_verbosity(tf.logging.ERROR)
from tensorflow.examples.tutorials.mnist import input_data
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#载入数据
mnist = input_data.read_data_sets("MNIST_data",one_hot=True,source_url=
'http://yann.lecun.com/exdb/mnist/')
tf.logging.set_verbosity(old_v)
print("type of 'mnnist' is %s"% (type(mnist)))
print("number of train data is %d " % mnist.train.num_examples)
print("number of test data is %d" % mnist.test.num_examples)
#每个批次大小
batch_size = 100
#计算一共有多少批次
n_batch = mnist.train.num_examples//batch_size
#初始化权值
def weight_variable(shape):
inital = tf.truncated_normal(shape,stddev=0.1)#生成一个截断的正态分布
return tf.Variable(inital)
#初始化偏置值
def bias_variable(shape):
inital = tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(inital)
#卷积层
def conv2d(x,W):
# x: input a tensor of shape [batch,in_height,in_width,in_channels]
# W: 一个滤波器(卷积核) tensor of shape[filter_height,filter_width,in_channels,out_channels]
#strides[0] = strides[3] == 1 strides[1]代表x方向步长,strides【2】代表y方向的步长
#padding A string from ‘SAME’‘VALID’
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
#池化层
def max_pool_2x2(x):
#ksize: 表示池化窗口2,2表示x和y方向长度
#stride:2,2表示x和y方向的步长
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
#定义两个placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
#改变x的格式为4D的向量[batch,in_height,in_width,in_channels]
x_image = tf.reshape(x,[-1,28,28,1])
#初始化第一个卷积层的权值和偏置
W_conv1 = weight_variable([5,5,1,32])#5*5的采样窗口,32个卷积核从1个平面抽取特征
b_conv1 = bias_variable([32])#每个卷积核一个偏置值
#x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
h_pool1 = max_pool_2x2(h_conv1)#进行max—pooling
#初始化第二个卷积层的权值和偏置
W_conv2 = weight_variable([5,5,32,64])#5*5的采样窗口,32个卷积核从1个平面抽取特征
b_conv2 = bias_variable([64])#每个卷积核一个偏置值
#h_pool1和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
h_pool2 = max_pool_2x2(h_conv2)#进行max—pooling
#28*28的图片第一次卷积后还是28*28
#第一次池化后,变成14*14
#第二次卷积后,变成14*14
#第二次池化后,变成7*7
#通过上面的操作后得到64张7*7的平面图
#初始化第一个全连接层的权值
W_fc1 = weight_variable([7*7*64,1024])#上一场有7*7*64个神经元,全连接层有1024个神经元
b_fc1 = bias_variable([1024])
#把池化层2的输出扁平化为1维
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)
#keep_prob用来表示神经元的输出概率
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
#初始化第二个全连接层
W_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10])
#求第二个全连接层的输出
h_fc2 = tf.nn.relu(tf.matmul(h_fc1_drop,W_fc2) + b_fc2)
#计算输出
prediction = tf.nn.softmax(h_fc2)
#交叉熵代价函数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y,logits=prediction))
#使用AdmOptimizer进行优化
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#结果存放在一个bool列表中
correct_prediction = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(9):
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.7})
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))
结果: