2016-05-17 21 views
4

我與建立一個線性迴歸的Tensorflow例子玩,和我的代碼如下所示:Tensorflow「feed_dict」:使用相同的符號鍵值對了「類型錯誤:無法解釋feed_dict鍵張量」

import numpy as np 
import tensorflow as tf 

train_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1]) 
train_Y = np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3]) 

n_samples = train_X.shape[0] 
batch_size = 100 

total_epochs = 50 

X = tf.placeholder('float') 
y = tf.placeholder('float') 

W = tf.Variable(np.random.randn(), name="weights") 
b = tf.Variable(np.random.randn(), name="bias") 

y_pred = tf.add(tf.mul(X, W), b) 

cost = tf.reduce_sum(tf.pow(y_pred-y, 2))/(2*n_samples) #L2 loss 
optimizer = tf.train.AdamOptimizer().minimize(cost) #Gradient 

init = tf.initialize_all_variables() 

with tf.Session() as sess: 
    sess.run(init) 
    print("Initia values for W and b: ", W.eval(), b.eval()) 
    for _ in range(total_epochs): 
     sess.run(optimizer, feed_dict={X: x, y: y}) 
    print("Value for W and b after GD: ", W.eval(), b.eval()) 

然而,上述運行會給我這個錯誤:

--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-11-185d8e05cbcd> in <module>() 
    28  for _ in range(total_epochs): 
    29   for (x, y) in zip(train_X, train_Y): 
---> 30    sess.run(optimizer, feed_dict={X: x, y: y}) 
    31   print("Value for W and b after GD: ", W.eval(), b.eval()) 

/home/ubuntu/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata) 
    338  try: 
    339  result = self._run(None, fetches, feed_dict, options_ptr, 
--> 340       run_metadata_ptr) 
    341  if run_metadata: 
    342   proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) 

/home/ubuntu/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata) 
    540   except Exception as e: 
    541    raise TypeError('Cannot interpret feed_dict key as Tensor: ' 
--> 542        + e.args[0]) 
    543 
    544   if isinstance(subfeed_val, ops.Tensor): 

TypeError: Cannot interpret feed_dict key as Tensor: Can not convert a float64 into a Tensor. 

更深的挖掘後,我意識到這個錯誤在這裏:

feed_dict={X: x, y: y} 

其中鍵值對使用的是相同的('y'和'y')。如果我將其更改爲Y:y,並相應修改其餘部分:

Y = tf.placeholder('float') 
cost = tf.reduce_sum(tf.pow(y_pred-Y, 2))/(2*n_samples) #L2 loss 
sess.run(optimizer, feed_dict={X: x, Y: y}) 

代碼將完美運行。

我非常想知道爲什麼我不能在feed_dict中爲鍵值對使用相同的符號?左邊的'y'(關鍵)不應該指上面的成本函數中的'y'嗎?

回答

13

feed_dict參數是一個需要張量作爲關鍵字的字典。在您糾正例如,XY是那些張量。

但是,如果你使用XY另一個變量的名稱,您將覆蓋初始張量和XY將不再與您的圖表中的張量。 Tensorflow無法理解您是從覆蓋圖中引用圖中的節點。

簡而言之,您要使用相同的名稱爲兩個不同的變量,這是不可能的。

0

change sess.run(optimizer, feed_dict={X: x, y: y}) to sess.run(optimizer, feed_dict={X: train_x, y: train_y})。 012dfedd_dict的值是您想要提供給優化器的實際輸入。

相關問題