tensorflow - 我们为什么使用tf.name_scope()

标签 tensorflow

我一直在看TensorFlow上的教程

with tf.name_scope('read_inputs') as scope:
    # something

这个例子
a = tf.constant(5)


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

似乎有相同的效果。那么,为什么我们要使用name_scope呢?

最佳答案

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

范围

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

  • 实例化变量
  • tf.Variable()构造函数在变量名前添加当前name_scopevariable_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等-可能会引起冲突:(
  • 关于tensorflow - 我们为什么使用tf.name_scope(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42708989/

    相关文章:

    python - 如何在Tensorflow中删除张量中的重复值?

    python - 在 initializable_iterator 不可用的急切执行模式下,如何动态地提供 tf.data.Dataset?

    python - Keras 序列模型 非线性回归模型 错误预测

    Tensorflow,用 tf.train.Saver 保存了什么?

    python - 带有tensorflow后端: layer implementation when batch_size is used,的keras,但在图构建过程中它是None

    java - 在多核设备上运行 TensorFlow

    python - 迭代 tf.data.Dataset 的有效方法

    python - 生成器和序列之间的 Keras 区别

    python - 无法从检查点 : bidirectional/backward_lstm/bias 恢复

    tensorflow - 凯拉斯 GlobalMaxPooling2D 类型错误 : ('Keyword argument not understood:' , 'keepdims' )