2017-01-17 7 views
0

Ich möchte Variable Umfang bedingt in Tensorflow ändern.Tensorflow: Bedingte Variable hinzufügen Bereich

So zum Beispiel, wenn scope ist entweder ein String oder 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(....) 

Aber ich will nicht zu schreiben, haben die a= ..., b= ... Teil in Doppel. Ich will nur die if ... else ... den Umfang bestimmen und dann alles andere von dort gleich machen.

Irgendwelche Ideen, wie ich das tun könnte?

Antwort

1

Dies ist nicht spezifisch für TensorFlow, sondern eher eine allgemeine Python-Frage, nur FYI. In jedem Fall können Sie erreichen, was Sie mit einem Wrapper-Kontext-Manager tun wollen, wie folgt:

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: Der Code wurde behoben.

+0

Vielen Dank! Das sieht wirklich cool und elegant aus ... aber ich weiß nicht, wie ich es in meinem Kontext anwenden soll. Wohin geht "tf.variable_scope"? –

+0

Es scheint, als ob Ihre Lösung zu 'mit False:' führen könnte, was nicht zu funktionieren scheint. –

+0

Ich gehe davon aus, dass Sie meinen, was ist, dass ich '@contextmanager def cond_scope (scope) haben sollte: Ausbeute tf.variable_scope (scope), wenn Umfang sonst false' noch, aber das würde dazu führen,' mit False: 'was tut Arbeit. –

1

Vielen Dank für @keveman für mich auf dem richtigen Weg. Obwohl ich nicht seine Antwort Arbeit machen könnte er hat mich auf dem richtigen Weg: Was brauchte ich einen leeren Rahmen war, so dass folgende Arbeiten:

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) 

Nach dem was ich tun kann:

with cond_scope(scope): 

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

Für mehr über die with in Python siehe: The Python "with" Statement by Example

+0

Ja, das funktioniert auch. – keveman