0%

MNIST 3.cnn实现

  • 该模型是tensorflow官方文档的第二个模型,使用了cnn卷积网络
  • 该技术源于最早的lenet模型,细分计算过程,算上输入和输出,过程可分为卷积、池化、卷积、池化、全联接,总共七层。

卷积是用一个卷积核(比二维图像更小的一个二维数组)去扫一遍(就是矩阵积运算)图像,卷积计算可以提取带有卷积核的特征图像

池化是放大原图像局部特征,如3*3的像素值数组,突出最大像素值,清零其他像素值。达到放大特征,类似数据清洗,也可以减少计算量

全联接就是把图像值输出到结果值的万能公式y = wx+b得到输出的过程

  • 该模型正确率约为99.2%

image

各层原理暂不详说,代码中有详细注释,先放两个传送门去多了解吧:

以下是MNIST代码实现(注意最好当前文件夹下有MNIST_data这个本地包可以免去下载):

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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./MNIST_data/",one_hot=True)

sess = tf.InteractiveSession()
#交互式session,可以边构建运算图边执行sess,如果是普通session,需要构建完整的运算图后才可以运行sess

x = tf.placeholder('float',[None,784])
y_= tf.placeholder('float',[None,10])

W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

sess.run(tf.initialize_all_variables())

y = tf.nn.softmax(tf.matmul(x,W)+b)
cross_entropy = -tf.reduce_sum(y_*tf.log(y))

##1.参数初始化
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)

##2.卷积层和池化层

def conv2d(x,W):
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')

def max_pool_2_2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')

##3.第一层

W_conv1 = weight_variable([5,5,1,32])
#[5,5,1,32]表示为卷积核为5*5,卷积输入为1,输出为32(32个卷积核)
b_conv1 = bias_variable([32])

x_image = tf.reshape(x,[-1,28,28,1])
#最后一维是通道数,这里是灰度图所以为1

h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
#[-1,28,28,1]用[5,5,1,32]卷积,得到图片28*28*32(因为有32个卷积核所以有32个特征图),具体为[-1,28,28,32]
h_pool1 = max_pool_2_2(h_conv1)
#池化,池化步长x和y轴都是2,所以图片缩小一半得到14*14*32,即[-1,14,14,32]

##4.第二层

W_conv2 = weight_variable([5,5,32,64])
#[5,5,1,32]表示为卷积核为5*5,卷积输入通道为32,输出通道为64
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
#[-1,14,14,32]被[5,5,32,64]卷积32个通道输出为64个通道(卷积核),具体为[-1,14,14,64]
h_pool2 = max_pool_2_2(h_conv2)
#池化后图片数据量减一半,最终为1024个特征向量[-1,7,7,64]

##5.全连接层

W_conv3 = weight_variable([7*7*64,1024])#[4096,1024]
b_conv3 = bias_variable([1024])

h_conv3_flat = tf.reshape(h_pool2,[-1,7*7*64])
#[-1,7,7,64]reshape为[-1,7*7*64]
h_conv3_fc1 = tf.nn.relu(tf.matmul(h_conv3_flat,W_conv3)+b_conv3)
#[-1,7*7*64]*[7*7*64,1024]+[1014]

##6.dropout防止过拟合
keep_prob = tf.placeholder('float')
h_conv3_drop = tf.nn.dropout(h_conv3_fc1,keep_prob)

##7.输出

W_output = weight_variable([1024,10])
b_output = bias_variable([10])

y_conv = tf.nn.softmax(tf.matmul(h_conv3_drop,W_output)+b_output)
#[-1,1024]*[1024,10]+[10]

##8.评估模型

cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))

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, "float"))

sess.run(tf.initialize_all_variables())
for i in range(20000):
batch = mnist.train.next_batch(50)
if i%1000 == 0:
train_accuracy = accuracy.eval(feed_dict={
x:batch[0], y_: batch[1], keep_prob: 1.0})
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}))


最终准确率:
image