gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:40:53 24 4
gpt4 key购买 nike

我一直在看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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com