我想用tf.name_scope
来做这样的事情:
my_scope = tf.name_scope('something')
if cond_1:
foo(my_scope)
if cond_2:
bar(my_scope)
我想避免使用with tf.name_scope('something') as scope
表示法,因为我不知道什么时候第一次要使用名称范围something
。简单的my_scope = tf.name_scope('something')
不起作用,导致错误TypeError: expected string or buffer
。
现在我使用:
with tf.name_scope('something') as scope:
pass
my_scope = scope
if cond_1:
foo(my_scope)
if cond_2:
bar(my_scope)
这有效,但非常不令人满意。
我不确定foo
和bar
应该做什么,但是上面提供的片段中的两个my_scope
是完全不同的。
第一个my_scope
是上下文管理器,即实例contextlib.GeneratorContextManager
。第二个my_scope
(就像scope
一样)是一个普通的字符串,即"something/"
(见源代码)。您只需my_scope="something/"
即可达到完全相同的效果。根据错误TypeError:预期的字符串或缓冲区,这正是foo
和bar
期望的 - 字符串。
另请注意,您可以获取上下文的引用,并随时输入。 tf.name_scope
只需将名称推到堆栈顶部,然后在退出时将其弹出。但是,如果您多次输入相同的名称范围,则会得到一个后缀:_1
、_2
、...