问题描述
我正在尝试在 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)
...
围绕这个问题还有很多帖子,但似乎它们都回到了这三个基本想法。期待您的建议!