s
99.12% adam
# -*- coding: UTF-8 -*-
'''
Created on 2017年12月8日
'''
import tensorflow.examples.tutorials.mnist.input_data as input_data
import tensorflow as tf
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #下载并加载mnist数据
x = tf.placeholder(tf.float32,[None, 784]) #图像输入向量,占位符,每一个sample都是784维,none表示有无数个sample
y_ = tf.placeholder(tf.float32, [None,10]) #占位符,每一个sample都是10维(行),因为是one_hot
#初始化权重和偏置项参数
#tf.truncated_normal(shape, mean, stddev) :shape表示生成张量的维度,mean是均值,stddev是标准差。
#正态分布
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev = 0.1) #均值为0 标准差为0.1
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape = shape) #统一值为0.1
return tf.Variable(initial)
def conv2d(x, W): #做卷积,步长为1,same padding same padding 填充型
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x): #2*2的大小做max pooling
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]) #调用权值初始化函数 卷积核5*5 通道1 输出通道32,也就是32个卷积核--第一个卷积层的权重参数
b_conv1 = bias_variable([32]) #调用偏置项初始化函数 共享权重,所以没一个卷积核一个偏执项
#为了用这一层,我们把x变成一个4d向量,其第2、第3维对应图片的宽、高,最后一维代表图片的颜色通
#道数(因为是灰度图所以这里的通道数为1,如果是rgb彩色图,则为3)。
x_image = tf.reshape(x, [-1,28,28,1]) #-1代表有多少就取多少
#我们把x_image和权值向量进行卷积,加上偏置项,然后应用ReLU激活函数,最后进行max pooling。
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1) #特征图越来越小,但通道数越来越多
print h_pool1.get_shape() #用以输出经过第一层卷积处理后的维度 #? 14 14 32 每一个滤波器的参数个数为25
#第二层卷积
W_conv2 = weight_variable([5, 5, 32, 64]) #上一次得到的32个图,现在用64个filter了
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #注意,这个h_pool1现在已经是14*14的了
h_pool2 = max_pool_2x2(h_conv2)
print h_pool2.get_shape() # ? 7 7 64 每一个滤波器的参数个数为25*32
#全连接层 full-connected network
W_fc1 = weight_variable([7 * 7 * 64, 1024]) #也就是有1024个neuron
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) #进行flatten操作,搞成向量
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
print h_fc1.get_shape() # ? 1024
#Dropout
#为了减少过拟合,我们在输出层之前加入dropout。
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
#输出层
#最后,我们添加一个softmax层,就像前面的单层softmax regression一样。
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)) #y_是真实的,y_conv是CNN的输出
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy) #梯度下降法 ,learning rate 0.001
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) #正确率
#训练和评估模型
#我们会用更加复杂的ADAM优化器来做梯度最速下降,在feed_dict中加入额外的参数keep_prob来控制dropout比例。
#然后每100次迭代输出一次日志。
sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables()) #初始化所有参数
for i in range(10000):
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}) #在训练的时候,搞dropout,这里出错了,不应该缩进来
print "test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})