3 回答

TA貢獻1805條經驗 獲得超10個贊
TensorFlow 2.0
急切執行默認情況下.numpy()處于啟用狀態,因此只需調用Tensor對象即可。
import tensorflow as tf
a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)
a.numpy()
# array([[1, 2],
# [3, 4]], dtype=int32)
b.numpy()
# array([[2, 3],
# [4, 5]], dtype=int32)
tf.multiply(a, b).numpy()
# array([[ 2, 6],
# [12, 20]], dtype=int32)
值得注意的是(來自文檔),
Numpy數組可以與Tensor對象共享內存。對一個的任何更改都可能反映在另一個上。
大膽強調我的。副本可能會也可能不會返回,這是實現的詳細信息。
如果禁用了“急切執行”,則可以構建一個圖形,然后通過tf.compat.v1.Session以下方式運行它:
a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)
out = tf.multiply(a, b)
out.eval(session=tf.compat.v1.Session())
# array([[ 2, 6],
# [12, 20]], dtype=int32)
另請參見TF 2.0符號映射,以獲取舊API到新API的映射。
- 3 回答
- 0 關注
- 2155 瀏覽
添加回答
舉報