它取决于你的计算图是什么样子的,以及你如何运行由张量供给的运算(这里:
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.]