机器学习100天-Day2503 Tensorboard 训练数据可视化(线性回归)

首页.jpg

源代码来自莫烦python(https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/4-1-tensorboard1/)
今日重点

  • 读懂教程中代码,手动重写一遍,在浏览器中获取到训练数据

Tensorboard是一个神经网络可视化工具,通过使用本地服务器在浏览器上查看神经网络训练日志,生成相应的可是画图,帮助炼丹师优化神经网络。
油管上有单迪伦·马内在2017年做的汇报,很惊艳。主要包括了以下主要功能

  • 可视化网络
  • 可视化训练过程
  • 多模型效果可视化对比

先看一下教程提供的原始代码(不包括tensorboard构造),就是一个两层(包括输出)的线性回归网络。
因为有了训练的数据,教程使用numpy生成部分模拟数据。

import tensorflow as tf
import numpy as np

#构造模拟数据
x_data=np.linspace(-1,1,300,dtype=np.float32)[:,np.newaxis]
#使用np.random.normal()生成一些噪声
noise=np.random.normal(0,0.05,x_data).astype(np.float32)
y_data=np.square(x_data)-0.5+noise

制作对Weights和biases的变化图表distributions。
我们为层中的Weights设置变化图, tensorflow中提供了tf.histogram_summary()方法,用来绘制图片, 第一个参数是图表的名称, 第二个参数是图表要记录的变量

def add_layer(inputs, in_size, out_size, n_layer,activation_function=None):
    layer_name='layer%s'%n_layer
    with tf.name_scope('layer'):
        # add one more layer and return the output of this layer
        with tf.name_scope('weights'):
            Weights = tf.Variable(tf.random_normal([in_size, out_size]),name='W')
            tf.summary.histogram(layer_name+'/weights',Weights)
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1,name='b')
            tf.summary.histogram(layer_name+'/biases',biases)
        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)
    return outputs
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)

Loss 的变化图和之前设置的方法略有不同. loss是在tesnorBorad 的event下面的, 这是由于我们使用的是tf.scalar_summary() 方法.

with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
    tf.summary.scalar('loss',loss)

以上这些仅仅可以记录很绘制出训练的图表, 但是不会记录训练的数据。 为了较为直观显示训练过程中每个参数的变化,我们每隔上50次就记录一次结果 , 同时我们也应注意, merged 也是需要run 才能发挥作用的.

sess=tf.Session()
merged=tf.summary.merge_all()
writer=tf.summary.FileWriter('./logs/layer2',sess.graph)

sess.run(tf.global_variables_initializer())

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

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)
image.png

image.png

image.png

你可能感兴趣的:(机器学习100天-Day2503 Tensorboard 训练数据可视化(线性回归))