tensorflow笔记(五)之MNIST手写识别系列二
版权声明:本文为博主原创文章,转载请指明转载地址
http://www.cnblogs.com/fydeblog/p/7455233.html
首先先导入我们需要的模块
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)
说明:
接下来建立conv2d和max_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')
说明:
接下来我们用占位符定义一些输入,有图片集的输入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]
说明:
接下来,我们开始构造卷积神经网络,先进行第一层的卷积层和第一层的池化层
## 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
说明:
为了得到更高层次的特征,我们需要构建一个更深的网络,再加第二层卷积层和第二层池化层,原理与上面一样
## 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]
说明:
全连通层开始,先从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)
说明:
然后再加一个全连通层,进行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)
说明:
然后我们开始算交叉熵和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)
说明:
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
说明:
好了,所有的工作准备完毕,现在开始训练和测试,每训练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/