您的位置:首页 > 编程语言

Tensorflow深度学习入门——采用卷积和池化优化训练MNIST数据——代码+注释

2016-11-24 14:32 861 查看
Tensorflow深度学习入门——采用卷积和池化优化训练MNIST数据——代码+注释

适合入门

# load MNIST data
import input_data
mnist = input_data.read_data_sets("MNIST-data/", one_hot=True)

# start tensorflow interactiveSession
import tensorflow as tf
sess = tf.InteractiveSession() #交互对话

# weight initialization
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)

# convolution 卷积
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# pooling 池化
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

# Create the model
# placeholder
#创建输入图像和输出类别的节点来创建计算题
x = tf.placeholder("float", [None, 784]) #添加一个新的占位符用于输入正确值,这里x,y不代表具体的值
y_ = tf.placeholder("float", [None, 10])
# variables
W = tf.Variable(tf.zeros([784,10]))
#一个Variable代表在计算图中的一个值,他是能在计算过程中被读取和修改的
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x,W) + b)

# first convolutinal layer
#第一层卷积
w_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

x_image = tf.reshape(x, [-1, 28, 28, 1])
#为了用这一层,我们把x变成一个4维向量,第2,3维对应图片的宽高,最后一维代表颜色通道
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
#把x_image和权值向量进行卷积相乘,加上偏置,使用ReLU激活函数,最后max pooling

# second convolutional layer
#第二层卷积:
#为了构建一个更深的网络,我们会把几个类似的层堆叠起来。
#第二层中,每个5*5的patch会得到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)

# densely connected layer
#密集连接层:
#现在图片降到了7*7,我们加入一个有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.fropout操作会自动处理神经元输出值的scale
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# readout layer
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) #送入softmax回归模型,w*x+b,得到输出值

# train and evaluate the model 训练和评估模型
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
#在训练中最小化损失函数 #计算交叉熵 sum(y*log(y))
train_step = tf.train.AdagradOptimizer(1e-4).minimize(cross_entropy) #自适应梯度调节器来做梯度最速下降,调节embedding列表的数据,使得偏差最小
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
#检测我们的预测是否与真实标签匹配
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
#将布尔值转换成浮点值,然后去平均值
sess.run(tf.initialize_all_variables()) #初始化我们创建的所有变量
#variable需要在session之前初始化,才能被session调用

for i in range(20000): #让模型循环训练20000次
batch = mnist.train.next_batch(50)
#在该循环的每个步骤中,都随机抓取训练数据中的100个批处理数据点,然后用这些数据点作为参数替换之前的占位符来运行train_step
if i%100 == 0: #没迭代100次输出一次日志
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_:batch[1], keep_prob:1.0})
#每一次迭代,我们都会加载50个训练数据,然后执行一次train_step,使用feed_dict,用训练数据替换placeholder向量x和y_
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})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  TensorFlow
相关文章推荐