Tensorflow官方文档学习理解 (五)-卷积MNIST

之前构建的模型在MNIST上只有91%的正确率,有点低,我们尝试一下使用卷积神经网络来改善效果。如果您不是很清楚什么是卷积神经网络的话,可以参考我的这篇文章:链接

权重初始化

在创建模型之前,我们先来创建权重和偏置。一般来说,初始化时应加入轻微噪声,来打破对称性,防止零梯度的问题。因为我们用的是ReLu激活函数,所以用稍微大于0的值来初始化偏置能够避免节点输出恒为0的问题(dead neurons)。为了不在建立模型的时候反复做初始化操作,我们定义两个函数用于初始化。

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在卷积和池化上有很强的灵活性。我们如何处理边界,步长设置多大什么的。在这里我们的卷积使用步长(stride size)为1,边距(padding size)为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")

strides里面的每一量对应Wx上的移动步长,比如strides = [1, 2, 3, 4]批,每次移动batch的个数是1;每次移动in_height的数目是2;每次移动in_width的数目是3;每次移动in_channels的数目是4。当然,每次只应该移动一个量。注意,batch和in_channels一般每次只会移动1。所以一般形式是strides = [1, stride, stride, 1]。得到的结果,包括四个维度[batch, in_height, in_width, in_channels]ksize指对x的四个维度做池化时的大小。如ksize=[1, 2, 2, 1],池化的模板的每次一个batch,一个channel,长为2,宽为2。

padding可以用SAMEVALID两种方式:对于VALID,输出的形状计算如下:

对于SAME,输出的形状计算如下:

现在我们可以开始实现第一层了。它由一个卷积核接一个max pooling完成。卷积在每个5*5的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表示,它的大小信息由其它几组值确定。

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

我们把x_image和权值向量进行卷积相乘,加上偏置,使用ReLu激活函数,最后max pooling。

扫描二维码关注公众号,回复: 3722518 查看本文章
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
h_pool1 = max_pool_2x2(

为了构建一个更深的网络,我们会把几个类似的层堆叠起来,第二层卷积中,我们采用5*5的卷积核,希望得到64个特征。

w_conv2 = weight_variable([5, 5, 32, 64])
b_conv1 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv1)
h_pool2 = max_pool_2x2(h_conv2)

密集连接层

28/2/2=7,现在图片降维到7x7,我们加入一个有1024个神经元的全连接层,用于处理整个图片。我们把池化层输出的张量reshape成一些向量,乘上权重矩阵,加上偏置,使用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

为了减少过拟合,我们在输出层之前加入dropout。我们用一个placeholder来代表一个神经元在dropout中被保留的概率。这样我们可以在训练过程中启用dropout,在测试过程中关闭dropout。Tensorflow的tf.nn.dropout操作会自动处理神经元输出值的scale。所以用dropout的时候不用考虑scale。

keep_prob = tf.placeholder("float")
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 = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(0.0001).minimize(cross_entropy)
correct_prediction = tf.equal(tf.arg_max(y_conv, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
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, train_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}))

全部代码:

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
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")
w_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
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)

w_conv2 = weight_variable([5, 5, 32, 64])
b_conv1 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv1)
h_pool2 = max_pool_2x2(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])
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_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)

cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(0.0001).minimize(cross_entropy)
correct_prediction = tf.equal(tf.arg_max(y_conv, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
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, train_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}))

输出结果如下:

参考:

https://blog.csdn.net/CY_TEC/article/details/52082647

https://blog.csdn.net/wuzqChom/article/details/74785643

猜你喜欢

转载自blog.csdn.net/weixin_39059031/article/details/82851513
今日推荐