为了学习CNN神经网络,从官网上把示例代码抄了下来,先从读懂开始。
源代码
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
import matplotlib.pyplot as plt
import numpy as np
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)
#定义一个函数,用于构建卷积层
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
#定义一个函数,用于构建池化层
def max_pool(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
mnist=input_data.read_data_sets("F:\py_practice\py_jupyter\MNIST_data/",
one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
y_actual = tf.placeholder(tf.float32, shape=[None, 10])
x_image=tf.reshape(x,[-1,28,28,1]) #数据的占位符
w_conv1=weight_variable([5,5,1,32]) #标签的占位符
b_conv1=bias_variable([32])
h_conv1=tf.nn.relu(conv2d(x_image,w_conv1)+b_conv1)#第一个卷积层
h_pool1=max_pool(h_conv1)
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #第二个卷积层
h_pool2 = max_pool(h_conv2)
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) #reshape成向量
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_predict=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) #softmax层
cross_entropy = -tf.reduce_sum(y_actual*tf.log(y_predict)) #交叉熵
train_step = tf.train.AdamOptimizer(1e-3).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_predict,1), tf.argmax(y_actual,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
#sess=tf.Session()
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for i in range(20000):
batch = mnist.train.next_batch(100)
if i%500 == 0: #训练500次,验证一次
train_acc = accuracy.eval(feed_dict={x:batch[0], y_actual: batch[1], keep_prob: 1.0})
print( 'step %d, training accuracy %g'%(i,train_acc))
train_step.run(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.7})
test_acc=accuracy.eval(feed_dict={x: mnist.test.images, y_actual: mnist.test.labels, keep_prob: 1.0})
sess.close()
print ("test accuracy %g"%test_acc)
说明一下,我的电脑上相对路径有一点问题,所以使用的绝对路径。相对路径应该鲁棒性强一点。
首先是定义一些函数
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)
#定义一个函数,用于构建卷积层
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
#定义一个函数,用于构建池化层
def max_pool(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
mnist=input_data.read_data_sets("F:\py_practice\py_jupyter\MNIST_data/",
one_hot=True)
一些具体的参数
- tf.truncated_normal中的stddev是正态分布的标准差。
- tf.nn.conv2d中的strides,可以理解为卷积核移动的步长
- tf.nn.conv2d中的padding:string类型的量,只能是"SAME","VALID"其中之一,这个值决定了不同的卷积方式
- pooling有两种,一种是最大值池化,一种是平均值池化,我采用的是最大值池化tf.max_pool()。池化的核函数大小为2*2,因此ksize=[1,2,2,1],步长为2,因此strides=[1,2,2,1]。
数据的输入
x = tf.placeholder(tf.float32, [None, 784])
y_actual = tf.placeholder(tf.float32, shape=[None, 10])
x_image=tf.reshape(x,[-1,28,28,1])
使用placeholder占位符,定义数据类型和数据格式。reshape是将输入数据转换成指定格式,-1的意思是暂定不管。
第一层的建立
w_conv1=weight_variable([5,5,1,32]) #标签的占位符
b_conv1=bias_variable([32])
h_conv1=tf.nn.relu(conv2d(x_image,w_conv1)+b_conv1)#第一个卷积层
h_pool1=max_pool(h_conv1)
- [5,5,1,32]的意思是卷积核大小为5×5,单通道,输出的通道为32.
- 因为输出是32通道,所以偏置量的size也是32
- max_pool是最大值的池化准则。
第一层的用处就是将输入的单通道图片输出为32个不同特征的图片
第二个卷积层
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #第二个卷积层
h_pool2 = max_pool(h_conv2)
同样,先是进行卷积,然后进行激活函数,最后池化一下。
输入为32通道,输出64通道。
全连接层
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) #reshape成向量
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
这个层是输出一个1×1×X的张量。从其它人的博客学了一下全连接的意义,总结一下。
-
卷积取的是局部特征,全连接就是把以前的局部特征重新通过权值矩阵组装成完整的图。
-
因为用到了所有的局部特征,所以叫全连接。
-
全连接层之前的作用是提取特征,全连接层的作用是分类
全连接层的理论学习效率非常高,可以解决复杂的模型,但同时缺点就是,容易造成过拟合,以及运算速度降低等问题。
softmax层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_predict=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) #softmax层
softmax 可以理解为归一化,如目前图片分类有一百种,那经过 softmax 层的输出就是一个一百维的向量。向量中的第一个值就是当前图片属于第一类的概率值,向量中的第二个值就是当前图片属于第二类的概率值…这一百维的向量之和为1.
这些层中的参数选取很重要,学习率,dropout,标准差等关键参数更是十分敏感,稍有变更就可能导致结果不收敛,大家可以在经验参数的基础上进行小规模的改动,达到最好效果。