美文网首页
TensorFlow学习之mnist代码实例(四)

TensorFlow学习之mnist代码实例(四)

作者: zhglance | 来源:发表于2019-12-09 17:29 被阅读0次

代码实战(带说明注释):

import tensorflow as tf
# import tensorflow.examples.tutorials.mnist.input_data as input_data
from tensorflow.examples.tutorials.mnist import input_data

# 下载和读取mnist数据
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 占位符,每行有784数据
x = tf.placeholder(tf.float32, [None, 784])
y_actual = tf.placeholder(tf.float32, shape=[None, 10])  # 输入的标签占位符,即0~9


# 初始化权值
def weight_variable_initial(shape):
    # 截尾正态分布随机数组,张量的维度:shape,平均值:mean,标准差为stddev,随机种子:seed,取值范围为:[ mean - 2 * stddev, mean + 2 * stddev ]
    weight_initial = tf.truncated_normal(shape, mean=0, stddev=0.1, dtype=tf.float32, seed=None, name="weight_variable")

    # sess = tf.Session()
    # with sess.as_default():
    #     print("weight_variable_initial:", weight_initial.eval())
        # 生成变量
    return tf.Variable(weight_initial)


# 初始化偏置项
def bias_variable_initial(shape):
    # 定义常量
    initial = tf.constant(value=0.1, dtype=None, shape=shape, name="bias_variable")

    # sess = tf.Session()
    # with sess.as_default():
    #     print("bias_variable:", initial.eval())
    #     # 生成变量
    return tf.Variable(initial)


# 构建卷积层
def conv2d(x, W):
    '''
      输入张量:input 张量为为 [ batch, in_height, in_weight, in_channel ],
     其中batch为图片的数量,
     in_height 为图片高度,
     in_weight 为图片宽度,
     in_channel 为图片的通道数,灰度图该值为1,彩色图为3。


     卷积核:filter,也是一个张量
     shape为 [ filter_height, filter_weight, in_channel, out_channels ],
     其中 filter_height 为卷积核高度,
     filter_weight 为卷积核宽度,
     in_channel 是图像通道数

     strides 卷积时在图像每一维的步长,这是一个一维的向量,
     [ 1, strides, strides, 1],第一位和最后一位固定必须是1


     padding string类型,值为“SAME” 和 “VALID”
     表示的是卷积的形式,是否考虑边界。
     "SAME"是考虑边界,不足的时候用0去填充周围,"VALID"则不考虑


     use_cudnn_on_gpu
     bool类型,是否使用cudnn加速,默认为true

    '''

    return tf.nn.conv2d(input=x, filter=W, strides=[1, 1, 1, 1], padding='SAME', use_cudnn_on_gpu=None, name="conv2d")


# 构建池化层
def max_pool(x):
    '''
    value:
      需要池化的输入,一般池化层接在卷积层后面,所以输入通常是feature map,
      依然是[batch_size, height, width, channels]这样的shape

      ksize:
      池化窗口的大小,取一个四维向量,一般是[1, height, width, 1]

      strides:
       窗口在每一个维度上滑动的步长,一般也是[1, stride,stride, 1]

       padding:
    padding string类型,值为“SAME” 和 “VALID”
     表示的是卷积的形式,是否考虑边界。
     "SAME"是考虑边界,不足的时候用0去填充周围,"VALID"则不考虑
    '''

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


# 构建网络
'''将tensor变换为shape的形式
shape为一个列表形式,特殊的一点是列表中可以存在-1。
-1代表的含义是不用我们自己指定这一维的大小,
函数会自动计算,但列表中只能存在一个-1。

28 * 28 = 784

'''
x_image = tf.reshape(tensor=x, shape=[-1, 28, 28, 1],name="x_image")  # 转换shape
W_conv1 = weight_variable_initial([5, 5, 1, 32])
b_conv1 = bias_variable_initial([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)  # 第一个卷积层
h_pool1 = max_pool(h_conv1)  # 第一个池化层

W_conv2 = weight_variable_initial([5, 5, 32, 64])
b_conv2 = bias_variable_initial([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)  # 第二个卷积层
h_pool2 = max_pool(h_conv2)  # 第二个池化层

W_fc1 = weight_variable_initial([7 * 7 * 64, 1024])
b_fc1 = bias_variable_initial([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])  # reshape成向量
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)  # dropout层

W_fc2 = weight_variable_initial([1024, 10])
b_fc2 = bias_variable_initial([10])
y_predict = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)  # softmax层

cross_entropy = -tf.reduce_sum(y_actual * tf.log(y_predict))  # 交叉熵
train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy)  # 梯度下降法
correct_prediction = tf.equal(tf.argmax(y_predict, 1), tf.argmax(y_actual, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))  # 精确度计算
sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())
for i in range(50000):
    batch = mnist.train.next_batch(50)
    if i % 1000 == 0:  # 训练1000次,验证一次
        train_acc = accuracy.eval(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 1.0})
        print('loop:', i, 'current accuracy:', train_acc)
        train_step.run(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.5})

test_acc = accuracy.eval(feed_dict={x: mnist.test.images, y_actual: mnist.test.labels, keep_prob: 1.0})
print("last accuracy", test_acc)

输出结果:

Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz

loop: 1000 current accuracy: 0.14
 
loop: 2000 current accuracy: 0.2
 
loop: 3000 current accuracy: 0.26
 
loop: 4000 current accuracy: 0.54
 
loop: 5000 current accuracy: 0.7
 
loop: 6000 current accuracy: 0.7
 
loop: 7000 current accuracy: 0.82
 
loop: 8000 current accuracy: 0.78
 
loop: 9000 current accuracy: 0.88
 
loop: 10000 current accuracy: 0.94
 
loop: 11000 current accuracy: 0.92
 
loop: 12000 current accuracy: 0.94
 
loop: 13000 current accuracy: 0.88

loop: 14000 current accuracy: 0.9

loop: 15000 current accuracy: 0.92

loop: 16000 current accuracy: 0.92

loop: 17000 current accuracy: 0.94 

loop: 18000 current accuracy: 0.9 

last accuracy 0.9401

相关文章

网友评论

      本文标题:TensorFlow学习之mnist代码实例(四)

      本文链接:https://www.haomeiwen.com/subject/dxkigctx.html