【问题标题】:Tensorflow: Conditionally add variable scopeTensorflow:有条件地添加变量范围
【发布时间】:2017-01-17 11:25:17
【问题描述】:

我想在 tensorflow 中有条件地更改变量范围。

例如,如果scope 是字符串或None

if scope is None:

        a = tf.get_Variable(....)
        b = tf.get_Variable(....)
else:
    with tf.variable_scope(scope):

        a = tf.get_Variable(....)
        b = tf.get_Variable(....)

但我不想将a= ...b= ... 部分写成双写。我只希望if ... else ... 确定范围,然后从那里做其他所有事情。

关于如何做到这一点的任何想法?

【问题讨论】:

    标签: python scope tensorflow


    【解决方案1】:

    感谢@keveman 让我走上正轨。虽然我无法让他的回答发挥作用,但他让我走上了正轨:我需要的是一个空范围,因此以下工作:

    class empty_scope():
         def __init__(self):
             pass
         def __enter__(self):
             pass
         def __exit__(self, type, value, traceback):
             pass
    
    def cond_scope(scope):
        return empty_scope() if scope is None else tf.variable_scope(scope)
    

    之后我可以做:

    with cond_scope(scope):
    
        a = tf.get_Variable(....)
        b = tf.get_Variable(....)
    

    有关 python 中 with 的更多信息,请参阅: The Python "with" Statement by Example

    【讨论】:

      【解决方案2】:

      这不是 TensorFlow 特有的,而是一个通用的 Python 语言问题,仅供参考。在任何情况下,您都可以使用包装上下文管理器来实现您想要做的事情,如下所示:

      class cond_scope(object):
        def __init__(self, condition, contextmanager):
          self.condition = condition
          self.contextmanager = contextmanager
        def __enter__(self):
          if self.condition:
            return self.contextmanager.__enter__()
        def __exit__(self, *args):
          if self.condition:
            return self.contextmanager.__exit__(*args)
      
      with cond_scope(scope is not None, scope):
        a = tf.get_variable(....)
        b = tf.get_variable(....)
      

      编辑:修正了代码。

      【讨论】:

      • 谢谢!这看起来真的很酷很优雅......但我不知道如何在我的上下文中应用它。 tf.variable_scope去哪儿了?
      • 看来您的解决方案可能会导致 with False: 似乎不起作用。
      • 我假设你的意思是我应该有 @contextmanager def cond_scope(scope): yield tf.variable_scope(scope) if scope else False 但这仍然会导致 with False: 不起作用。
      • 所以我只是在我之前的评论中尝试过它,它适用于scope is None(感谢我假设的上下文管理器)但是当范围是字符串时它不起作用。我没有收到任何错误,但我的 tfvariables 不在范围内。
      • 抱歉代码错误,我在回车之前没有完全测试它。以上工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      相关资源
      最近更新 更多