TensorFlow练习2-CNNs实现分类

上一次主要是使用最简单的前馈神经网络,来对mnist数据进行了分类,测试正确率可以达到94-95%,这一节主要使用TensorFlow来实现卷积神经网络(CNN), 正确率可以到99%了,这已经接近最高了。 另外这一篇不记录CNN的原理以及训练方式,等段时间在整理。

同前一篇NN,首先定义几个参数:

1
2
3
4
# 图像的维度 28*28 ->784
x_img = 28
y_img = 28
n_classes = 10

接下来定义几个函数,方便使用,一些注释说明,在代码中说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def weight_variable(shape):
# 初始化卷积核的权重参数,一般使用高斯正太分布随机值
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial, name="W")
def bias_variable(shape):
# 定义卷积操作之后的偏置项,初始化为一个常数即可
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial, name="bias")
def conv2d(x, W):
# 定义卷积操作,直接使用tf的函数即可
# x和W的参数都要求是4维的tensor
# strides是卷积滑动的窗口的跨度,其中strides[0],与strides[3]一般为1, strides[1],strides[2]为每次滑动的height和width
# padding 有两个取值: SAME:表示卷积之后结果的维度与X相同,是宽卷积,VALID则表示窄卷积,结果维度比X小。
return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding="SAME", name="conv2d")
def max_pool(x):
# 对卷积之后结果进行pool的层
# ksize 是取多大的块作为pool的单元,一般ksize[0] = ksize[3] =1, 中间两项为表示pool单元为2X2,就是取这四个值的最大值
# strides 和 padding 与上述卷积操作含义相同
return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME", name="pooled")

然后开始构造CNN的输入输出:

1
2
3
xs = tf.placeholder(tf.float32, [None, x_img * y_img]) # shape: 784
ys = tf.placeholder(tf.float32, [None, n_classes]) # 10
keep_prob = tf.placeholder(tf.float32)

这里需要注意的是是tf.nn.conv2d的参数,先看看它的文档:

1
2
3
4
5
6
Signature: tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None)
Docstring:
Computes a 2-D convolution given 4-D `input` and `filter` tensors.
Given an input tensor of shape `[batch, in_height, in_width, in_channels]`
and a filter / kernel tensor of shape
`[filter_height, filter_width, in_channels, out_channels]`

也就说,conv2d的Input的输入是4维的,分别是:

  • batch_size: 数据量,这里表示有几张图片
  • in_height: 输入矩阵的height
  • in_width: 输入矩阵的width
  • in_channels: 输入数据的厚度,也叫通道,在黑白图片里面只有为1, RGB图片里面为3。表示一个data的厚度,卷积的时候,需要一层一层操作。

同样的,卷积核也是4维数据:

  • filter_height: 卷积核的维度-height
  • filter_width: 卷积核的维度-width
  • in_channels: 表示输入数据的通道或者厚度,与input的in_channels保持一致
  • out_channels: 卷积之后的输出的通道数或者厚度,可以理解为 每个卷积单元对输入数据卷积一次,得到一层。out_channels就代表有多少个卷积单元。

卷积层之后,是池化层,主要是对特征进行降维,函数max_pool的参数相对于卷积理解简单些,下面代码中也会给出具体的维度。 因为原始数据是28×28的向量,我们需要reshape之后为[28,28]的矩阵,以便进行卷积乘法:

1
2
3
4
x_image = tf.reshape(xs, [-1, 28,28, 1])
# 第一项的-1,表示任意维度,可以理解为,将原始748的向量转化的时候,优先考虑后面的参数,最后剩下多少就是-1这一项的数值
# 比如在这里在-1这一项就是: batch_size * 748 / 28 /28 /1 = batch_size, 因此这里表示就为batch_size,
# 第二项的与第三项的表示28 × 28,为图片的矩阵。最后一项的1表示通道数目,用1即可。

下面我们开始构造网络,这里我们构造两个卷积层,以及池化,提取到特征之后,之后再加含有一个隐层的普通前馈神经网络进行分类。 先用TensorFlow构造两个卷积层:

1
2
3
4
5
6
7
8
9
10
11
12
13
# conv_1 layer
with tf.name_scope('conv-layer-1'):
W_conv1 = weight_variable([5,5,1,32]) # 卷积核为5X5,in_size=1, outsize=32 : convolutions units
b_conv1 = bias_variable([32]) # 卷积之后加入偏置,因为输出的通道或者厚度是32,因此偏置也是32
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # image是28*28*1, 经过卷积之后,变为: 28 * 28 * 32
h_pooled_1 = max_pool(h_conv1) # 池化层取得2X2的矩阵,因此池化之后,height和weight各缩小一半,变为14*14*32
# conv_2 layer
with tf.name_scope('conv-layer-2'):
W_conv2 = weight_variable([5,5,32,64]) # 接conv_1layer的h_pooled_1: in_size=32, 这一卷积层继续抽取特征: outsize=64
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pooled_1, W_conv2) + b_conv2) # h_pool_1维度为: 14 * 14 *32, 卷积之后变为64通道,因此为:14 * 14 *64
h_pooled_2 = max_pool(h_conv2) # 池化层仍为: 2X2的矩阵,得到的为7 * 7 * 64三维特征

