tensorflow教程学习三深入MNIST

来源:互联网 发布:长城宽带 端口转发 编辑:程序博客网 时间:2024/05/16 09:07

讲解链接:http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_pros.html

#载入数据from tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets('MNIST_data', one_hot=True)#我们使用InteractiveSession类可以更加灵活地构建代码#它能让你在运行图的时候,插入一些计算图,这些计算图是由某些操作(operations)构成的。import tensorflow as tfsess = tf.InteractiveSession()#为输入图像和目标输出类别创建节点来开始构建计算图x = tf.placeholder("float", shape=[None, 784])y_ = tf.placeholder("float", shape=[None, 10])W = tf.Variable(tf.zeros([784,10]))b = tf.Variable(tf.zeros([10]))sess.run(tf.initialize_all_variables())#我们把向量化后的图片x和权重矩阵W相乘,加上偏置b,然后计算每个分类的softmax概率值。y = tf.nn.softmax(tf.matmul(x,W) + b)#可以很容易的为训练过程指定最小化误差用的损失函数,我们的损失函数是目标类别和预测类别之间的交叉熵。cross_entropy = -tf.reduce_sum(y_*tf.log(y))#用最速下降法让交叉熵下降,步长为0.01.train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)#每一步迭代,我们都会加载50个训练样本,然后执行一次train_step,#并通过feed_dict将x 和 y_张量占位符用训练训练数据替代。for i in range(1000):  batch = mnist.train.next_batch(50)  train_step.run(feed_dict={x: batch[0], y_: batch[1]})#首先让我们找出那些预测正确的标签。tf.argmax 是一个非常有用的函数,#它能给出某个tensor对象在某一维上的其数据最大值所在的索引值。由于标签向量是由0,1组成,#因此最大值1所在的索引位置就是类别标签,比如tf.argmax(y,1)返回的是模型对于任一输入x预测到的标签值,#而tf.argmax(y_,1)代表正确的标签,我们可以用tf.equal来检测我们的预测是否真实标签匹配(索引位置一样表示匹配)。  correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))#这里返回一个布尔数组。为了计算我们分类的准确率,我们将布尔值转换为浮点数来代表对、错,然后取平均值。#例如:[True, False, True, True]变为[1,0,1,1],计算出平均值为0.75。accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))print (accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))#权重初始化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_2x2(x):  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],                        strides=[1, 2, 2, 1], padding='SAME')#第一层卷积#卷积在每个5x5的patch中算出32个特征。卷积的权重张量形状是[5, 5, 1, 32],#前两个维度是patch的大小,接着是输入的通道数目,最后是输出的通道数目。W_conv1 = weight_variable([5, 5, 1, 32])#对于每一个输出通道都有一个对应的偏置量b_conv1 = bias_variable([32])#为了用这一层,我们把x变成一个4d向量,其第2、第3维对应图片的宽、高,最后一维代表图片的颜色通道数#(因为是灰度图所以这里的通道数为1,如果是rgb彩色图,则为3)。x_image = tf.reshape(x, [-1,28,28,1])#把x_image和权值向量进行卷积,加上偏置项,然后应用ReLU激活函数,最后进行max poolingh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)h_pool1 = max_pool_2x2(h_conv1)#第二层卷积#把几个类似的层堆叠起来。第二层中,每个5x5的patch会得到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)#密集连接层#现在,图片尺寸减小到7x7,我们加入一个有1024个神经元的全连接层,用于处理整个图片。#我们把池化层输出的张量reshape成一些向量,乘上权重矩阵,加上偏置,然后对其使用ReLUW_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)#为了减少过拟合,我们在输出层之前加入dropoutkeep_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_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))#用更加复杂的ADAM优化器来做梯度最速下降,在feed_dict中加入额外的参数keep_prob来控制dropout比例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, "float"))sess.run(tf.initialize_all_variables())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}))

最后附一张结果图,可以看出准确率上升速度很快
这里写图片描述

原创粉丝点击