Tensorflow:我什么时候应该使用或不使用 `feed_dict`? [英] Tensorflow: When should I use or not use `feed_dict`?

查看:36
本文介绍了Tensorflow:我什么时候应该使用或不使用 `feed_dict`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑为什么我们要使用 feed_dict?据我朋友说,你通常在使用 placeholder 时使用 feed_dict,这可能对生产不利.

I am kind of confused why are we using feed_dict? According to my friend, you commonly use feed_dict when you use placeholder, and this is probably something bad for production.

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

I have seen code like this, in which feed_dict is not involved:

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:

I have also seen code like this, in which feed_dict is involved:

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?

I understand feed_dict is that you are feeding in data and try X as the key as if in the dictionary. But here I don't see any difference. So, what exactly is the difference and why do we need feed_dict?

推荐答案

在 tensorflow 模型中你可以定义一个占位符比如 x = tf.placeholder(tf.float32),然后你会使用x 在您的模型中.

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

现在当我让 tensorflow 计算 y 时,很明显 y 依赖于 x.

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

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

这会产生一个错误,因为我没有给它一个 x 的值.在这种情况下,因为 x 是一个占位符,如果它在计算中被使用,你必须通过 feed_dict 传递它.如果你不这样做,这是一个错误.

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.

让我们解决这个问题:

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

这次的结果是84.伟大的.现在让我们看一个不需要 feed_dict 的小例子:

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

现在没有占位符(x 是一个常量),因此不需要向模型提供任何内容.这现在有效:

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)

这篇关于Tensorflow:我什么时候应该使用或不使用 `feed_dict`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