Tensorflow 2.0 中 Placeholder 的替代品是什么

What is the replacement of Placeholder in Tensorflow 2.0

我是 Tensorflow 的新手,我在 tensorflow 1.0 中使用过 tensorflow.placeholder()。但是有没有placeholder的替代。

Tf2 中没有占位符的替代品,因为它的默认模式是立即执行,如果想在 tf2 中使用占位符,请使用 tf.compat.v1 语法并禁用 v2 行为

粗略地说,TF 2 中最类似于​​占位符的语法元素是用 @tf.function 修饰的函数的参数。所以在 TF 1 中你有这样的东西:

x = tf.placeholder(...)
y = 2 * x

在 TF 2 中你写:

@tf.function
def my_function(x):
  y = 2 * x
  return y

同样,在 TF 1 中你有会话:

y_val = sess.run(y, feed_dict={x: tf.constant(1)})

但在 TF 2 中你只有函数调用(有一些关于它们参数类型的警告 - 你必须明确地使它们成为张量):

y_val = my_function(tf.constant(1))

如您所见,TF 2 稍微改变了心智模型,但希望您最终编写的代码更直观。

您可以在 this RFC 中阅读更多相关信息。