tensorboard - 第二讲

前言

  • tf.histogram_summary()方法,用来绘制图片, 第一个参数是图表的名称, 第二个参数是图表要记录的变量
  • tf.summary.scalar('loss', loss) loss 在 SCALARS中显示
  • tf.summary.merge_all() 方法会对我们所有的 summaries 合并到一起
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import tensorflow as tf 
import numpy as np 

# n_layer 识别层数 -> 在 layer 中为 Weights, biases 设置变化图表用到
def add_layer(inputs, in_size, out_size, n_layer, activation_function = None):
    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')    
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name = 'b') # 保证 biases 不为 0    
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
        if activation_function == None:
            outputs = Wx_plus_b
        else:
            outputs = activation_function(Wx_plus_b)
            
    tf.summary.histogram(layer_name + '/Weights', Weights)
    tf.summary.histogram(layer_name + '/biases', biases)
    tf.summary.histogram(layer_name + '/outputs', outputs)
    return outputs

# 认为制造点数据,为了更加真实引入 noise
x_data = np.linspace(-1, 1, 300, dtype = np.float32) #(300,)
x_data = x_data.reshape(300,1) # (300, 1)

noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise

# 为 batch 做准备
with tf.name_scope('input'):
    xs = tf.placeholder(tf.float32, [None, 1], name = 'x_in')
    ys = tf.placeholder(tf.float32, [None, 1], name = 'y_in')

# 隐藏层
l1 = add_layer(xs, 1, 10, n_layer = 1, activation_function = tf.nn.relu)
# 输出层
prediction = add_layer(l1, 10, 1, n_layer = 2, activation_function = None)

# 观看loss的变化比较重要. 当你的loss呈下降的趋势,说明你的神经网络训练是有效果的.
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), 1))
    tf.summary.scalar('loss', loss)

with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

# 只要使用 tf.Variable, 就必须全局初始化
init = tf.global_variables_initializer()


# 训练
with tf.Session() as sess:
    sess.run(init)
    merged = tf.summary.merge_all()
    writer = tf.summary.FileWriter("E:/tensorflowe/graph", sess.graph)     
    for step in range(1000):
        sess.run(train_step, feed_dict = {xs: x_data, ys: y_data})
        if step % 50 == 0:
            # print('loss = ', sess.run(loss, feed_dict = {xs: x_data, ys: y_data}))
            rs = sess.run(merged, feed_dict = {xs: x_data, ys: y_data})
            writer.add_summary(rs, step)

writer.close()
tensorboard - 第二讲_第1张图片
tensor流

tensorboard - 第二讲_第2张图片
loss显示

tensorboard - 第二讲_第3张图片
weight,biases, output直方图

tensorboard - 第二讲_第4张图片

你可能感兴趣的:(tensorboard - 第二讲)