首先认识下tensorflow cnn的API
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)
- 第一个参数input:指需要做卷积的输入图像,它要求是一个Tensor,具有[batch, in_height, in_width, in_channels]这样的shape,具体含义是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数],注意这是一个4维的Tensor,要求类型为float32和float64其中之一
- 第二个参数filter:相当于CNN中的卷积核,它要求是一个Tensor,具有[filter_height, filter_width, in_channels, out_channels]这样的shape,具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数],要求类型与参数input相同,有一个地方需要注意,第三维in_channels,就是参数input的第四维
- 第三个参数strides:卷积时在图像每一维的步长,这是一个一维的向量,长度4,一般情况下[1,x,x,1],batch和channels是1
- 第四个参数padding:string类型的量,只能是"SAME","VALID"其中之一
- VALID:
- SAME:
- 第五个参数:use_cudnn_on_gpu:bool类型,是否使用cudnn加速,默认为true
- 结果返回一个Tensor,这个输出,就是我们常说的feature map
tf.nn.max_pool(value, ksize, strides, padding, name=None)
- 第一个参数value:需要池化的输入,一般池化层接在卷积层后面,所以输入通常是feature map,依然是[batch, height, width, channels]这样的shape
- 第二个参数ksize:池化窗口的大小,取一个四维向量,一般是[1, height, width, 1],因为我们不想在batch和channels上做池化,所以这两个维度设为了1
- 第三个参数strides:和卷积类似,窗口在每一个维度上滑动的步长,一般也是[1, stride,stride, 1]
- 第四个参数padding:和卷积类似,可以取'VALID' 或者'SAME'
- 返回一个Tensor,类型不变,shape仍然是[batch, height, width, channels]这种形式
以input和oupt shape的变化来分析整个卷积过程 | ||
---|---|---|
input | filter | output |
图像属性[28,28,1]要转成4维输入[-1,28,28,1] | CONV [5,5,1,6] S=1 P='SAME' | [-1,28,28,6] |
[-1,28,28,6] | maxPool [1,2,2,1] S=2 P='SAME' | [-1,14,14,6] |
[-1,14,14,6] | CONV [5,5,6,16] S=1 P='SAME' | [-1,14,14,16] |
[-1,14,14,16] | maxPool [1,2,2,1] S=2 P='SAME' | [-1,7,7,16] |
[-1,7,7,16] | CONV [5,5,16,120] S=1 P='SAME' | [-1,7,7,120] |
FC1 reshape [-1,7*7*120] | W [7*7*120,80] b [80] | [-1,80] |
[-1,80] | W [80,10] b [10] | [-1,10] |
这里解释下shape中的-1,其实这个-1是一个自动求值,在输入一个batch大小不确定时,知道shape的其他维度大小,程序会自动推断出-1位置维度的大小,并且在CNN的说明时,也知道input的第一个维度是指batch的大小
mnist图像大小是28*28 黑白图像,channels=1
x = tf.placeholder('float',[None,784])
CNN输入是图像的形式,这里要reshape,已知height,weight,channels,那么可以将batch_size = -1
x_image = tf.reshape(x,[-1,28,28,1])
conv1 = tf.nn.conv2d(x_image,filter1,strides=[1,1,1,1],padding='SAME')
获得batch_size大小,然后feed_dict给x
bach_xs,batch_ys = mnist_data_set.train.next_batch(200)
sess.run(train_step,feed_dict={x: bach_xs,y_: batch_ys})
- 完整代码
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import time
mnist_data_set = input_data.read_data_sets('D:/Tensorflow/ronny-git-master/tf-tutorials/4_CNN/MNIST_data', one_hot=True)
x = tf.placeholder('float',[None,784])
y_ = tf.placeholder('float',[None,10])
x_image = tf.reshape(x,[-1,28,28,1])
filter1 = tf.Variable(tf.truncated_normal([5,5,1,6]))
bias1 = tf.Variable(tf.truncated_normal([6]))
conv1 = tf.nn.conv2d(x_image,filter1,strides=[1,1,1,1],padding='SAME')
h_conv1 = tf.nn.sigmoid(conv1+bias1)
maxPool2 = tf.nn.max_pool(h_conv1,ksize=[1,2,2,1],strides=[1, 2, 2, 1],padding='SAME')
filter2 = tf.Variable(tf.truncated_normal([5,5,6,16]))
bias2 = tf.Variable(tf.truncated_normal([16]))
conv2 = tf.nn.conv2d(maxPool2,filter2,strides=[1,1,1,1],padding='SAME')
h_conv2 = tf.nn.sigmoid(conv2+bias2)
maxPool3 = tf.nn.max_pool(h_conv2,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
filter3 = tf.Variable(tf.truncated_normal([5,5,16,120]))
bias3 = tf.Variable(tf.truncated_normal([120]))
conv3 = tf.nn.conv2d(maxPool3,filter3,strides=[1,1,1,1],padding='SAME')
h_conv3 = tf.nn.sigmoid(conv3+bias3)
h_pool3_flat = tf.reshape(h_conv3,[-1,7*7*120])
w_fc1 = tf.Variable(tf.truncated_normal([7*7*120,80]))
b_fc1 = tf.Variable(tf.truncated_normal([80]))
h_fc1 = tf.nn.sigmoid(tf.matmul(h_pool3_flat,w_fc1) + b_fc1)
w_fc2 = tf.Variable(tf.truncated_normal([80,10]))
b_fc2 = tf.Variable(tf.truncated_normal([10]))
y_conv = tf.nn.softmax(tf.matmul(h_fc1,w_fc2) + b_fc2)
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
train_step = tf.train.GradientDescentOptimizer(0.001).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"))
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
start_time = time.time()
for i in range(20000):
bach_xs,batch_ys = mnist_data_set.train.next_batch(200)
sess.run(train_step,feed_dict={x: bach_xs,y_: batch_ys})
if i%100==0 :
train_accuracy = sess.run(accuracy,feed_dict={x: bach_xs,y_: batch_ys})
print("step %d, training accuracy %g" % (i, train_accuracy))
end_time = time.time()
print('time: ', (end_time - start_time))
start_time = end_time
准确率
step 19700, training accuracy 0.99
time: 0.9129998683929443
step 19800, training accuracy 0.99
time: 1.003000020980835
step 19900, training accuracy 0.995
time: 0.9170000553131104