TensorFlow+MNIST实例讲解

来源:互联网 发布:小米6陶瓷尊享版 知乎 编辑:程序博客网 时间:2024/05/18 09:06

本人使用的环境是:TensorFlow1.1.0+python3.6+GPU

MNIST数据集:10类,训练库有60,000张手写数字图像,测试库有10,000张。黑白,28*28

模型:CNN,卷积神经网络对图像特征的提取和抽象能力尤为显著

首先导入MNIST数据集

from tensorflow.examples.tutorials.mnist import input_dataimport tensorflow as tfmnist = input_data.read_data_sets("MNIST_data/", one_hot=True)sess = tf.InteractiveSession()
创建权重函数,标准差设为0.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)
创建二维卷积函数,参数x为输入,W为卷积的参数,strides为卷积模板移动的步长,padding为边界的处理方式

def conv2d(x, W):  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
最大池化函数 2*2,最大池化会保留原始像素块中灰度值最高的那一个像素,即保留最显著的特征

def max_pool_2x2(x):  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],                        strides=[1, 2, 2, 1], padding='SAME')  
定义输入的placeholder,x为特征,将1D的输入向量转为2D的图片结构(28*28=784),y_为真实的label,tf.reshape为tensor变形函数,由于只有一个颜色通道,则最终尺寸为[-1,28,28,1],-1为样本数量不固定,1为颜色通道数量

x = tf.placeholder(tf.float32, [None, 784])y_ = tf.placeholder(tf.float32, [None, 10])x_image = tf.reshape(x, [-1,28,28,1])
定义第一个卷积层,卷积核尺寸为5*5,1个颜色通道,32个不同的卷积核
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_2x2(h_conv1)
定义第二个卷积层,卷积核的数量为64,即说明这一层的卷积会提取64种特征
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_2x2(h_conv2)
定义全连接层,前面通过两次步长为2*2的最大池化,则图片尺寸有28*28变成了7*7;而第二个卷积层的卷积核数量为64,其输出的tensor尺寸为7*7*64;tf.reshape函数对第二个卷积层的输出tensor进行变形,将其转成1D的向量,然后连接一个全连接层,隐含节点为1024,并使用ReLU

W_fc1 = weight_variable([7 * 7 * 64, 1024])b_fc1 = bias_variable([1024])h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
Dropout层,通过一个placeholder传入keep_prob比率来控制;在训练时,随机丢弃一部分节点的数据来减轻过拟合,预测时则保留全部数据来追求最好的预测性能

keep_prob = tf.placeholder(tf.float32)h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
Softmax层,得到最后的概率输出

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

定义损失函数cross_entropy,优化器Adam,并给予一个比较小的学习速率le-4

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))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, tf.float32))
开始训练过程:首先初始化参数,设置训练时Dropout的keep_prob比率为0.5;然后使用大小为50的mini-match,共进行20000次训练迭代,参与训练的样本数量总共为100万,其中每100次训练,对准确率进行一次评测

tf.global_variables_initializer().run()for i in range(20000):  batch = mnist.train.next_batch(50)  if i%100 == 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}))

最后,CNN模型得到的准确率为99.19%。依靠卷积核的权值共享,CNN的参数量没有爆炸,降低计算量的同时也减轻了过拟合,因此整个模型的性能有较大的提升。

本人测试的结果如下:


0 0