I found the solution to my problem via hit and trial but do not understand why it worked.
I am going through getting started of tensorflow. I ran the code till the end of the following code block and it works fine.
W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W * x + b
y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)
print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))
Now, I thought that loss
looks like something that should be in a function. I tried the following.
def get_loss(linear_model):
y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
return tf.reduce_sum(squared_deltas)
loss = get_loss(linear_model)
print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))
But it gave me an error.
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_26' with dtype float
[[Node: Placeholder_26 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
I then tried the following. The only difference is I returned y
also.
def get_loss(linear_model):
y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
return y, tf.reduce_sum(squared_deltas)
y, loss = get_loss(linear_model)
print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))
It worked. Why?