Machine Learning & Recommendation & NLP & DL机器学习100天

机器学习100天-Day2502 Tensorboard 图可视

2019-02-11  本文已影响0人  我的昵称违规了
首页.jpg
源代码来自莫烦python(https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/4-1-tensorboard1/)
今日重点

先看一下教程提供的原始代码(不包括tensorboard构造),就是一个两层(包括输出)的线性回归网络。

from __future__ import print_function
import tensorflow as tf


def add_layer(inputs, in_size, out_size, activation_function=None):
    # add one more layer and return the output of this layer
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    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, )
    return outputs


xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])

# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)
# add output layer
prediction = add_layer(l1, 10, 1, activation_function=None)
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

要让神经网络中的每一个元素在可视化界面中显示,就需要对图和参数进行命名,需要修改两个部分

隐藏层

def add_layer(inputs, in_size, out_size, activation_function=None):
    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]))
        with tf.name_scope('biases'):
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
        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, )
    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')

损失函数和训练

with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

最后是保存数据

writer = tf.summary.FileWriter("logs/", sess.graph)

完成之后,在pycharm的Terminal中输入‘tensorboard --logdir=/Users/01/Desktop/机器学习作业/sklearn+tensorflow/logs’,然后再chrome中输入‘http://localhost:6006’即可查看整个神经网络可视化结果,注意,因为没有数据的输入,现在仅能查看神经网络的结构。

01.png
上一篇 下一篇

猜你喜欢

热点阅读