简体   繁体   English

Tensorflow:tf.name_scope 没有“with”

[英]Tensorflow: tf.name_scope without 'with'

I would like to use tf.name_scope for something like this:我想将tf.name_scope用于这样的事情:

my_scope = tf.name_scope('something')

if cond_1:
    foo(my_scope)

if cond_2:
    bar(my_scope)

I would like to avoid using the with tf.name_scope('something') as scope notation, as I don't know when the first time I want to use the name scope something .我想避免使用with tf.name_scope('something') as scope表示法,因为我不知道我第一次想使用名称 scope something The simple my_scope = tf.name_scope('something') doesn't work, resulting in the error TypeError: expected string or buffer .简单的my_scope = tf.name_scope('something')不起作用,导致错误TypeError: expected string or buffer

Right now I use:现在我使用:

with tf.name_scope('something') as scope:
    pass
my_scope = scope

if cond_1:
    foo(my_scope)

if cond_2:
    bar(my_scope)

which works, but is very unsatisfying.这有效,但非常不令人满意。

I am not sure what foo and bar are supposed to do, but two my_scope in the provided above snippets are completely different.我不确定foobar应该做什么,但是上面提供的片段中的两个my_scope是完全不同的。

The first my_scope is a context manager , namely contextlib.GeneratorContextManager instance.第一个my_scope是一个上下文管理器,即contextlib.GeneratorContextManager实例。 The second my_scope (just as scope ) is an ordinary string, namely "something/" (see the source code ).第二个my_scope (就像scope )是一个普通的字符串,即"something/" (参见源代码)。 You can achieve exactly the same effect with just my_scope="something/" .仅使用my_scope="something/"即可达到完全相同的效果。 Based on the error TypeError: expected string or buffer , that's exactly what foo and bar expect - a string.基于错误TypeError: expected string or buffer ,这正是foobar期望的 - 一个字符串。

Also note that you can get a reference on a context and enter it whenever you like.另请注意,您可以在上下文中获取参考并随时输入。 tf.name_scope simply pushes the name on top of the stack and then pops it back on exit. tf.name_scope只是将名称压入堆栈顶部,然后在退出时将其弹出。 But if you enter the same name scope multiple times, you'll get a suffix: _1 , _2 , ...但是如果你多次输入相同的名称范围,你会得到一个后缀: _1_2 ,...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM