从 tensorflow 1.x 升级到 2.0

Upgrading from tensorflow 1.x to 2.0

我是张量流的新手。 试过这个简单的例子:

import tensorflow as tf
sess = tf.Session()
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
z = x + y
print(sess.run(z, feed_dict={x: 3.0, y: 4.5}))

并得到一些警告 The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. 和正确答案 - 7.5

阅读here后,我了解到警告是由于从 tf 1.x 升级到 2.0,描述的步骤是 "simple" 但他们没有给出任何示例。 ...

我试过:

@tf.function
def f1(x1, y1):
    return tf.math.add(x1, y1)


print(f1(tf.constant(3.0), tf.constant(4.5)))
  1. 我的代码是否正确(在 link 中定义的意义上)?
  2. 现在,我得到 Tensor("PartitionedCall:0", shape=(), dtype=float32) 作为输出,我怎样才能得到实际值?

你的代码确实正确。您收到的警告表明,从 Tensorflow 2.0 开始,tf.Session() 将不存在于 API 中。因此,如果您希望您的代码与 Tensorflow 2.0 兼容,您应该改用 tf.compat.v1.Session。所以,只需更改此行:

sess = tf.Session()

收件人:

sess = tf.compat.v1.Session()

然后,即使您将 Tensorflow 从 1.xx 更新为 2.xx,您的代码也会以相同的方式执行。至于Tensorflow 2.0中的代码:

@tf.function
def f1(x1, y1):
    return tf.math.add(x1, y1)

print(f1(tf.constant(3.0), tf.constant(4.5)))

如果你在 Tensorflow 2.0 中 运行 就没问题。如果你想运行相同的代码,而不安装Tensorflow 2.0,你可以这样做:

import tensorflow as tf
tf.enable_eager_execution()

@tf.function
def f1(x1, y1):
    return tf.math.add(x1, y1)

print(f1(tf.constant(3.0), tf.constant(4.5)).numpy())

这是因为从Tensorflow 2.0开始执行Tensorflow操作的默认方式是eager模式。在 Tensorflow 1.xx 中激活 eager 模式的方法是在导入 Tensorflow 后立即启用它,就像我在上面的示例中所做的那样。

根据 Tensorflow 2.0,您的代码是正确的。 Tensorflow 2.0 与 numpy 的结合更加紧密,所以如果你想得到运算的结果,你可以使用 numpy() 方法:

print(f1(tf.constant(3.0), tf.constant(4.5)).numpy())