将tensorflow 1.0代码转换为tensorflow 2.0

2024-06-14 14:45:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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”,我如何修改它,使其符合tensorflow 2.0语法

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

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


Tags: 函数代码文档importaddsessiontftensorflow
1条回答
网友
1楼 · 发布于 2024-06-14 14:45:49

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

Enabling eager execution changes how TensorFlow operations behave—now they immediately evaluate and return their values to Python. tf.Tensor objects reference concrete values instead of symbolic handles to nodes in a computational graph. Since there isn't a computational graph to build and run later in a session, it's easy to inspect results using print() or a debugger.

Eager execution works nicely with NumPy. NumPy operations accept tf.Tensor arguments. The tf.Tensor.numpy method returns the object's value as a 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()])

相关问题 更多 >