代码之家  ›  专栏  ›  技术社区  ›  Eric Auld

在TensorFlow中,是否需要输入与所需内容无关的值?

  •  0
  • Eric Auld  · 技术社区  · 7 年前

    在TensorFlow中,当我 run 任何事,我的 feed_dict 需要给我的所有占位符赋予值,即使是那些与我运行的内容无关的占位符?

    特别是我正在考虑做一个预测,在这种情况下,我的 targets 占位符不相关。

    1 回复  |  直到 7 年前
        1
  •  2
  •   kmario23 Mazdak    7 年前

    它取决于你的计算图是什么样子的,以及你如何运行由张量供给的运算(这里: placeholders )如果在您将在会话中执行的计算图的任何部分中都不依赖于占位符,则不需要向它提供值。下面是一个小例子:

    In [90]: a = tf.constant([5, 5, 5], tf.float32, name='A')
        ...: b = tf.placeholder(tf.float32, shape=[3], name='B')
        ...: c = tf.constant([3, 3, 3], tf.float32, name='C')
        ...: d = tf.add(a, c, name="Add")
        ...: 
        ...: with tf.Session() as sess:
        ...:       print(sess.run(d))
        ...:
    
    # result       
    [8. 8. 8.]
    

    另一方面,如果执行计算图中依赖于占位符的部分,则必须为其提供一个值,否则它将引发 InvalidArgumentError . 下面是一个例子,说明了这一点:

    In [89]: a = tf.constant([5, 5, 5], tf.float32, name='A')
        ...: b = tf.placeholder(tf.float32, shape=[3], name='B')
        ...: c = tf.add(a, b, name="Add")
        ...: 
        ...: with tf.Session() as sess:
        ...:       print(sess.run(c))
        ...:       
    

    执行上述代码,抛出以下代码 无效参数错误

    InvalidArgumentError:必须为具有dtype float和shape[3]的占位符张量“b”提供一个值

    [node:b=placeholderdtype=dt_float,shape=[3],_device=“/job:localhost/replica:0/task:0/device:cpu:0”]


    因此,要使其正常工作,必须使用 feed_dict 如:

    In [91]: a = tf.constant([5, 5, 5], tf.float32, name='A')
        ...: b = tf.placeholder(tf.float32, shape=[3], name='B')
        ...: c = tf.add(a, b, name="Add")
        ...: 
        ...: with tf.Session() as sess:
        ...:       print(sess.run(c, feed_dict={b: [3, 3, 3]}))
        ...:       
        ...:       
    [8. 8. 8.]