2017-01-17 11 views
0

可変スコープを条件付きでテンソルフローで変更したいと思います。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 ...が範囲を決定し、そこから他のすべてをすることを望みます。

私はそれをどのように行うことができますか?

答えて

1

これは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(....) 

をEDITは:コードを修正しました。

+0

ありがとう!それは本当にクールでエレガントに見えますが、私はそれを私の状況でどのように適用するのか分かりません。 'tf.variable_scope'はどこに行きますか? –

+0

あなたの解決策が 'False:'になる可能性があるようですが、うまくいかないようです。 –

+0

私が何を意味することは、私が '@contextmanager デフcond_scope(スコープ)持つべきであるということであることを前提としています 降伏tf.variable_scope(スコープ)false'を 他の範囲であればそれはまだ' Falseを持つことになる: 'どのdoesntのを作業。 –

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

+0

はい、それも動作します。 – keveman

関連する問題