python - 从 tensorflow 1.x 升级到 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
阅读此处后,我了解到警告是由于从 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)))
- 我的代码是否正确(在链接中定义的意义上)?
- 现在,我得到
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 中激活渴望模式的方法是在导入 Tensorflow 后立即启用它,就像我在上面的示例中所做的那样。
推荐阅读
- ios - How to record audio for a certain duration using AV Audio
- vuejs2 - Unit-testing VueJS component doesn't seem to register click() invocation
- python - 在其他函数中使用全局变量不起作用
- swift - Using SwiftNIO and SwiftNIOHTTP2 as an HTTP2 client
- javascript - Connect express with react application
- python - GCP:在哪里安排写入 BigQuery 的 PubSub 订阅者
- ruby-on-rails - 具有货币字段类型的 Searchkick 和 PostgreSQL
- android - MongoDB Mobile 是否构建在 SQLite 之上?
- r - 在 R 中使用聚合函数过滤特定值
- python - PyTorch - 将张量与标量相乘得到零向量