tensorflow识别手写数字(2)

来源:互联网 发布:外贸数据应用 编辑:程序博客网 时间:2024/05/23 15:06

TensorFlow 擅长大规模的计算图模型,它的特长之一就是训练深度神经网络,这篇教程将会使用TensorFlow 构建一个CNN来识别MNIST.

建立CNN

在之前的softmax中我们的准确率只有92%左右,在这里我们使用一个简单的CNN将会把准确率提升至99.2%。

权重初始化

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)

卷积和池化

TensorFlow同样提供了方便的卷积和池化计算。怎样处理边界元素?怎样设置卷积窗口大小?在这个例子中,我们始终使用vanilla版本。这里的卷积操作仅使用了滑动步长为1的窗口,使用0进行填充,所以输出规模和输入的一致;而池化操作是在2 * 2的窗口内采用最大池化技术(max-pooling)。

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')

第一个卷积层

这一层包括一个卷积层和一个最大池化层,对每一个5*5图像都将其卷积为32个特征,它的weight tensor形状为[5,5,1,32] [5,5] 代表patch大小,[1] 代表输入维度,[32] 代表输出维度。

W_conv1 = weight_variable([5, 5, 1, 32])b_conv1 = bias_variable([32])

同时要把x转化为4维的tensor,第2,3维为原来的长和宽,第四维为色彩数。

x_image = tf.reshape(x, [-1,28,28,1])

接下来实施卷积和池化:

h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)h_pool1 = max_pool_2x2(h_conv1)

第二个卷积层

对每个5*5的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)

全连接层

这时图片已经变成7*7大小的了,每个像素点上有64个特征,我们把这个3维的tensor转化为一个向量,再添加一个有1024个神经元的隐藏层作为全连接层。

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

为了避免过拟合使用Dropout方法, 具体的,使用placeholder作为Dropout概率,可以让我们在训练时有Dropout,在测试时关掉Dropout。

keep_prob = tf.placeholder(tf.float32)h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

输出层

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

训练和评价模型

CNN的训练和评价和之前softmax中的差不多,主要区别在于:

  • 使用ADAM进行优化,而不是梯度下降
  • 使用keep_prob 控制Dropout率
  • 每训练一百次输出日志(因为CNN训练相对较慢,打印日志便于调试)
cross_entropy = tf.reduce_mean(    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))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))sess.run(tf.global_variables_initializer())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}))
0 0