如何将tf.Variable转换为numpy



如何将tf.Variable转换为numpy数组?

var1 = tf.Variable(4.0)

我想要[4.0]

您可以简单地在张量对象上调用.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)

有关更多信息,请参见自定义基础:张量和操作。也如文件中所述

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

最新更新