嗯,这取决于您的计算图的外观以及您如何运行由张量提供的操作(此处为: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
InvalidArgumentError:您必须为占位符张量“B”提供一个值,其 dtype 为 float 和 shape [3]
[[节点: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.]