2015-11-19 82 views
16

我想實現一個簡單的前饋網絡。但是,我不知道如何餵養Placeholder。這個例子:如何提供佔位符?

import tensorflow as tf 

num_input = 2 
num_hidden = 3 
num_output = 2 

x = tf.placeholder("float", [num_input, 1]) 
W_hidden = tf.Variable(tf.zeros([num_hidden, num_input])) 
W_out = tf.Variable(tf.zeros([num_output, num_hidden])) 
b_hidden = tf.Variable(tf.zeros([num_hidden])) 
b_out = tf.Variable(tf.zeros([num_output])) 

h = tf.nn.softmax(tf.matmul(W_hidden,x) + b_hidden) 

sess = tf.Session() 

with sess.as_default(): 
    print h.eval() 

使我有以下錯誤:

... 
    results = self._do_run(target_list, unique_fetch_targets, feed_dict_string) 
    File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 419, in _do_run 
    e.code) 
tensorflow.python.framework.errors.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape dim { size: 2 } dim { size: 1 } 
    [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[2,1], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] 
Caused by op u'Placeholder', defined at: 
    File "/home/sfalk/workspace/SemEval2016/java/semeval2016-python/slot1_tf.py", line 8, in <module> 
    x = tf.placeholder("float", [num_input, 1]) 
    ... 

我已經試過

tf.assign([tf.Variable(1.0), tf.Variable(1.0)], x) 
tf.assign([1.0, 1.0], x) 

但顯然並未工作。

+0

不錯的問題,我一直在試圖找出這個問題 –

回答

28

要提供佔位符,請使用參數Session.run()(或Tensor.eval())。比方說,你有如下的圖,用一個佔位符:

x = tf.placeholder(tf.float32, shape=[2, 2]) 
y = tf.constant([[1.0, 1.0], [0.0, 1.0]]) 
z = tf.matmul(x, y) 

如果你要評估z,你必須養活值x。你可以這樣做如下:

sess = tf.Session() 
print sess.run(z, feed_dict={x: [[3.0, 4.0], [5.0, 6.0]]}) 

欲瞭解更多信息,請參閱documentation on feeding

+0

嗯..有沒有其他方式?我看起來很不方便想看中介結果。 – displayname

+0

您也可以將'feed_dict'參數傳遞給'Tensor.eval()',這在構建圖時可能更方便。如果你想要一個「粘性」的佔位符,我建議你自己創建一個封裝'sess.run()'的函數,捕獲一組feed的值,並且每次將它傳遞給'run()'調用。 – mrry

+0

@ mrry,你能舉一個你的評論的例子嗎?謝謝 – Amir