python - tf.variable_scope 中的重用选项如何工作?

标签 python tensorflow with-statement

from __future__ import print_function
import tensorflow as tf

def _var_init(name, shape, initializer=tf.contrib.layers.xavier_initializer(),
              trainable=True):
  with tf.device('/cpu:0'):
    var = tf.get_variable(
      name=name,
      shape=shape,
      initializer=initializer,
      trainable=trainable
    )
    return var

def main():
  sess = tf.Session()

  # 1th case, it works
  with tf.variable_scope('test1', reuse=False) as test1:
    with tf.variable_scope('test2', reuse=False) as test2:
      w1 = _var_init('w1', [1, 2])
      sess.run(tf.global_variables_initializer())
      print(sess.run(w1), w1)

  # 2th case, it works
  with tf.variable_scope('test1', reuse=True):
    with tf.variable_scope('test2', reuse=False):
      w2 = _var_init('w1', [1, 2])
      print(sess.run(w2), w2)

  # 3th case, it works
  with tf.variable_scope(test1, reuse=False):
    with tf.variable_scope(test2, reuse=True):
      w3 = _var_init('w1', [1, 2])
      print(sess.run(w3), w3)

  # 4th case, ValueError: Variable test1/test2/w1 already exists.
  with tf.variable_scope(test1, reuse=True):
    with tf.variable_scope(test2, reuse=False):
      w4 = _var_init('w1', [1, 2])
      print(sess.run(w4), w4)

  # 5th case, ValueError: Variable test1/test2/w1 already exists.
  with tf.variable_scope('test1', reuse=False):
    with tf.variable_scope('test2', reuse=False):
      w5 = _var_init('w1', [1, 2])
      print(sess.run(w5), w5)


if __name__ == '__main__':
    main()

第 1-3 个案例输出:

[[ 0.34345531 -0.84748644]] <tf.Variable 'test1/test2/w1:0' shape=(1, 2) dtype=float32_ref>
[[ 0.34345531 -0.84748644]] <tf.Variable 'test1/test2/w1:0' shape=(1, 2) dtype=float32_ref>
[[ 0.34345531 -0.84748644]] <tf.Variable 'test1/test2/w1:0' shape=(1, 2) dtype=float32_ref>

问题:

我很困惑为什么第二个案例有效但第四个案例失败。 Tensorflow不通过scope_name搜索variable_scope吗?第2种情况和第4种情况有什么区别? (即 with tf.variable_scope('test1',reuse=True):with tf.variable_scope(test1,reuse=False): 有什么区别?)

我认为它们之前是一样的。但现在他们看起来不同了。 tf.variable_scope 中的重用选项如何工作?

相似但不重复的问题:

  1. How does the reuse option in tf.variable_scope work? ;

  2. How do I force tf.variable_scope to reuse name_scope?

最佳答案

来自 Tensorflow 的官方文档,这就是解释重用选项的全部内容:

这是共享变量的基本示例:

with tf.variable_scope("foo"):
     v = tf.get_variable("v", [1])
with tf.variable_scope("foo", reuse=True):
     v1 = tf.get_variable("v", [1])
assert v1 == v

通过捕获范围并设置重用来共享变量:

with tf.variable_scope("foo") as scope:
    v = tf.get_variable("v", [1])
    scope.reuse_variables()
    v1 = tf.get_variable("v", [1])
assert v1 == v

同样,当我们尝试获取重用模式下不存在的变量时,我们会引发异常。

with tf.variable_scope("foo", reuse=True):
    v = tf.get_variable("v", [1])
    #  Raises ValueError("... v does not exists ...").

请注意,重用标志是继承的:如果我们打开一个重用作用域,那么它的所有子作用域也会被重用。

关于名称范围的注意事项:设置重用不会影响其他操作(例如 mult)的命名。参见github上的相关讨论#6189

请注意,直到版本 1.0 为止,都允许(尽管明确不鼓励)将 False 传递给重用参数,从而产生与 None 略有不同的未记录行为。从 1.1.0 开始,传递 None 和 False 作为重用具有完全相同的效果。

关于python - tf.variable_scope 中的重用选项如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45830081/

相关文章:

python - 如何在 python 中 "with open"文件列表并获取它们的句柄?

python - 跳过 -with- block 的执行

python - 沿所有轴无缝高效地翻转 numpy 数组或稀疏矩阵

python - Pandas : Usecols do not match columns, 列预期但未找到

python - 如何从具有向量列的 DataFrame 创建 tensorflow 数据集?

machine-learning - xavier_initializer() 如何知道激活?

python - 我的代码犯了什么错误?

python - 为什么字符串中的变量和标点符号之间有一个额外的空格? Python

python - 如何从边缘列表创建 python-igraph 图

tensorflow - 属性错误 : The layer has never been called and thus has no defined output shape