将TensorFlow 1.0代码转换为TensorFlow 2.0 [英] Converting tensorflow 1.0 code to tensorflow 2.0

查看:21
本文介绍了将TensorFlow 1.0代码转换为TensorFlow 2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

import tensorflow as tf
a = tf.constant(5)
b = tf.constant(2)
c = tf.constant(3)
d = tf.multiply(a,b)
e = tf.add(b,c)
f = tf.subtract(d,e)

with tf.Session() as sess: #changes should be made here since session is not supported in 2.0
    fetches = [a,b,c,d,e,f]
    outs = sess.run(fetches)
    print("outs={}".format(outs))

由于TensorFlow 2.0中不再支持";Session&Quot;,我如何修改它以使其使用TensorFlow 2.0语法?

我不希望使用Compat函数,因为我想学习新的TensorFlow 2.0会话替代语法。我阅读了文档https://www.tensorflow.org/guide/effective_tf2,但我很难理解文档中提到的使用函数。

如何修改上面的会话代码,以便在TensorFlow 2.0中获得相同的输出?

推荐答案

由于默认情况下启用eager execution,因此任何操作都会立即计算。

启用急切执行改变了TensorFlow操作的行为方式-现在 它们会立即求值并将其值返回给Python。Tf.Tensor 对象引用具体的值,而不是节点的符号句柄 在计算图表中。因为没有计算图可以 在稍后的会话中构建和运行,可以使用以下命令轻松检查结果 Print()或调试器。

急切执行与NumPy配合得很好。接受NumPy操作 Tf.张量参数。Tf.Tensor.numpy方法返回对象的 数值为NumPy ndarray。

因此您可以对张量调用numpy()以获取其数值:

import tensorflow as tf
a = tf.constant(5)
b = tf.constant(2)
c = tf.constant(3)
d = tf.multiply(a,b)
e = tf.add(b,c)
f = tf.subtract(d,e)

print('outs =', [a.numpy(), b.numpy(), c.numpy(), d.numpy(),
      e.numpy(), f.numpy()])

这篇关于将TensorFlow 1.0代码转换为TensorFlow 2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