0

Sorry Newbee in Tensorflow and Python I implemented this code to learn the sum of 9 random numbers. I'm getting an error which I can't understand.Unfortunately I could not find a similar problem in tutorials our here ...

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)

And I'm getting this error:

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

Any help is appreciated.

Aaron
  • 2,354
  • 1
  • 17
  • 25

1 Answers1

1

The code defines y twice:

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

Since y is just a normal Python variable, the second assignment overwrites the placeholder with the output of your bias addition. When you come to feed a value for y, TensorFlow interprets this as attempting to feed a replacement value for the result of tf.matmul(x, W) + b, and not the original tf.placeholder().

To fix this problem, use a different Python variable name for the placeholder y and result of tf.matmul(x, W) + b.

mrry
  • 125,488
  • 26
  • 399
  • 400
  • Thanks, I'll do so. – Dr. Michael R. Alvers Mar 02 '17 at 17:26
  • I changed the to 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) but it did not solve the problem. Now this error. InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_4' with dtype float and shape [100] [[Node: Placeholder_4 = Placeholder[dtype=DT_FLOAT, shape=[100], _device="/job:localhost/replica:0/task:0/cpu:0"]()]] – Dr. Michael R. Alvers Mar 03 '17 at 08:04
  • It's hard to say what the problem is without seeing the whole code in context. Could you update the question with your current version, and I'll take a look? – mrry Mar 03 '17 at 16:15
  • The code posted above is the full code. I just followed your advise and changed y = tf.matmul(x, W) + b to yy = tf.matmul(x, W) + b (accordingly below as well). Thx for the effort! – Dr. Michael R. Alvers Mar 06 '17 at 08:21