首页 > 解决方案 > 在 tensorflow2.3.0 上急切执行

问题描述

我正在上 TensorFlow 的初学者课程。我安装的版本是2.3.0。由于课程的 TensorFlow 版本与我安装的不同,因此我遇到了急切执行的问题。有谁知道我如何执行急切的执行?

举个例子,

    import tensorflow.compat.v1 as tf 
        
        
    x = tf.constant([3,5,7])
    y = tf.constant([1,2,3])
    z1 = tf.add(x,y)
    z2 = x*y
    z3 = z2-z1
        
    print(z2)
       
    with tf.compat.v1.Session() as sess:
        a1, a2, a3 = sess.run([z1,z2,z3])
        print(a1)
        print(a2)
        print(a3)


我得到作为急切执行 Tensor("mul_6:0", shape=(3,), dtype=int32) 的输出

标签: pythontensorfloweager-execution

解决方案


如果您想急切执行 - 以常规方式导入 tf,而不是tensorflow.compat.v1. 那么根本不需要使用session。只需输入公式并打印结果:

import tensorflow as tf

x = tf.constant([3,5,7])
y = tf.constant([1,2,3])
z1 = tf.add(x,y)
z2 = x*y
z3 = z2-z1

print(z1)
print(z2)
print(z3)

tf.Tensor([ 4  7 10], shape=(3,), dtype=int32)
tf.Tensor([ 3 10 21], shape=(3,), dtype=int32)
tf.Tensor([-1  3 11], shape=(3,), dtype=int32)

推荐阅读