【问题标题】:Upgrading from tensorflow 1.x to 2.0从 tensorflow 1.x 升级到 2.0
【发布时间】:2019-08-19 19:17:05
【问题描述】:

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

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 造成的,描述的步骤“简单”但没有给出任何示例......

我试过了:

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


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

【问题讨论】:

    标签: python python-3.x tensorflow python-3.6


    【解决方案1】:

    您的代码确实是正确的。您收到的警告表明,从 Tensorflow 2.0 开始,API 中将不存在tf.Session()。因此,如果您希望您的代码与 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 之后立即启用它,就像我在上面的示例中所做的那样。

    【讨论】:

    • 这种方法不是禁用了一些 tf 2.0 功能(我根本不知道...)吗?
    • Tensorflow 2.0 中运行操作的默认方式是 Eager 模式。但是,您仍然可以按照当前方式进行操作。
    【解决方案2】:

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

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

    【讨论】:

    • 你确定吗?刚刚试过print(f1(tf.constant(3.0), tf.constant(4.5)).numpy()),得到了AttributeError: 'Tensor' object has no attribute 'numpy'
    • 对于 tf 1,是的,你这样做了,在 tensorflow 2 中,Eager Execution 是默认开启的。
    • 老实说,我怀疑您使用的是 1.x。检查tf.__version__
    • 很抱歉跳入讨论。已弃用意味着您收到警告的内容将从未来版本中排除。因为您正在运行 TF 1.14,并且 tf.Session 将被排除在 TF 2.0 中,因此警告会告诉您将其更改为 tf.compat.v1.Session,因为 tf.compat.v1.Session 将保留在 TF 2.0 API 中。
    • 啊,真的,@gorjan 是正确的,很抱歉我的大脑没有注意到这是一个警告,并一直认为你有一个例外。不错的收获:)
    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2014-06-02
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    相关资源
    最近更新 更多