【问题标题】:Converting tensorflow 1.0 code to tensorflow 2.0 [duplicate]将 tensorflow 1.0 代码转换为 tensorflow 2.0 [重复]
【发布时间】:2021-08-30 12:29:39
【问题描述】:

我有以下代码:

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 不再支持“会话”,我该如何修改它以使其符合 tensorflow 2.0 语法?

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

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

【问题讨论】:

    标签: python tensorflow tensorflow2.0


    【解决方案1】:

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

    启用 Eager Execution 会改变 TensorFlow 操作的行为方式——现在 他们立即评估并将其值返回给 Python。 tf.张量 对象引用具体值而不是节点的符号句柄 在计算图中。由于没有计算图 稍后在会话中构建和运行,很容易使用检查结果 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()])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 2021-05-23
      • 1970-01-01
      • 2020-03-09
      相关资源
      最近更新 更多