【问题标题】:how do i convert a tf.Variable to numpy?如何将 tf.Variable 转换为 numpy?
【发布时间】:2020-12-01 23:07:32
【问题描述】:

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

var1 = tf.Variable(4.0)

我想得到[4.0]

【问题讨论】:

  • 欢迎。如果您可以包含您尝试实现目标的代码,那就太好了。

标签: python numpy tensorflow


【解决方案1】:

您可以简单地在 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

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 2020-03-27
    • 2017-11-04
    • 1970-01-01
    • 2021-12-14
    • 2017-01-29
    • 2016-07-01
    • 2015-12-17
    • 2017-07-02
    相关资源
    最近更新 更多