2017-11-03 1 views
-1

Der folgende Code (bei dem Versuch, Codestruktur in https://danijar.com/structuring-your-tensorflow-models/ zu replizieren)Wie Lazy Loading in Tensorflow korrekt implementieren?

import tensorflow as tf 

class Model: 

    def __init__(self, x): 
     self.x = x 
     self._output = None 

    @property 
    def output(self): 
     if not self._output: 
      weight = tf.Variable(tf.constant(4.0)) 
      bias = tf.Variable(tf.constant(2.0)) 
      self._output = tf.multiply(self.x, weight) + bias 
     return self._output 

def main(): 
    x = tf.placeholder(tf.float32) 
    model = Model(x) 

    with tf.Session() as sess: 
     sess.run(tf.global_variables_initializer()) 
     output = sess.run(model.output, {x: 4.0}) 
     print(output) 

if __name__ == '__main__': 
    main() 

gibt einen Fehler. Ein Teil davon ist wie folgt:

Caused by op 'Variable_1/read', defined at: 
    File "example.py", line 27, in <module> 
     main() 
    File "example.py", line 23, in main 
     output = sess.run(model.output, {x: 4.0}) 
    File "example.py", line 12, in output 
     weight = tf.Variable(tf.Variable(tf.constant(4.0))) 

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable_1 

Wie behebe ich das Problem?

+0

Warum definieren Sie 'weight' als' tf.Variable (tf.Variable (tf.constant (4,0))) 'im Gegensatz zu' tf.Variable (tf. Konstante (4.0)) '? – mrry

+0

Es war ein Fehler. Die Frage wurde korrigiert. – prabodhhere

Antwort

2

Das Problem ist, dass der Aufruf von sess.run(tf.global_variables_initializer()) geschieht vor die Variablen erstellt werden, in dem ersten Aufruf von model.output in der folgenden Zeile.

Um das Problem zu beheben, müssen Sie irgendwie auf model.output zugreifen, bevor Sie sess.run(tf.global_variables_initializer()) aufrufen. Zum Beispiel kann der folgende Code funktioniert:

import tensorflow as tf 

class Model: 

    def __init__(self, x): 
     self.x = x 
     self._output = None 

    @property 
    def output(self): 
     # NOTE: You must use `if self._output is None` when `self._output` can 
     # be a tensor, because `if self._output` on a tensor object will raise 
     # an exception. 
     if self._output is None: 
      weight = tf.Variable(tf.constant(4.0)) 
      bias = tf.Variable(tf.constant(2.0)) 
      self._output = tf.multiply(self.x, weight) + bias 
     return self._output 

def main(): 
    x = tf.placeholder(tf.float32) 
    model = Model(x) 

    # The variables are created on this line. 
    output_t = model.output 

    with tf.Session() as sess: 
     sess.run(tf.global_variables_initializer()) 
     output = sess.run(output_t, {x: 4.0}) 
     print(output) 

if __name__ == '__main__': 
    main() 
+0

Das 'if self._output ist None' ist ein guter Anruf. – yeaske