tensorflow笔记(五)之MNIST手写识别系列二

tensorflow笔记(五)之MNIST手写识别系列二

版权声明:本文为博主原创文章,转载请指明转载地址

http://www.cnblogs.com/fydeblog/p/7455233.html

前言

  • 这篇博客将用tensorflow实现CNN卷积神经网络去训练MNIST数据集,并测试一下MNIST的测试集,算出精确度。
  • 由于这一篇博客需要要有一定的基础,基础部分请看前面的tensorflow笔记,起码MNIST手写识别系列一CNN初探要看一下,对于已经讲过的东西,不会再仔细复述,可能会提一下。还有一件事,我会把jupyter notebook放在这个百度云链接里,方便你下载调试,密码是5dx9

实践

首先先导入我们需要的模块

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

然后导入MNIST数据集

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

运行后如图则导入成功:

MNIST数据集的导入不清楚的地方请看here,接下来我们定义两个函数,分别是生成权重和偏差的函数

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)

说明:

  • 权重在初始化时应该加入少量的噪声(偏差stddev=0.1)来打破对称性以及避免0梯度。由于我们使用的是ReLU神经元,因此比较好的做法是用一个较小的正数来初始化偏置项,以避免神经元节点输出恒为0的问题(dead neurons)。为了不在建立模型的时候反复做初始化操作,我们定义两个函数用于初始化。

接下来建立conv2dmax_pool_2X2这两个函数

def conv2d(x, W):
    # stride [1, x_movement, y_movement, 1]
    # Must have strides[0] = strides[3] = 1
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    # stride [1, x_movement, y_movement, 1]
    #ksize  [1,pool_op_length,pool_op_width,1]
    # Must have ksize[0] = ksize[3] = 1
    return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')

说明:

  • conv2d函数的输入参数是要进行卷积的图片x和卷积核W,函数内部strides是卷积核步长的设定,上面已进行标注,x轴,y轴都是每隔一个像素移动的,步长都为1,padding是填充的意思,这里是SAME,意思是卷积后的图片与原图片一样,有填充。
  • max_pool_2X2函数的输入参数是卷积后的图片x,ksize是池化算子,由于是2x2max_pool,所以长度和宽度都为2,x轴和y轴的步长都为2,有填充。

接下来我们用占位符定义一些输入,有图片集的输入xs,相应的标签ys和dropout的概率keep_prob

xs = tf.placeholder(tf.float32, [None, 784])  # 28x28
ys = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32)

由于我们要进行卷积,为了符合tf.nn.conv2d和tf.nn.max_pool_2x2的输入图片需为4维tensor,我们要对xs做一个reshape,让它符合要求

x_image = tf.reshape(xs, [-1, 28, 28, 1])  # [n_samples, 28,28,1]

说明:

  • x_image是四维张量,分别是[batch, height, width, channels],batch要看上面xs第一维,长和宽为28,通道由于是灰度图片,所以是1,RGB为3

接下来,我们开始构造卷积神经网络,先进行第一层的卷积层和第一层的池化层

## conv1 layer ##
W_conv1 = weight_variable([5,5, 1,32]) # patch 5x5, in size 1, out size 32
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28x28x32
##pool1 layer##
h_pool1 = max_pool_2x2(h_conv1)                          # output size 14x14x32

说明:

  • 卷积核的大小是5x5的,由于输入size1,输出32,可见有32个不同的卷积核,然后将W_conv1与x_image送入conv2d函数后加入偏差,最后外围加上RELU函数,RELU函数是相比其他函数(sigmiod)好很多,使用它,迭代速度会很快,因为它的大于0的导数恒等于1,而sigmiod的导数有可能会很小,趋近于0,我们在进行反向传播迭代参数更新时,如果这个导数太小,参数的更新就会很慢。

为了得到更高层次的特征,我们需要构建一个更深的网络,再加第二层卷积层和第二层池化层,原理与上面一样

## conv2 layer ##
W_conv2 = weight_variable([5,5, 32, 64]) # patch 5x5, in size 32, out size 64
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 14x14x64
##pool2_layer##
h_pool2 = max_pool_2x2(h_conv2)                          # output size 7x7x64

好了,特征提取出来了,我们开始用全连通层进行预测,在建立之前,我们需要对h_pool2进行维度处理,因为神经网络的输入并不能是4维张量。

h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])  # [n_samples, 7, 7, 64] ->> [n_samples, 7*7*64]

说明:

  • 上面将4维张量,变为2维张量,第一维是样本数,第二维是输入特征,可见输入神经元的个数是7*7*64=3136

全连通层开始,先从7*7*64映射到1024个隐藏层神经元

# fc1 layer ##
W_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
#dropout 
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

说明:

  • 这个跟传统的神经网络一样,但和前面见的有点不同,这里最后加了dropout,防止神经网络过拟合

然后再加一个全连通层,进行1024神经元到10个神经元的映射,最后加一个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)

