参考 tf.Tensor.numpy - 云+社区 - 腾讯云
.numpy方法只用在使用tf.enable_eager_execution()
(命令式编程开启)后才有的方法, 否则会有==AttributeError: ‘Tensor’ object has no attribute ‘numpy’==报错。
import tensorflow as tf
from math import pi
tf.enable_eager_execution()
def f(x):
return tf.square(tf.sin(x))
assert f(pi/2).numpy() == 1.0
print(f(pi/2).numpy())
print(f(pi/2))
Output:
----------------------------------------
1.0
tf.Tensor(1.0, shape=(), dtype=float32)
----------------------------------------