【发布时间】:2020-12-01 23:07:32
【问题描述】:
如何将 tf.Variable 转换为 numpy 数组?
var1 = tf.Variable(4.0)
我想得到[4.0]
【问题讨论】:
-
欢迎。如果您可以包含您尝试实现目标的代码,那就太好了。
标签: python numpy tensorflow
如何将 tf.Variable 转换为 numpy 数组?
var1 = tf.Variable(4.0)
我想得到[4.0]
【问题讨论】:
标签: python numpy tensorflow
您可以简单地在 Tensor 对象上调用 .numpy()。
import tensorflow as tf
a = tf.Variable(4.0)
b = tf.Variable([4.0])
c = tf.Variable([[1, 2], [3, 4]])
a.numpy()
# 4.0
b.numpy()
# array([4.], dtype=float32)
c.numpy()
# array([[1, 2],
[3, 4]], dtype=int32)
请参阅Customization basics: tensors and operations 了解更多信息。也如文档中所述
Numpy 数组可以与 Tensor 对象共享内存。对其中一个的任何更改都可能反映在另一个中。
如果 Eager Execution 被禁用,您可以构建一个图表,然后通过tf.compat.v1.Session 运行它:
import tensorflow as tf
a = tf.Variable(4.0)
b = tf.Variable([4.0])
c = tf.Variable([[1, 2], [3, 4]])
a.eval(session=tf.compat.v1.Session())
# 4.0
【讨论】: