Tensorboard 可视化好帮手 2
制作输入源
import tensorflow as tf
import numpy as np
x_data= np.linspace(-1, 1, 300, dtype=np.float32)[:,np.newaxis]
noise= np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data= np.square(x_data) -0.5+ noise
在 layer 中为 Weights, biases 设置变化图表
添加一个参数 n_layer,用来标识层数
用变量 layer_name 代表其每层的名称
tf.summary.histogram用来绘制图片, 第一个参数是图表的名称, 第二个参数是图表要记录的变量
def add_layer(inputs ,
in_size,
out_size,n_layer,
activation_function=None):
## add one more layer and return the output of this layer
layer_name='layer%s'%n_layer
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) # tensorflow >= 0.12
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1,out_size])+0.1, name='b')
tf.summary.histogram(layer_name + '/biases', biases) # Tensorflow >= 0.12
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) # Tensorflow >= 0.12
return outputs
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)
设置loss的变化图
loss是在tesnorBorad 的scalars下面的, 因为使用tf.summary.scalar() 方法.
with tf.name_scope('loss'):
loss= tf.reduce_mean(tf.reduce_sum(
tf.square(ys- prediction), reduction_indices=[1]))
# tf.scalar_summary('loss',loss) # tensorflow < 0.12
tf.summary.scalar('loss', loss) # tensorflow >= 0.12
给所有训练图合并
tf.summary.merge_all()方法会对所有的 summaries 合并到一起
sess= tf.Session()
# merged= tf.merge_all_summaries() # tensorflow < 0.12
merged = tf.summary.merge_all() # tensorflow >= 0.12
# writer = tf.train.SummaryWriter('logs/', sess.graph) # tensorflow < 0.12
writer = tf.summary.FileWriter("logs/", sess.graph) # tensorflow >=0.12
sess.run(tf.global_variables_initializer()) # 替换成这样就好
训练数据
for i in range(1000):
sess.run(train_step, feed_dict={xs:x_data, ys:y_data})
if i%50 == 0:
rs = sess.run(merged,feed_dict={xs:x_data,ys:y_data})
writer.add_summary(rs, i)
Last updated