说明:

  • 这个跟上面原理一样,加了一个softmax,不懂softmax请看往期的笔记或看链接中的wiki

然后我们开始算交叉熵和train_step

cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),reduction_indices=[1]))       # loss
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

说明:

  • 不同之前的,这里用到了AdamOptimizer优化器,由于这个计算量很大,用GradientDescentOptimizer优化器下降速度太慢,所以用AdamOptimizer
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

上面是套路了,不用多说了,下面再建立一个测量测试集精确度的函数,后面会用到

def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
    correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})
    return result

说明:

  • 函数的输入是测试集的图片v_xs和相应的标签v_ys,global prediction让prediction代表前面的预测值,不这么做下一行会出错,显示找不到prediction,测试的时候不加dropout,即keep_prob等于1,后面的跟上一篇笔记一样。最后返回精确度

好了,所有的工作准备完毕,现在开始训练和测试,每训练50次,测试一次,这个时间会有点长,要耐心等待

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
    if i % 50 == 0:
        print(compute_accuracy(mnist.test.images, mnist.test.labels))

运行结果如下:

感慨:终于运行完了,这段程序大概跑了四十多分钟,电脑一直处于崩溃状态,感慨还是有gpu好哦,最后精确度是97.37%,我感觉还能再提高,没有完全收敛,你们可以再多迭代试试。我是不想在电脑跑这种程序,要跑到gpu服务器上跑,各位跑程序要有心理准备哈

完整代码如下(直接运行即可):

 1 import tensorflow as tf
 2 from tensorflow.examples.tutorials.mnist import input_data
 3 # number 1 to 10 data
 4 mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
 5 
 6 def compute_accuracy(v_xs, v_ys):
 7     global prediction
 8     y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
 9     correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
10     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
11     result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})
12     return result
13 
14 def weight_variable(shape):
15     initial = tf.truncated_normal(shape, stddev=0.1)
16     return tf.Variable(initial)
17 
18 def bias_variable(shape):
19     initial = tf.constant(0.1, shape=shape)
20     return tf.Variable(initial)
21 
22 def conv2d(x, W):
23     # stride [1, x_movement, y_movement, 1]
24     # Must have strides[0] = strides[3] = 1
25     return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
26 
27 def max_pool_2x2(x):
28     # stride [1, x_movement, y_movement, 1]
29     #ksize  [1,pool_op_length,pool_op_width,1]
30     # Must have ksize[0] = ksize[3] = 1
31     return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
32 
33 # define placeholder for inputs to network
34 xs = tf.placeholder(tf.float32, [None, 784])    # 28x28
35 ys = tf.placeholder(tf.float32, [None, 10])
36 keep_prob = tf.placeholder(tf.float32)
37 x_image = tf.reshape(xs, [-1, 28, 28, 1])
38 # print(x_image.shape)  # [n_samples, 28,28,1]
39 
40 ## conv1 layer ##
41 W_conv1 = weight_variable([5,5, 1,32]) # patch 5x5, in size 1, out size 32
42 b_conv1 = bias_variable([32])
43 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # output size 28x28x32
44 h_pool1 = max_pool_2x2(h_conv1)                          # output size 14x14x32
45 
46 ## conv2 layer ##
47 W_conv2 = weight_variable([5,5, 32, 64]) # patch 5x5, in size 32, out size 64
48 b_conv2 = bias_variable([64])
49 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # output size 14x14x64
50 h_pool2 = max_pool_2x2(h_conv2)                          # output size 7x7x64
51 
52 ##flat h_pool2##
53 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])  # [n_samples, 7, 7, 64] ->> [n_samples, 7*7*64]
54 
55 ## fc1 layer ##
56 W_fc1 = weight_variable([7*7*64, 1024])
57 b_fc1 = bias_variable([1024])
58 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
59 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
60 
61 ## fc2 layer ##
62 W_fc2 = weight_variable([1024, 10])
63 b_fc2 = bias_variable([10])
64 prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
65 
66 cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
67                                               reduction_indices=[1]))       # loss
68 train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
69 
70 init = tf.global_variables_initializer()
71 
72 sess = tf.Session()
73 
74 sess.run(init)
75 
76 for i in range(1000):
77     batch_xs, batch_ys = mnist.train.next_batch(100)
78     sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
79     if i % 50 == 0:
80         print(compute_accuracy(mnist.test.images, mnist.test.labels))

结尾

MNIST数据集的识别到这里就结束了,希望看过这个博客的朋友们能有所收获!最后,还是那句话,笔者能力有限,如果有错误,还请不吝指教,共同学习!谢谢!

参考

[1] https://www.tensorflow.org/versions/r1.0/api_docs/python/

[2] http://www.tensorfly.cn/tfdoc/tutorials/mnist_pros.html

 

 

posted @ 2017-08-30 20:50 FANG_YANG 阅读(...) 评论(...) 编辑 收藏