import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/2017/python/',one_hot=True)
#还不是太理解InteractiveSession(),要比Session()更方便些,启动session之前,不需要构建整个计算图
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32,shape=[None,784])
y_ = tf.placeholder(tf.float32,shape=[None,10])
#定义两个函数,用于W和b的初始化操作,权重加入少量噪声打破对称性以避免0梯度,
#用较小的正数初始化偏置,避免神经元节点输出恒为0
def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial)
#tf.truncated_normal(shape, mean, stddev) : 产生正态随机分布
#shape表示生成张量的维度,mean是均值,stddev是标准差
def bias_variable(shape):
initial = tf.constant(0.1,shape=shape)
return tf.Variable(initial)
#定义卷积网络,x为输入,W为卷积核,步长stride为1,边界补0
def conv2d(x,W):
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
#定义池化操作,池化窗口大小为2x2,步长为2,边界补0
def max_pool_2x2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
#卷积核,大小为5x5,通道为1(只有灰度),32个核,相当于输出为32个通道
W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
#输入为28x28=784个像素点,第一维batch大小为-1,根据“喂给的”数据自定义,第四维chanel通道为1
x_image = tf.reshape(x,[-1,28,28,1])
#把卷积后的输出用relu函数激活,再经过池化2x2,步长为2操作,输出图片为14x14
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
#第二层网络的参数,卷积核5x5,32个输入通道,64个卷积核(即64个输出)
W_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
#池化后,图片为7x7
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
#全连接层,将第二层池化后的数据变形成一维,与这一维的权重相乘,此时每一行有1024列数据
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)
#为了防止过拟合overfiting,用dropout丢弃一些链接,通过keep_prob参数控制
#训练时,打开dropput,测试时,关闭dropout
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
#输出层,将1024列数据与权重相乘,变成10列,通过softmax处理,对应相应的十个数字的概率值,提取标签
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)
#计算交叉熵,通过AdamOptimizer最小化交叉熵,修改各层的权重和偏置值
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#计算预测精确率
correct_prediction = tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
sess.run(tf.global_variables_initializer())
#一个batch提取50张图片
for i in range(10000):
batch = mnist.train.next_batch(50)
train_step.run(feed_dict={x:batch[0],y_:batch[1],keep_prob:0.5})
if i%500 == 0:
print(i)
print(accuracy.eval(feed_dict={x:batch[0],y_:batch[1],keep_prob:0.5}))
print(accuracy.eval(feed_dict={
x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0}))
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/2017/python/',one_hot=True)
#还不是太理解InteractiveSession(),要比Session()更方便些,启动session之前,不需要构建整个计算图
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32,shape=[None,784])
y_ = tf.placeholder(tf.float32,shape=[None,10])
#定义两个函数,用于W和b的初始化操作,权重加入少量噪声打破对称性以避免0梯度,
#用较小的正数初始化偏置,避免神经元节点输出恒为0
def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial)
#tf.truncated_normal(shape, mean, stddev) : 产生正态随机分布
#shape表示生成张量的维度,mean是均值,stddev是标准差
def bias_variable(shape):
initial = tf.constant(0.1,shape=shape)
return tf.Variable(initial)
#定义卷积网络,x为输入,W为卷积核,步长stride为1,边界补0
def conv2d(x,W):
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
#定义池化操作,池化窗口大小为2x2,步长为2,边界补0
def max_pool_2x2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
#卷积核,大小为5x5,通道为1(只有灰度),32个核,相当于输出为32个通道
W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
#输入为28x28=784个像素点,第一维batch大小为-1,根据“喂给的”数据自定义,第四维chanel通道为1
x_image = tf.reshape(x,[-1,28,28,1])
#把卷积后的输出用relu函数激活,再经过池化2x2,步长为2操作,输出图片为14x14
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
#第二层网络的参数,卷积核5x5,32个输入通道,64个卷积核(即64个输出)
W_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
#池化后,图片为7x7
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
#全连接层,将第二层池化后的数据变形成一维,与这一维的权重相乘,此时每一行有1024列数据
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)
#为了防止过拟合overfiting,用dropout丢弃一些链接,通过keep_prob参数控制
#训练时,打开dropput,测试时,关闭dropout
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
#输出层,将1024列数据与权重相乘,变成10列,通过softmax处理,对应相应的十个数字的概率值,提取标签
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)
#计算交叉熵,通过AdamOptimizer最小化交叉熵,修改各层的权重和偏置值
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#计算预测精确率
correct_prediction = tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
sess.run(tf.global_variables_initializer())
#一个batch提取50张图片
for i in range(10000):
batch = mnist.train.next_batch(50)
train_step.run(feed_dict={x:batch[0],y_:batch[1],keep_prob:0.5})
if i%500 == 0:
print(i)
print(accuracy.eval(feed_dict={x:batch[0],y_:batch[1],keep_prob:0.5}))
print(accuracy.eval(feed_dict={
x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0}))