上一个阶段构造的简单模型训练后,只有91%正确率。本文章讲解如何用一个稍微复杂的模型:卷积神经网络来提升效果。
下面是效果图:
具体的步骤为:
首先完成准备工作:
import input_data
import tensorflow as tf
#导入数据
mnist = input_data.read_data_sets('MNIST_data', one_hot = True)
#设置占位符和输入数据的格式
x = tf.placeholder("float", shape = [None, 784])
y = tf.placeholder("float' shape = [None, 10])
#784=>>28*28, 最后一维代表图片的颜色通道数,这里是灰度图为1,如果是rgb彩色图,则为3.
x_image = tf.reshape(x, [-1,28,28,1]) #
定义权重初始化函数
在初始化W和b时应该加入少量的噪声来打破对称性以及避免0梯度。为了不在建立模型的时候反复做初始化操作,定义两个函数用于初始化:
#其实现在的W就是卷积核(filters),是不断学习的参数
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev = 0.1) # 从正态分布中取样,stddev表示标准差
return tf.Variable(initial)
def bias_variable(shaple):
initial = tf.constant(0.1, shape = shape)
return tf.Variable(initial)