问题 为什么我们使用tf.name_scope()


我一直在阅读他们写过的tensorflow教程

    with tf.name_scope('read_inputs') as scope:
          <insert code here>

我怀疑为什么我们使用name_scope?

    1) a = tf.constant(5)
    2) with tf.name_scope('s1') as scope:
            a = tf.constant(5)

1)和2)都是一样的。那么什么时候使用name_scope创造差异?


3803
2018-03-10 02:15


起源



答案:


它们不是同一件事。

import tensorflow as tf
c1 = tf.constant(42)
with tf.name_scope('s1'):
    c2 = tf.constant(42)
print(c1.name)
print(c2.name)

版画

Const:0
s1/Const:0

顾名思义,范围函数为其创建了一个范围  你在里面创建的操作。这会影响您如何引用张量,重用,图表在TensorBoard中的显示方式等等。


11
2018-03-10 07:24



感谢您的答复。你能告诉我如何重用c1和c2吗? - Vibhor Kanojia
@VibhorKanojia将它们定义为tf.Variables? - imsrgadich


答案:


它们不是同一件事。

import tensorflow as tf
c1 = tf.constant(42)
with tf.name_scope('s1'):
    c2 = tf.constant(42)
print(c1.name)
print(c2.name)

版画

Const:0
s1/Const:0

顾名思义,范围函数为其创建了一个范围  你在里面创建的操作。这会影响您如何引用张量,重用,图表在TensorBoard中的显示方式等等。


11
2018-03-10 07:24



感谢您的答复。你能告诉我如何重用c1和c2吗? - Vibhor Kanojia
@VibhorKanojia将它们定义为tf.Variables? - imsrgadich


我没有看到重用常量的用例,但这里有一些关于范围和变量共享的相关信息。

领域

  • name_scope 将范围添加为所有操作的前缀

  • variable_scope 将范围添加为所有变量和操作的前缀

实例化变量

  • tf.Variable() constructer前缀变量名与current name_scope 和 variable_scope 

  • tf.get_variable() 构造函数忽略 name_scope 并且只有当前名称的前缀 variable_scope

例如:

with tf.variable_scope("variable_scope"):
     with tf.name_scope("name_scope"):
         var1 = tf.get_variable("var1", [1])

with tf.variable_scope("variable_scope"):
     with tf.name_scope("name_scope"):
         var2 = tf.Variable([1], name="var2")

产生

var1 = <tf.Variable 'variable_scope/var1:0' shape=(1,) dtype=float32_ref>

var2 = <tf.Variable 'variable_scope/name_scope/var2:0' shape=(1,) dtype=string_ref>

重用变量

  • 一直用 tf.variable_scope 定义共享变量的范围

  • 重用变量的最简单方法是使用 reuse_variables() 如下所示

with tf.variable_scope("scope"):
    var1 = tf.get_variable("variable1",[1])
    tf.get_variable_scope().reuse_variables()
    var2=tf.get_variable("variable1",[1])
assert var1 == var2
  • tf.Variable() 总是创建一个新变量,当一个变量是用它刚刚附加的已经使用的名称构造的 _1_2 等它 - 这可能会导致冲突:(

3
2018-04-04 21:43