46

什么是TensorBoard?

 5 years ago
source link: https://segmentfault.com/a/1190000018930265?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前言

只有光头才能变强。

文本已收录至我的GitHub仓库,欢迎Star: https://github.com/ZhongFuCheng3y/3y

回顾前面:

这篇文章主要讲讲TensorBoard的基本使用以及 name_scope和variable_scope 的区别

一、入门TensorBoard

首先来讲讲TensorBoard是什么吧,我当时是在官方文档里学习的,官网也放出了介绍TensorBoard的视频。我在b站搜了一把,发现也有,大家可以 先去 看看视频了解一下(其实已经说得很好了):

为了更方便 TensorFlow 程序的理解、调试与优化,于是就有了TensorBoard 这样的的 可视化工具

因为我们编写出来的TensorFlow程序,建好一个神经网络,其实我们也不知道神经网络里头 具体细节 到底做了什么, 要人工调试十分困难 (就好比你无法想象出递归的所有步骤一样)。有了TensorBoard,可以将TensorFlow程序的执行步骤都显示出来,非常直观。并且,我们可以对 训练的参数 (比如loss值)进行统计,用 的方式来查看变化的趋势。

1.1 name_scope和variable_scope

在视频中其实也有提到,我们想要TensorBoard的图能够更好地展示(更加有条理),那一般我们需要对其用 name_scope 取名。

那除了 name_scope ,还有一个叫做 variable_scope 。那他们有什么区别呢?顾名思义, name_scope 是一个名称作用域, variable_scope 是变量作用域。

在前面文章中,创建变量有两种方式,一种是用 tf.get_variable() 来创建,一种是用 tf.Variable() 来创建。这两种创建方式也是有区别的。

  • tf.name_scope 下时, tf.get_variable() 创建的变量名 不受 name_scope 的影响,而且在未指定共享变量时,如果重名就会报错。 tf.Variable() 会自动检测有没有变量重名,如果有则会自行处理(自动创建一个)

比如下面的代码:

with tf.name_scope('name_sp1') as scp1:
    with tf.variable_scope('var_scp2') as scp2:
        with tf.name_scope('name_scp3') as scp3:
            a = tf.Variable('a')
            b = tf.get_variable('b')

等同于:

with tf.name_scope('name_sp1') as scp1:
    with tf.name_scope('name_sp2') as scp2:
        with tf.name_scope('name_scp3') as scp3:
            a = tf.Variable('a')

with tf.variable_scope('var_scp2') as scp2:
        b = tf.get_variable('b')

这里体现的是如果用 get_variable 的方式来创建对象,是不受 name_scope 所影响的。

要注意的是,下面的代码会报错。因为在scp作用域下压根就没有a这个变量,同时又设置成 reuse=True 。这里因为的是 找不到共享变量而出错

with tf.variable_scope('scp', reuse=True) as scp:
    a = tf.get_varialbe('a') #报错

同样地,下面的代码也会报错,因为明明 已经有 共享变量了,但设置成 reuse=false 。所以就会报错。

with tf.variable_scope('scp', reuse=False) as scp:    
     a = tf.get_varialbe('a')
    a = tf.get_varialbe('a') #报错

最后,我们再来看这个例子,应该就可以看懂了。

with tf.variable_scope('variable_scope_y') as scope:
    var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
    scope.reuse_variables()  # 设置共享变量
    var1_reuse = tf.get_variable(name='var1')
    var2 = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)
    var2_reuse = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(var1.name, sess.run(var1))
    print(var1_reuse.name, sess.run(var1_reuse))
    print(var2.name, sess.run(var2))
    print(var2_reuse.name, sess.run(var2_reuse))
# 输出结果:
# variable_scope_y/var1:0 [-1.59682846]
# variable_scope_y/var1:0 [-1.59682846]   可以看到变量var1_reuse重复使用了var1
# variable_scope_y/var2:0 [ 2.]
# variable_scope_y/var2_1:0 [ 2.]

参考资料:

1.2 TensorBoard例子

下面我们来看一个TensorBoard简单的入门例子,感受一下:

def learn_tensor_board_2():
    # prepare the original data
    with tf.name_scope('data'):
        x_data = np.random.rand(100).astype(np.float32)
        y_data = 0.3 * x_data + 0.1
    ##creat parameters
    with tf.name_scope('parameters'):
        with tf.name_scope('weights'):
            weight = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
            tf.summary.histogram('weight', weight)
        with tf.name_scope('biases'):
            bias = tf.Variable(tf.zeros([1]))
            tf.summary.histogram('bias', bias)
    ##get y_prediction
    with tf.name_scope('y_prediction'):
        y_prediction = weight * x_data + bias
    ##compute the loss
    with tf.name_scope('loss'):
        loss = tf.reduce_mean(tf.square(y_data - y_prediction))
        tf.summary.scalar('loss', loss)
    ##creat optimizer
    optimizer = tf.train.GradientDescentOptimizer(0.5)
    # creat train ,minimize the loss
    with tf.name_scope('train'):
        train = optimizer.minimize(loss)
    # creat init
    with tf.name_scope('init'):
        init = tf.global_variables_initializer()
    ##creat a Session
    sess = tf.Session()
    # merged
    merged = tf.summary.merge_all()
    ##initialize
    writer = tf.summary.FileWriter("/Users/zhongfucheng/tensorboard/loss-2", sess.graph)
    sess.run(init)
    ## Loop
    for step in range(201):
        sess.run(train)
        rs = sess.run(merged)
        writer.add_summary(rs, step)


if __name__ == '__main__':
    learn_tensor_board_2()
    # 启动完了之后,要在命令行上运行tensor_board的命令,指定其目录,最后我们就可以通过6006的默认端口访问我们的图。

(例子来源网络,我改动了一下,出处我忘了,侵删~)

接下来,我们启动一下TensorBoard,看看图是怎么样的,启动命令如下:

tensorboard --logdir=/Users/zhongfucheng/tensorboard/loss-2

启动成功的图:

FNjiyiJ.jpg!web

通过6006端口我们去访问一下,首先我们可以检测到loss值的变更:

qiauamR.jpg!web

我们也可以查看TensorFlow程序大概的执行步骤:

bUzuQvV.jpg!web

参数w和b的直方图:

JRniQzv.jpg!web

总之,TensorBoard可以方便地查看我们参数的变化,以便更好理解我们写的代码。

参考资料:

最后

乐于输出 干货 的Java技术公众号:Java3y。公众号内有200多篇 原创 技术文章、海量视频资源、精美脑图,不妨来 关注 一下!

6bUJZvv.jpg!web

觉得我的文章写得不错,不妨点一下


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK