Tensorflow:我应该何时使用或不使用`feed_dict`?

时间:2018-05-23 21:27:08

标签: tensorflow

我有点困惑为什么我们使用feed_dict?根据我的朋友的说法,当你使用feed_dict时,你常常使用placeholder,这可能对生产有害。

我见过这样的代码,其中不涉及feed_dict

for j in range(n_batches):
    X_batch, Y_batch = mnist.train.next_batch(batch_size)
    _, loss_batch = sess.run([optimizer, loss], {X: X_batch, Y:Y_batch}) 

我也看过这样的代码,其中涉及feed_dict

for i in range(100): 
    for x, y in data:
        # Session execute optimizer and fetch values of loss
        _, l = sess.run([optimizer, loss], feed_dict={X: x, Y:y}) 
        total_loss += l

我理解feed_dict是您正在提供数据并尝试将X作为关键字,就像在字典中一样。但在这里,我没有看到任何区别。那么,究竟有什么区别,为什么我们需要feed_dict

1 个答案:

答案 0 :(得分:4)

In a tensorflow model you can define a placeholder such as x = tf.placeholder(tf.float32), then you will use x in your model.

For example, I define a simple set of operations as:

x = tf.placeholder(tf.float32)
y = x * 42

Now when I ask tensorflow to compute y, it's clear that y depends on x.

with tf.Session() as sess:
  sess.run(y)

This will produce an error because I did not give it a value for x. In this case, because x is a placeholder, if it gets used in a computation you must pass it in via feed_dict. If you don't it's an error.

Let's fix that:

with tf.Session() as sess:
  sess.run(y, feed_dict={x: 2})

The result this time will be 84. Great. Now let's look at a trivial case where feed_dict is not needed:

x = tf.constant(2)
y = x * 42

Now there are no placeholders (x is a constant) and so nothing needs to be fed to the model. This works now:

with tf.Session() as sess:
  sess.run(y)