【Tensorflow 复习3】使用Tensorboard 可视化神经网络

使用TensorFlow的可视化工具 — tensorboard : 通过使用这个工具可以很直观的看到整个神经网络的结构、框架。
以前几节的代码为例:相关代码 通过tensorflow的工具大致可以看到,今天要显示的神经网络差不多是这样子的
在这里插入图片描述

同时我们也可以展开看每个layer中的一些具体的结构:4_1_2.png

1. 通过阅读代码和之前的图片大概知道了此处是有一个输入层(inputs),一个隐含层(layer),还有一个输出层(output) 现在可以看看如何进行可视化.

使用Tensorboard 可视化神经网络最重要的就是名称域with tf.name_scope('scope name'):


def add_layer(inputs, in_size, out_size, activation_function=None):
    with tf.name_scope('layer'):
        with tf.name_scope('Weights'):
            Weights = tf.Variable(tf.random.rand([in_size, out_size]))  # 定义权重
        with tf.name_scope('biase'):
            biases = tf.Variable(tf.zeros([1, in_size]) + 0.1)  # 定义偏置
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b = tf.matmul(inputs, Weights) + biases  # 计算Σ

        # 激活函数选择
        if activation_function is None:
            outputs = Wx_plus_b
        else:
            outputs = activation_function(Wx_plus_b)

        return outputs


# 初始化数据
x_data = np.linspace(-1, 1, 300, dtype=np.float32)[:, np.newaxis]
noise = np.random.rand(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) + noise
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')

# 从输入层到隐含层 ,从隐含层到输出层
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)  # 从输入层(x_data)到隐藏层(l1)
prediction = add_layer(l1, 10, 1, activation_function=None)  # 从隐藏层(l1)到输出层(prediction)

# 计算误差 和 传播误差
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)  # 优化误差

init = tf.gloal_variables_initializer()

2. 我们需要使用 tf.summary.FileWriter() (tf.train.SummaryWriter() 这种方式已经在 tf >= 0.12 版本中摒弃) 将上面‘绘画’出的图保存到一个目录中,以方便后期在浏览器中可以浏览。 这个方法中的第二个参数需要使用sess.graph , 因此我们需要把这句话放在获取session的后面。 这里的graph是将前面定义的框架信息收集起来,然后放在logs/目录下面。

with tf.Session as sess:
    writer = tf.Summary.FileWriter("logs/", sess.graph) #将图片加载到文件夹里面
    for i in range(1000):
        sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
        print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))

3. 最后在你的terminal(终端)中 ,切换到存放该图片的文件夹,使用以下命令

tensorboard --logdir logs

4. 将终端中输出的网址复制到浏览器中,便可以看到之前定义的视图框架了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值