主要分为导入数据部分、构建CNN部分。
导入数据需要声明占位符
784个输入节点,10个输出节点
x = tf.placeholder(tf.float32, [None, 784]) #输入的数据占位符
y_actual = tf.placeholder(tf.float32, shape=[None, 10]) #输入的标签占位符
定义四个函数,分别用于初始化权值W,初始化偏置项b, 构建卷积层和构建池化层。
#定义一个函数,用于初始化所有的权值 W
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)#生成正态分布的随机值
return tf.Variable(initial)
#定义一个函数,用于初始化所有的偏置项 b
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)#生成值为0.1的常数
return tf.Variable(initial)
#定义一个函数,用于构建卷积层
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
#定义一个函数,用于构建池化层
def max_pool(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
使用到tensorflow中的函数为
tf.truncated_normal(shape, stddev=0.1)
tf.constant(0.1, shape=shape)
tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
详细解释见下篇点击打开链接
接下来构建网络。整个网络由两个卷积层(包含激活层和池化层),一个全连接层,一个dropout层和一个softmax层组成。
由于采用的是minist数据集,是一个784个像素值的一维数组。需要转换为28x28 的图片,示意图:
第一级卷积池化之后,卷积核为5x5,将depth=1的原图转化为14x14,depth=32的map。
#构建网络
x_image = tf.reshape(x, [-1,28,28,1]) #转换输入数据shape,784个像素值的一维数组。需要转换为28x28 的图片
W_conv1 = weight_variable([5, 5, 1, 32]) #5x5,输入通道为1 输出通道为32
b_conv1 = bias_variable([32]) #32维
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) #第一个卷积层 输出为28x28x32
h_pool1 = max_pool(h_conv1) #第一个池化层 输出为14x14x32
W_conv2 = weight_variable([5, 5, 32, 64]) #5x5,输入通道为32 输出通道为64
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #第二个卷积层 输出为14x14x64
h_pool2 = max_pool(h_conv2) #第二个池化层 输出为7x7x64
W_fc1 = weight_variable([7 * 7 * 64, 1024]) #生成行为7x7x64,列为1024的矩阵
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) #reshape成一维向量,将size为7x7,64张map生成一维的7x7x64的行向量
#全连接层
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) #第一个全连接层,输出为1x1,1024个特征map
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) #dropout层 对卷积结果执行dropout操作,减少过拟合
#输出层 使用softmax计算概率进行分类,最后一层网络 输入1024个节点输出为10个节点 1024->10
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_predict=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) #softmax层
#下面是代码,添加了详细注释:
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
mnist = input_data.read_data_sets ( "MNIST_data/", one_hot=True ) # 读取图片数据集
sess = tf.InteractiveSession ( ) # 创建 session
# 一,函数声明部分
def weight_variable ( shape ) :
# 正态分布,标准差为 0.1,默认最大为 1,最小为 -1,均值为 0
initial = tf.truncated_normal ( shape, stddev=0.1 )
return tf.Variable ( initial )
def bias_variable ( shape ) :
# 创建一个结构为 shape 矩阵也可以说是数组 shape 声明其行列,初始化所有值为 0.1
initial = tf.constant ( 0.1, shape=shape )
def conv2d ( x, W ) :
# 卷积遍历各方向步数为 1,SAME:边缘外自动补 0,遍历相乘
return tf.nn.conv2d ( x, W, strides= [ 1, 1, 1, 1 ] , padding='SAME' )
def max_pool_2x2 ( x ) :
# 池化卷积结果(conv2d)池化层采用 kernel 大小为 2*2,步数也为 2,周围补 0,取最大值。数据量缩小了 4 倍
return tf.nn.max_pool ( x, ksize= [ 1, 2, 2, 1 ] ,strides= [ 1, 2, 2, 1 ] , padding='SAME' )
# 二,定义输入输出结构
# 声明一个占位符,None 表示输入图片的数量不定,28*28 图片分辨率
xs = tf.placeholder ( tf.float32, [ None, 28*28 ] )
# 类别是 0-9 总共 10 个类别,对应输出分类结果
ys = tf.placeholder ( tf.float32, [ None, 10 ] )
keep_prob = tf.placeholder ( tf.float32 )
# x_image 又把 xs reshape 成了 28*28*1 的形状,因为是灰色图片,所以通道是 1. 作为训练时的 input,-1 代表图片数量不定
x_image = tf.reshape ( xs, [ -1, 28, 28, 1 ] )
# 三,搭建网络 , 定义算法公式,也就是 forward 时的计算
## 第一层卷积操作 ##
# 第一二参数值得卷积核尺寸大小,即 patch,第三个参数是图像通道数,第四个参数是卷积核的数目,代表会出现多少个卷积特征图像;
W_conv1 = weight_variable ( [ 5, 5, 1, 32 ] )
# 对于每一个卷积核都有一个对应的偏置量。
b_conv1 = bias_variable ( [ 32 ] )
# 图片乘以卷积核,并加上偏执量,卷积结果 28x28x32
h_conv1 = tf.nn.relu ( conv2d ( x_image, W_conv1 ) + b_conv1 )
# 池化结果 14x14x32 卷积结果乘以池化卷积核
h_pool1 = max_pool_2x2 ( h_conv1 )
## 第二层卷积操作 ##
# 32 通道卷积,卷积出 64 个特征
w_conv2 = weight_variable ( [ 5,5,32,64 ] )
# 64 个偏执数据
b_conv2 = bias_variable ( [ 64 ] )
# 注意 h_pool1 是上一层的池化结果,# 卷积结果 14x14x64
h_conv2 = tf.nn.relu ( conv2d ( h_pool1,w_conv2 ) +b_conv2 )
# 池化结果 7x7x64
h_pool2 = max_pool_2x2 ( h_conv2 )
# 原图像尺寸 28*28,第一轮图像缩小为 14*14,共有 32 张,第二轮后图像缩小为 7*7,共有 64 张
## 第三层全连接操作 ##
# 二维张量,第一个参数 7*7*64 的 patch,也可以认为是只有一行 7*7*64 个数据的卷积,第二个参数代表卷积个数共 1024 个
W_fc1 = weight_variable ( [ 7*7*64, 1024 ] )
# 1024 个偏执数据
b_fc1 = bias_variable ( [ 1024 ] )
# 将第二层卷积池化结果 reshape 成只有一行 7*7*64 个数据 # [ n_samples, 7, 7, 64 ] ->> [ n_samples, 7*7*64 ]
h_pool2_flat = tf.reshape ( h_pool2, [ -1, 7*7*64 ] )
# 卷积操作,结果是 1*1*1024,单行乘以单列等于 1*1 矩阵,matmul 实现最基本的矩阵相乘,不同于 tf.nn.conv2d 的遍历相乘
# 自动认为是前行向量后列向量
h_fc1 = tf.nn.relu ( tf.matmul ( h_pool2_flat, W_fc1 ) + b_fc1 )
# dropout 操作,减少过拟合,其实就是降低上一层某些输入的权重 scale,甚至置为 0,
# 升高某些输入的权值,甚至置为 2,防止评测曲线出现震荡,个人觉得样本较少时很必要
# 使用占位符,由 dropout 自动确定 scale,也可以自定义,比如 0.5,根据 tensorflow
# 文档可知,程序中真实使用的值为 1/0.5=2,也就是某些输入乘以 2,同时某些输入乘以 0
keep_prob = tf.placeholder ( tf.float32 )
h_fc1_drop = tf.nn.dropout ( f_fc1,keep_prob ) # 对卷积结果执行 dropout 操作
## 第四层输出操作 ##
# 二维张量,1*1024 矩阵卷积,共 10 个卷积,对应我们开始的 ys 长度为 10
W_fc2 = weight_variable ( [ 1024, 10 ] )
b_fc2 = bias_variable ( [ 10 ] )
# 最后的分类,结果为 1*1*10 softmax 和 sigmoid 都是基于 logistic 分类算法,
# 一个是多分类一个是二分类
y_conv=tf.nn.softmax ( tf.matmul ( h_fc1_drop, W_fc2 ) + b_fc2 )
# 四,定义 loss ( 最小误差概率 ) ,选定优化优化 loss,
cross_entropy = -tf.reduce_sum ( ys * tf.log ( y_conv ) ) # 定义交叉熵为 loss 函数
train_step = tf.train.DradientDescentOptimizer ( 0.5 ) .minimize ( cross_entropy ) # 调用优
# 化器优化,其实就是通过喂数据争取 cross_entropy 最小化
# 五,开始数据训练以及评测
correct_prediction = tf.equal ( tf.argmax ( y_conv,1 ) , tf.argmax ( ys,1 ) )
accuracy = tf.reduce_mean ( tf.cast ( correct_prediction, tf.float32 ) )
tf.global_variables_initializer ( ) .run ( )
for i in range ( 20000 ) :
batch = mnist.train.next_batch ( 50 )
if i%100 == 0:
train_accuracy = accuracy.eval ( feed_dict={x:batch [ 0 ] , ys: batch [ 1 ] , keep_prob: 1.0} )
print ( "step %d, training accuracy %g"% ( i, train_accuracy ) )
train_step.run ( feed_dict={x: batch [ 0 ] , ys: batch [ 1 ] , keep_prob: 0.5} )
print ( "test accuracy %g"%accuracy.eval ( feed_dict={x: mnist.test.images, ys: mnist.test.labels, keep_prob: 1.0} ) )
参考文献
手把手教你用 TensorFlow 实现卷积神经网络(附代码)
tensorflow学习笔记五:mnist实例--卷积神经网络(CNN)