1

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?

Aseem Bansal
  • 6,722
  • 13
  • 46
  • 84

1 Answers1

2

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"

Community
  • 1
  • 1
weitang114
  • 1,285
  • 9
  • 14
  • I understand that it is not in the scope. That was my guess. Is that dictionary actually using the variable itself as the key? – Aseem Bansal May 03 '17 at 16:14
  • It uses either the placeholder tensor object or its name as the key. y is just an assignment (name) to the tensor object, and it's the only way you can access the object in your code. – weitang114 May 03 '17 at 16:26