摘要:
基于CNN的Mnist代码详解
- tensorflow.nn.conv2d函数
- strides
- reshape
- tensorflow.nn.max_pool函数
- padding
- 。。。。。。
tensorboard
- tensorboard中的name_scope
- tensorboard中的summary.*
- 将graph加到tensorboard中
- 。。。。。。
- 详解Windows中查看tensorboard页面
- 文件路径
- 解决No dashboards are active for the current data set
老规矩,先给出官网以及apachecn的代码分析,及Github地址,还有YouTube上Google的tensorboard介绍(讲解者是开发者)
官网
apachecn
代码Github地址
TensorBoard
第1、4个链接需要梯子
- 导入一些包
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
- 定义权重以及偏置的初始化函数,简化待会的重复使用
- 权重的shape[filter_height, filter_width, in_channels, out_channels]
# 生成给定形状的权值及偏置变量
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
# 通常,权重在初始化时应该加入少量的噪声来打破对称性以及避免0梯度。由于我们使
#用 ReLU神经元,因此较好的做法是用一个较小的正数来初始化偏置量,以避免神经元节点输出恒为0(dead neurons)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
- 定义TensorBoard概要函数
def variable_summaries(var):
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)#平均值
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev)#标准差
tf.summary.scalar('max', tf.reduce_max(var))#最大值
tf.summary.scalar('min', tf.reduce_min(var))#最小值
tf.summary.histogram('histogram', var)#直方图
- 定义卷积层与池化层
padding 详见:padding操作
def conv2d(x, W):
# tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None)
# padding='SAME'表示适当的用0填充。
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# 给定一个形状为[[batch(输入的数量。-1表示数量不定),in_height,
# in_width,in_channels]]的输入张量x和一个形状为[filter_height,
# filter_width,in_channels,out_channels]的过滤器W,返回的是卷积后的maps
def max_pool_2x2(x):
# ksize是要执行取最值操作的切片(窗口)在各个维度上的尺寸。第一个1不清楚意义。 2 2 1分别表示2*2的pool切片大小,1是通道数
# strides是一个长度为4的一维张量,第2 3位是卷积的横向和纵向步长,第一1表示batch(只能是1把?还能同时多个)和第四个暂不明白其意义
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
再单独解释下’VALID’/‘SAME’:
- 卷积层中:使得输出图像尺寸等于输出图像尺寸与输入图像尺寸相同。比如这里输入尺寸是28*28,5*5的卷积核,如果步长是1,如果是参数是’VALID’,那么输出就是(28-5+1)的24*24尺寸,但是‘SAME’后,输出仍然是28*28
- 池化层中,如果pool切片大小是3*3,‘SAME’操作,(28*28)/(3*3)就会在周围添一圈0,使得能整除,也就是向上取整(Ceiling/⌈⌉)
- deepnn函数构建一个比较深的用于该数据集分类的网络
返回一个元组(y, keep_prob),y是接下来要输入给softmax的那些对应0-9的分类的张量
keep_prob是dropout中的一个参数,比如1.0就是全部神经元参与连接,0.6就是百分之60的神经元参与连接
def deepnn(x):
# Tensorboard中的命名空间,with下的都属于该空间范围
with tf.name_scope('reshape'):
x_image = tf.reshape(x, [-1, 28, 28, 1])
# -1代表任何维度大小;2'3参数是reshape输入的图像大小;最后一个参数是颜色通道数。
- 第一个卷基层与池化层,将输入的灰度图映射到32个feature maps(上接def deepnn(x))
# 给conv1一个命名空间,Tensorboard中,以下张量及op都会在conv1节点下
with tf.name_scope('conv1'):
# 5*5的卷积核,第三个参数也是颜色通道数,最后一个参数是卷积核数量(会提取32个features)
# 得到32个尺寸为24*24的feature maps
W_conv1 = weight_variable([5, 5, 1, 32])
variable_summaries(W_conv1)
b_conv1 = bias_variable([32])
variable_summaries(b_conv1)
# conv2d是TensorFlow中的二维卷积函数
# 把x_image和权值向量进行卷积,加上偏置项,然后应用ReLU激活函数,最后进行max pooling。
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
# 池化层,这里是2*2的最大池化(最大池化保留最显著的特征)
with tf.name_scope('pool1'):
h_pool1 = max_pool_2x2(h_conv1)
- 第二个卷积层与池化层,
with tf.name_scope('conv2'):
# 用64个卷积核对上一卷积层的32个feature maps进行卷积
# 这64个卷积核是随意对之前的32feature maps卷积,并不一定是一对一
W_conv2 = weight_variable([5, 5, 32, 64])
variable_summaries(W_conv2)
b_conv2 = bias_variable([64])
variable_summaries(b_conv2)
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
with tf.name_scope('pool2'):
h_pool2 = max_pool_2x2(h_conv2)
- 全连接层
# 2次降采样后,图像变为28/(2*2)的7*7的尺寸
# 最后一次pool后输出的张量尺寸是7*7*64
with tf.name_scope('fc1'):
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
# reshape将h_pool2的输出转换为一维张量
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机制,控制复杂度,减小模型过拟合的程度
with tf.name_scope('dropout'):
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 1024个features映射到10个分类的得分(之后在用softmax处理)
with tf.name_scope('fc2'):
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
# tf.nn.dropout操作除了可以屏蔽神经元的输出外,还会自动处理神经元输出值的scale。所以用dropout的时候可以不用考虑scale。
return y_conv, keep_prob
到此deepnn函数结束
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
with tf.name_scope('input'):
x = tf.placeholder(tf.float32, [None, 784],name='xinput')
y_ = tf.placeholder(tf.float32, [None, 10],name='y_input')
y_conv, keep_prob = deepnn(x)
with tf.name_scope('loss'):
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_,logits=y_conv))
tf.summary.scalar('loss',cross_entropy)
with tf.name_scope('adam_optimizer'):
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
with tf.name_scope('accuracy'):
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', accuracy)
# 合并所有的summary,之后一起存入磁盘
merged = tf.summary.merge_all()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# 将Tensorboard图像的文件写到磁盘(可以设置绝对路径)
# 在FileWriter的构造函数中加入了sess.graph后,就不需要再使用add_graph函数传递graph了
# 给两个graph,所以打开tensorboard页面后,相关图会有两条线
# 观测可知模型是否适当拟合
train_writer = tf.summary.FileWriter('E:/logs/train', sess.graph)
test_writer = tf.summary.FileWriter('E:/logs/test', sess.graph)
for i in range(2001):
batch_xs,batch_ys = mnist.train.next_batch(50)
# 训练模型
train_step.run(feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})
# 记录训练集计算的参数
train_summary = sess.run(merged,feed_dict={x: batch_xs,y_: batch_ys, keep_prob: 1.0})
# 将summary放进协议缓冲区
train_writer.add_summary(train_summary, i)
# 记录测试集计算的参数
test_batch_xs, test_batch_ys = mnist.test.next_batch(50)
test_summary = sess.run(merged, feed_dict={x: test_batch_xs, y_: test_batch_ys, keep_prob: 1.0})
test_writer.add_summary(test_summary, i)
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict={
x: batch_xs, y_: batch_ys, keep_prob: 1.0})
print('step %d, 训练准确度为 %g' % (i, train_accuracy))
print('最终测试 准确度 %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
代码结束
- 查看保存的graph文件:(该文件是实时更新的)
- 启动tensorboard:
- 如果是Windows,先cmd到相应盘符;然后执行命令:
- tensorboard –logdir=E:/logs(你的文件路径)
- 路径中 最后不加“‘ ”符号。就照着上面的格式写,反正我之前用过:’E:/logs/’、’E:/logs’、’E:\logs\’、’E:\logs’等等都是错的
- 如果提示找不见tensorboard命令,则去把TensorFlow下的Scripts文件路径添加到环境变量。
- 运行后不要关闭命令提示符窗口
- 浏览器输入localhost:6006即可查看tensorboard页面
- 如果文件夹中已有文件,打开localhost:6006后如图:
解决办法:多修改几次你的–logdir=后的文件路径(注意斜杠和‘)
以下是tensorboard相关截图:
- TensorBoard相关界面:(所有内容默认30秒更新一次)
1.GRAPHS概览:(左下角显示有问题,自家产品不兼容?)
可拖动可放大
2.SCALARS概览:
3.DISTRIBUTIONS参数训练过程的分布变化:
4.HISTOGRAMS概览:
详细解读见:
HISTOGRAMS解读
4.相关符号:
5.几种常见的摘要(summary):