该文章在tensorboard上显示训练过程,包括权重、偏置、输出、损失、的变化过程。
相关代码:
from __future__ import print_function
import tensorflow as tf
import numpy as np
def add_layer(inputs, in_size, out_size, n_layer, activation_function=None):
# add one more layer and return the output of this layer
#其中,n_layer表示哪一个神经层的层数,是一个具体的数字。如第一层调用add_layer定义第一层神经层的时
#候,可以吧n_layer写成1,这只是给这个函数多传了一个参数。
layer_name = 'layer%s' % n_layer#神经层的名字,第一层调用add_layer的时候可以命名为layer1
with tf.name_scope(layer_name):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
tf.summary.histogram(layer_name + '/weights', Weights)#在tensorboard中的
#histogram中显示权重的变化
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
tf.summary.histogram(layer_name + '/biases', biases)#在tensorboard中的
#histogram显示偏置的变化过程
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b, )
tf.summary.histogram(layer_name + '/outputs', outputs)
#这个表示在tensorboard显示outputs的变化值,在tensorboard中的histogram中可以显示
return outputs
# Make up some real data
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]#其中,linspace表生成(-1,1)的三百个随机数#据
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise
# define placeholder for inputs to network
with tf.name_scope('inputs'):
xs = tf.placeholder(tf.float32, [None, 1], name='x_input')
ys = tf.placeholder(tf.float32, [None, 1], name='y_input')
# add hidden layer
l1 = add_layer(xs, 1, 10, n_layer=1, activation_function=tf.nn.relu)
# add output layer
prediction = add_layer(l1, 10, 1, n_layer=2, activation_function=None)
# the error between prediciton and real data
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1]))
tf.summary.scalar('loss', loss)#在tensorboard中显示loss的变化过程
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
sess = tf.Session()
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter("logs/", sess.graph)
init = tf.global_variables_initializer()
sess.run(init)
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i % 50 == 0:
result = sess.run(merged,
feed_dict={xs: x_data, ys: y_data})
writer.add_summary(result, i)
# direct to the local dir and run this in terminal:
# $ tensorboard --logdir logs
相关解释:
给所有训练图合并
合并打包。 tf.merge_all_summaries()
方法会对我们所有的 summaries
合并到一起. 因此在原有代码片段中添加:
sess= tf.Session()
merged = tf.summary.merge_all() # 合并summary
writer = tf.summary.FileWriter("logs/", sess.graph) # 打包到logs文件夹中
图像显示:
损失函数值的变化,横坐标表示迭代步数,纵坐标表示损失函数的值。
横坐标表示迭代步数,纵坐标表示权重或偏置的值,颜色深的地方表示在这个值附件概率多一点。