import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据
mnist = input_data.read_data_sets('./MNIST_data', one_hot=True)
#每个批次的大小
batch_size = 50
#计算一共多少个批次
n_batch = mnist.train.num_examples // batch_size
#参数概要
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)
#命名空间
with tf.name_scope('input'):
#定义两个placeholder
x = tf.placeholder(tf.float32, [None, 784], name='x-input')
y = tf.placeholder(tf.float32, [None, 10], name='y-input')
with tf.name_scope('layer'):
# 创建一个简单的神经网络
with tf.name_scope('weights'):
W = tf.Variable(tf.zeros([784,10]))
variable_summaries(W)
with tf.name_scope('biases'):
B = tf.Variable(tf.zeros([10]))
variable_summaries(B)
with tf.name_scope('wx_plus_b'):
wx_plus_b = tf.matmul(x, W) + B
with tf.name_scope('softmax'):
prediction = tf.nn.softmax(wx_plus_b)
with tf.name_scope('cost'):
# 交叉熵代价函数
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
tf.summary.scalar('cost', cost)
with tf.name_scope('train'):
#使用梯度下降
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cost)
#初始化变量
init = tf.global_variables_initializer()
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
#准确率
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(prediction,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(init)
writer = tf.summary.FileWriter('./logs/', sess.graph)
for epoch in range(51):
for batch in range(n_batch):
batchx, batchy = mnist.train.next_batch(batch_size)
summary,_ = sess.run([merged, train_step], feed_dict={x:batchx, y:batchy})
writer.add_summary(summary, epoch)
acc = sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels})
print('Iter' + str(epoch) + ', Testing Accuracy' + str(acc))
通过 tf.summary.scalar() 函数可以将网络的参数命名并记录下来,便于通过tensorboard进行可视化,代码中将cost,Weights和Bias全都记录下来了,最后通过 tf.summary.merge_all() 函数将所有的记录下来的参数进行整合。
最后,通过Tensorflow1学习-3 tensorboard使用
链接中的tensorboard的使用方法,在浏览器中可视化网络的变化。