Tensorflow学习笔记(4)-mnist(MultilayerConvolutionalNetwork)

版权声明:博客仅供参考,有什么意见,请在下方留言,转载时请附上链接,谢谢! https://blog.csdn.net/u010105243/article/details/76562120
# -*- coding: utf-8 -*-
# @Time    : 17-8-1 下午9:40
# @Author  : 未来战士biubiu!!
# @FileName: 4-mnist(MultilayerConvolutionalNetwork).py
# @Software: PyCharm Community Edition
# @Blog    :http://blog.csdn.net/u010105243/article/

import tensorflow as tf

# import MNIST data
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data", one_hot=True)

# 构建图结构,这里的x,y_不是确切的值,而是一个palceholder,在我们运行tensorflow时输入
x = tf.placeholder(tf.float32, [None, 784])  # [None,28× 28]第一个参数代表batch_size,第二个参数代表图片的大小
y_ = tf.placeholder(tf.float32, [None, 10])  # 输出预测值有10个

W = tf.Variable(tf.zeros([784, 10]))  # 784*10的mat,因为我们有784的feature和10个输出
b = tf.Variable(tf.zeros([10]))  # 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):
    # 定义卷积操作
    # x和W的参数都要求是4维的张量
    # strides是卷积滑动的窗口的跨度,其中strides[0][3]一般为1,[1][2]为每次滑动的height和weight
    # padding 有两个取值:SAME表示卷积之后的维度与X相同,是宽卷积,VALID则表示窄卷积,结果维度比X小
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


def max_pool_2x2(x):
    # 对卷积之后结果进行pool的层
    # ksize[0]=ksize[3]=1,中间两项为表示pool单元的大小2*2,就是取这四个值的最大值
    # strides是卷积滑动的窗口的跨度
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')


# 第一项的-1,表示任意维度,可以理解为,讲原始748向量转化的时候优先考虑后面的参数,最后剩下多少-1这一项的数值
# 最后一项为通道数目,在黑白图片里面只有为1, RGB图片里面为3
x_image = tf.reshape(x, [-1, 28, 28, 1])

# 第一个卷积层
W_conv1 = weight_variable([5, 5, 1, 32])  # 卷积核为5*5,in_size=1,outsize=32
b_conv1 = bias_variable([32])  # 卷积之后加入偏置,因为输出通道为32,因此偏置也是32
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)  # 原始数据为28*28*1,卷积之后变为28*28*32
h_conv1 = max_pool_2x2(h_conv1)  # pooling层取2*2的矩阵,因此池化之后,height和weight各缩小一般,变为14*14*32

# 第二个卷积层
W_conv2 = weight_variable([5, 5, 32, 64])# 接conv_1layer的h_pooled_1: in_size=32, 这一卷积层继续抽取特征: outsize=64
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_conv1, W_conv2) + b_conv2)# h_pool_1维度为: 14 * 14 *32, 卷积之后变为64通道,因此为:14 * 14 *64
h_pool2 = max_pool_2x2(h_conv2)# 池化层仍为: 2X2的矩阵,得到的为7 * 7 * 64三维特征

W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

# 两个卷积-池化结束之后,后面就是加一个普通的前馈神经网络进行分类,有一点需要注意的就是FNN的输入是向量,因此还需要reshape
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) # 将[7,7,64]的三维特征,转为一维向量 7*7*64,就相当于 flat的过程
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# Dropout
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)# 这里加了drop_out,防止过拟合

# Readout_layer
W_fc2 = weight_variable([1024, 10]) # 隐层-输出层
b_fc2 = bias_variable([10])

y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2

cross_entroy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))# softmax分类
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entroy)

correct_prediction = tf.equal(tf.arg_max(y_conv, 1), tf.arg_max(y_, 1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

with tf.Session() as sess:
    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}))

猜你喜欢

转载自blog.csdn.net/u010105243/article/details/76562120