gpt4 book ai didi

python - 使用默认范围名称时 variable_scope 不会被重用

转载 作者:太空狗 更新时间:2023-10-30 02:24:29 27 4
gpt4 key购买 nike

我对重用变量时的子作用域有疑问。这个

import tensorflow as tf

def make_bar():
with tf.variable_scope('bar'):
tf.get_variable('baz', ())

with tf.variable_scope('foo') as scope:
make_bar()
scope.reuse_variables()
make_bar()

工作得很好,只创建了一个变量 foo/bar/baz

但是,如果我将 make_bar 更改为

def make_bar(scope=None):
with tf.variable_scope(scope, 'bar'):
tf.get_variable('baz', ())

代码现在失败了

ValueError: Variable foo/bar_1/baz does not exist

问题:为什么在使用默认名称时变量作用域重用失败?如果是故意的,这个选择背后的理由是什么?

编辑

tf.variable_scopedefault_name 参数的一些精度。 From the documentation,

  • default_name: The default name to use if the name_or_scope argument is None, this name will be uniquified. If name_or_scope is provided it won't be used and therefore it is not required and can be None.

因此,正如其名称所依据的那样,它是一种提供默认范围名称的方法。

make_bar 的第一个版本中,范围名称被强制为 bar -- 该函数没有参数来更改它。

make_bar 的第二个版本中,我增强了这个函数以使其可参数化。所以 bar 仍然是默认范围名称(这次作为 tf.variable_scopedefault_name 参数提供),但是这次调用者有可以通过将 make_bar 的默认参数 scope 设置为 None 以外的任何值来更改它。`

make_bar 的第二个版本在没有参数的情况下使用时,我认为它应该退回到第一个版本的行为——但它没有。

请注意,在我的示例中,bar 旨在成为 foo 的子范围。要重用的变量意味着foo/bar/baz

最佳答案

您实际上并没有在您的示例中使用范围“foo”。您需要将参数传递给 tf.variable_scope('foo', 'bar')tf.variable_scope(scope, 'bar')。在这两种情况下,您都在调用方法 make_bar 而不带参数,这意味着在您的第一个示例中 name_or_scope='bar',在第二个示例中 name_or_scope=scope (值为 None)和 default_name='bar'

这可能是你想要的:

import tensorflow as tf

def make_bar(scope=None):
with tf.variable_scope(scope, 'bar'):
tf.get_variable('baz', ())

with tf.variable_scope('foo') as scope:
make_bar(scope)
scope.reuse_variables()
make_bar(scope)

我实际上建议不要使用默认参数,因为它们会像您的示例一样降低可读性。 None 范围什么时候是您想要的答案?如果你测试它会更有意义,也许像这样?

import tensorflow as tf

def make_bar(scope=None):
if scope is None:
scope = 'default_scope'
with tf.variable_scope(scope, 'bar'):
tf.get_variable('baz', ())


with tf.variable_scope('foo') as scope:
make_bar(scope) # use foo scope
scope.reuse_variables()
make_bar() # use 'default_scope'

但这会降低代码的可读性并更容易导致错误

关于python - 使用默认范围名称时 variable_scope 不会被重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53300337/

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