2017-05-04 187 views
1

我已經定義了兩類模型,xy如何使用Tensorflow r-1.0將一個模型的輸出作爲另一個模型的輸入?

class x(): 
    def __init__(self, x_inp1, x_inp2): 
     # do sth... 

    def step(self, session, encoder_inputs): 
     input_feed = {} 
     for l in range(encoder_size): 
      input_feed[self.encoder_inputs[l].name] = encoder_inputs[l] 
     ... 
     output_feed = [x_output] 
     return session.run(x_output) 

class y(): 
    def __init__(self, y_inp1, y_inp2): 
     # do sth... 

    def step(self, encoder_inputs): 
     input_feed = {} 
     for l in range(encoder_size): 
      input_feed[self.encoder_inputs[l].name] = encoder_inputs[l] 
     ... 

它們有很相似的功能。然後我定義另一個班級將其分組。

class gp(): 
    def __init__(self, x_inp1, x_inp2, y_inp1, y_inp2): 
     with tf.variable_scope('x'): 
       self.x_model = x(x_inp1, x_inp2) 
     with tf.variable_scope('y'): 
       self.y_model = y(y_inp1, y_inp2) 
    def step(self, session, encoder_inputs): 
     x_output = self.x_model.step(session, encoder_inputs) 
     y_output = self.y_model.step(session, x_output) 
     ... 

請注意到y_model需要的x_model輸出作爲輸入。我在main功能運行gp()

with tf.Session() as sess: 
    gp_m = gp(x_inp1, x_inp2, y_inp1, y_inp2) 
    gp_m.step(sess, x_inp1, x_inp2, y_inp1, y_inp2) 

和運行後x_output = self.x_model.step(encoder_inputs)並開始做y_output = self.y_model.step(x_output),我得到了這樣的錯誤:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'x/encoder0' with dtype int32 
[[Node: x/encoder0 = Placeholder[dtype=DT_INT32, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 

請注意此錯誤指向x_model連它的一步功能已經完成。我想知道如何將x_model的輸出作爲y_model的輸入而沒有任何錯誤?提前致謝!

回答

0

您應該將呼叫推遲到session.run以超出step功能。這裏的問題是試圖運行Y觸發器X,因爲它們連接在圖中。

相反,它可能更好地完全分離您的程序的圖形構建和圖形運行階段,因此您知道什麼時候提供佔位符。

+0

感謝您的回答!但我很抱歉,我仍然有點困惑。我應該推遲到'session.run'的調用,以在哪個'step'功能之外? 你能告訴我如何完全分離圖嗎?非常感謝!!! – user5779223

+0

在一個地方建立圖形(即調用大多數tf函數),返回想要運行的張量,並在另一個地方調用session.run。要查看構建代碼的好方法,請嘗試查看tf.estimator.Estimator –

相關問題