2017-03-01 30 views
0

對不起在Tensorflow和Python的Newbee 我實現了這個代碼來學習9個隨機數的總和。我發現了一個錯誤,我不能understand.Unfortunately我不能教程我們在這裏找到了類似的問題...加入了9張隨機數與tensorflow/Python

import tensorflow as tf 
import numpy as np 

n_samples = 100 

x = tf.placeholder(tf.float32, shape=[n_samples, 9]) 
y = tf.placeholder(tf.float32, shape=[n_samples]) 

x_value = tf.placeholder(tf.float32, shape=[n_samples, 9]) 
y_value = tf.placeholder(tf.float32, shape=[n_samples]) 

W = tf.Variable(tf.zeros([9, 1])) 
b = tf.Variable(0.0) 

y = tf.matmul(x, W) + b 
y_pred = tf.placeholder(tf.float32, shape=[n_samples]) 

cost = tf.reduce_sum((y - y_pred)**2/n_samples) 
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cost) 

init = tf.global_variables_initializer() 
sess = tf.Session() 
sess.run(init) 

x_value = np.random.uniform(0, 1, size = (n_samples, 9)) 
y_value = np.random.uniform(0, 1, size = (n_samples)) 

for i in range(n_samples): 
    mysum = 0.0 
    print (i) 
    for j in range(9): 
     print (x_value[i][j]) 
     mysum += x_value[i][j] 
    y_value[i] = mysum 
    print (y_value[i]) 

cost = sess.run(train_step, feed_dict={x: x_value, y: y_value}) 

print (cost) 

而且我得到這個錯誤:

ValueError: Cannot feed value of shape (100,) for Tensor u'add:0', which has shape '(100, 1)' 

任何幫助表示讚賞。

回答

1

的代碼定義y兩次:

y = tf.placeholder(tf.float32, shape=[n_samples]) 
# ... 
y = tf.matmul(x, W) + b 

由於y僅僅是一個普通的Python變量,所述第二分配覆蓋佔位符與偏壓相加的輸出。當您輸入y的值時,TensorFlow將此解釋爲試圖爲tf.matmul(x, W) + b的結果提供替換值,而不是原始tf.placeholder()

要解決此問題,請爲佔位符y使用不同的Python變量名稱,結果爲tf.matmul(x, W) + b

+0

謝謝,我會這樣做的。 –

+0

y_ = tf.matmul(x,W)+ b y_pred = tf.placeholder(tf.float32,shape = [n_samples]) cost = tf.reduce_sum((y_ - y_pred)** 2/n_samples) 但它沒有解決問題。現在這個錯誤。 InvalidArgumentError(請參閱上面的回溯):您必須爲dtype float和shape [100]提供佔位符張量'Placeholder_4'的值[100] \t [[節點:Placeholder_4 =佔位符[dtype = DT_FLOAT,shape = [100],_device =「/ job:localhost/replica:0/task:0/cpu:0」]()]] –

+0

如果沒有在上下文中看到整個代碼,很難說出問題所在。你可以用你當前的版本更新這個問題,我會看看嗎? – mrry