两个卷积-池化结束之后,后面就是加一个普通的前馈神经网络进行分类,有一点需要注意的就是FNN的输入是向量,因此还需要reshape:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# fnn layer
with tf.name_scope('nn-layer-1'):
W_fun1 = weight_variable([7*7*64, 1024]) # 1024是hidden units,
b_fun1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pooled_2, [-1, 7*7*64]) # 将[7,7,64]的三维特征,转为一维向量 7*7*64,就相当于 flat的过程
h_fun2 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fun1) + b_fun1) #激活函数
h_fun2_drop = tf.nn.dropout(h_fun2, keep_prob) # 这里加了drop_out,防止过拟合
# fnn layer
with tf.name_scope('nn-layer-2'):
W_fun2 = weight_variable([1024, 10]) # 隐层-输出层
b_fun2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fun2_drop, W_fun2) + b_fun2) # softmax分类

到此,CNN基本构造完成,剩下的cost, train, accuracy与普通的fnn一样了,有一点不同的是,这里的优化方式不再使用SGD而是Adam,速度要快一些。 完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python
# encoding: utf-8
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial, name="W")
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial, name="bias")
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding="SAME", name="conv2d")
def max_pool(x):
return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME", name="pooled")
xs = tf.placeholder(tf.float32, [None, 784])
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs, [-1, 28,28, 1])
# conv_1 layer
with tf.name_scope('conv-layer-1'):
W_conv1 = weight_variable([5,5,1,32]) # outsize=32 : convolutions units
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # 28 * 28 * 32
h_pooled_1 = max_pool(h_conv1) # 14*14*32
# conv_2 layer
with tf.name_scope('conv-layer-2'):
W_conv2 = weight_variable([5,5,32,64]) # outsize=64
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pooled_1, W_conv2) + b_conv2) # 14 * 14 *64
h_pooled_2 = max_pool(h_conv2) # 7 * 7 * 64
# func1 layer
with tf.name_scope('nn-layer-1'):
W_fun1 = weight_variable([7*7*64, 1024])
b_fun1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pooled_2, [-1, 7*7*64])
h_fun2 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fun1) + b_fun1)
h_fun2_drop = tf.nn.dropout(h_fun2, keep_prob)
# func2 layer
with tf.name_scope('nn-layer-2'):
W_fun2 = weight_variable([1024, 10])
b_fun2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fun2_drop, W_fun2) + b_fun2)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction)))
train_step = tf.train.AdamOptimizer(1e-04).minimize(cross_entropy)
## accuracy
correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(ys, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
import time
n_epochs = 15
batch_size = 100
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
st = time.time()
for epoch in range(n_epochs):
n_batch = mnist.train.num_examples / batch_size
for i in range(n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob:0.6})
print 'epoch', 1+epoch, 'accuracy:', sess.run(accuracy, feed_dict={keep_prob:1.0, xs: mnist.test.images, ys: mnist.test.labels})
end = time.time()
print '*' * 30
print 'training finish.\ncost time:', int(end-st) , 'seconds;\naccuracy:', sess.run(accuracy, feed_dict={keep_prob:1.0, xs: mnist.test.images, ys: mnist.test.labels})

效果也很好, 仅仅这么简单的结构,迭代了15次,就可以达到99%, 通过调节参数,或许可以更高:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
epoch 1 accuracy: 0.9565
epoch 2 accuracy: 0.9717
epoch 3 accuracy: 0.9788
epoch 4 accuracy: 0.9799
epoch 5 accuracy: 0.9835
epoch 6 accuracy: 0.9856
epoch 7 accuracy: 0.987
epoch 8 accuracy: 0.9899
epoch 9 accuracy: 0.9886
epoch 10 accuracy: 0.9892
epoch 11 accuracy: 0.9903
epoch 12 accuracy: 0.9892
epoch 13 accuracy: 0.9897
epoch 14 accuracy: 0.99
epoch 15 accuracy: 0.9905
******************************
training finish.
cost time: 178 seconds;
accuracy: 0.9905

这一节主要是记录了如何使用TensorFlow写CNN,因为里面的参数困扰了好长时间,因此记录下来加深印象。