MNIST tensorflow官方卷积网络示例

来源:互联网 发布:淘宝优惠券名称怎么写 编辑:程序博客网 时间:2024/06/06 14:19

导入MNIST数据

import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

创建占位符,存放输入的mini-batch训练集,784是图像展开的维度(28*28),10是分类的类数,是一个one-hot向量

x = tf.placeholder(tf.float32, [None, 784])y_ = tf.placeholder(tf.float32, [None, 10])

定义变量weight_variable,卷积层中即卷积核,初始为均值0,标准差0.1的截断正态分布

def weight_variable(shape):    initial = tf.truncated_normal(shape, stddev=0.1)    return tf.Variable(initial)

定义变量bias_variable,即偏置, 初始为0.1的常量张量

def bias_variable(shape):    initial = tf.constant(0.1, shape=shape)    return tf.Variable(initial)

定义卷积操作

关于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_movement,y_movement, 1]
  • padding:string类型的量,只能是”SAME”,”VALID”其中之一,这个值决定了不同的卷积方式边距处理,“SAME”表示输出图层和输入图层大小保持不变,设置为“VALID”时表示舍弃多余边距(丢失信息)

结果返回一个Tensor,这个输出,就是我们常说的feature map

def conv2d(x, W):  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

定义最大池化操作

关于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]这种形式

def max_pool_2x2(x):    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

将输入mini-batch图像扩展到4维,即[batch, in_height, in_width, in_channels]的shape,以进行卷积操作

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

指定第一层卷积核的shape,即[filter_height, filter_width, in_channels, out_channels],以进行卷积操作

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

指定第一层的偏置shape

b_conv1 = bias_variable([32])

使用ReLU激活函数,由于边距保持不变,输出batch*28*28*32的张量

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

池化,图像尺寸减半,输出batch*14*14*32的张量

h_pool1 = max_pool_2x2(h_conv1)

第二层网络,最后输出batch*7*7*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)

第一层全连接层,加入1024个神经元的全连接层,输出batch*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,避免过拟合

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

第二层全连接层,softmax输出层,输出为batch*10的张量

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优化器来做梯度最速下降

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

启动Session并初始化变量

sess = tf.Session()sess.run(tf.initialize_all_variables())

开始迭代,在feed_dict中加入额外的参数keep_prob来控制dropout比例

for i in range(20000):    batch = mnist.train.next_batch(50)    if i % 100 == 0:        train_accuracy = accuracy.eval(session = sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})        print ('step %d, training accuracy %g' % (i, train_accuracy))    sess.run(train_step, feed_dict = {x: batch[0], y_: batch[1], keep_prob: 0.5})

使用测试集计算准确率,显存不够,仅用200幅测试图

print ('test accuracy %g' % accuracy.eval(session = sess, feed_dict={x: mnist.test.images[0:200,:], y_: mnist.test.labels[0:200,:], keep_prob: 1.0}))
1 0
原创粉丝点击