Reputation: 6962
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?
Upvotes: 1
Views: 141
Reputation: 1303
It doesn't work because y
is not visible outside the scope of get_loss()
. If you return y
as in the bottom, then y
is visible now, so it works.
If you don't want to return y, you may instead feed y with its name:
def get_loss(linear_model):
# give y a name 'y'
y = tf.placeholder(tf.float32, name='y')
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':[0,-1,-2,-3]}))
Here is some discussion about the ":0" part of "y:0"
Upvotes: 2