将 TensorFlow 张量转换为 Numpy 数组

2024-02-05

问题描述

我正在尝试在 TensorFlow 2.3.0 中编写自定义损失函数。为了计算损失,我需要y_pred要转换为 numpy 数组的参数。但是,我找不到将其转换为<class 'tensorflow.python.framework.ops.Tensor'>到 numpy 数组,尽管 TensorFlow 函数似乎可以这样做。

代码示例

def custom_loss(y_true, y_pred):
    print(type(y_pred))
    npa = y_pred.make_ndarray()
    ...
    

if __name__ == '__main__':
    ...
    model.compile(loss=custom_loss, optimizer="adam")
    model.fit(x=train_data, y=train_data, epochs=10)

给出错误消息:AttributeError: 'Tensor' object has no attribute 'make_ndarray打印类型后y_pred范围:<class 'tensorflow.python.framework.ops.Tensor'>

到目前为止我已经尝试过的

在寻找解决方案时,我发现这似乎是一个常见问题,并且有一些建议,但到目前为止它们对我不起作用:

1.“...所以只需在 Tensor 对象上调用 .numpy() 即可。”:如何在 TensorFlow 中将张量转换为 numpy 数组? https://www.thetopsites.net/article/51302819.shtml

所以我尝试了:

def custom_loss(y_true, y_pred):
    npa = y_pred.numpy()
    ...

给我AttributeError: 'Tensor' object has no attribute 'numpy'

2.“使用tensorflow.Tensor.eval()将张量转换为数组”:如何在 Python 中将 TensorFlow 张量转换为 NumPy 数组 https://www.kite.com/python/answers/how-to-convert-a-tensorflow-tensor-to-a-numpy-array-in-python

所以我尝试了:

def custom_loss(y_true, y_pred):
    npa = y_pred.eval(session=tf.compat.v1.Session())
    ...

给了我我所见过的最长的错误消息之一,其核心是:

InvalidArgumentError: 2 root error(s) found.
      (0) Invalid argument: You must feed a value for placeholder tensor 'functional_1/conv2d_2/BiasAdd/ReadVariableOp/resource' with dtype resource
         [[node functional_1/conv2d_2/BiasAdd/ReadVariableOp/resource (defined at main.py:303) ]]
         [[functional_1/cropping2d/strided_slice/_1]]
      (1) Invalid argument: You must feed a value for placeholder tensor 'functional_1/conv2d_2/BiasAdd/ReadVariableOp/resource' with dtype resource
         [[node functional_1/conv2d_2/BiasAdd/ReadVariableOp/resource (defined at main.py:303) ]]

还必须从 1.x 版本调用 TensorFlow 兼容性函数,感觉不太适合未来,所以无论如何我不太喜欢这种方法。

3.查看TensorFlow文档,似乎有我需要的功能正在等待:tf.make_ndarray https://www.tensorflow.org/api_docs/python/tf/make_ndarray从张量创建 numpy ndarray。

所以我尝试了:

def custom_loss(y_true, y_pred):
    npa = tf.make_ndarray(y_pred)
    ...

给我AttributeError: 'Tensor' object has no attribute 'tensor_shape'

查看 TF 文档中的示例,他们在 proto_tensor 上使用它,所以我尝试首先转换为 proto:

def custom_loss(y_true, y_pred):
    proto_tensor = tf.make_tensor_proto(y_pred)
    npa = tf.make_ndarray(proto_tensor)
    ...

但已经是tf.make_tensor_proto(y_pred)引发错误:TypeError: Expected any non-tensor type, got a tensor instead.

尝试首先创建一个 const 张量也会产生相同的错误:

def custom_loss(y_true, y_pred):
    a = tf.constant(y_pred)
    proto_tensor = tf.make_tensor_proto(a)
    npa = tf.make_ndarray(proto_tensor)
    ...

围绕这个问题还有很多帖子,但似乎它们都回到了这三个基本想法。期待您的建议!


y_pred.numpy()在 TF 2 中工作但是AttributeError: 'Tensor' object has no attribute 'make_ndarray表示您的代码的某些部分没有在 Eager 模式下运行,否则您将没有Tensor对象但是一个EagerTensor.

要启用 Eager 模式,请将其放在代码的开头,然后构建图中的任何内容:

tf.config.experimental_run_functions_eagerly(True)

其次,当您编译模型时,添加此参数:

model.compile(..., run_eagerly=True, ...)

现在,您正在 Eager 模式下执行,并且所有变量实际上都保存可以打印和使用的值。请注意,切换到 Eager 模式可能需要对代码进行额外调整(请参阅here https://www.tensorflow.org/guide/eager以获得概述)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 TensorFlow 张量转换为 Numpy 数组 的相关文章

随机推荐