新闻资讯

新闻资讯 行业动态

TensorBoard的基本使用以及name_scope和variable_scope的区别

编辑:008     时间:2020-02-29

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

一、入门TensorBoard

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

  • https://www.bilibili.com/video/av35203293?from=search&seid=6605552834229124959

为了更方便 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.] 

参考资料:

  • https://www.zhihu.com/question/54513728

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


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



原文链接:https://my.oschina.net/u/3777556/blog/3039621

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

回复列表

相关推荐