我正在尝试在 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)
Run Code Online (Sandbox Code Playgroud)
给出错误信息:AttributeError: 'Tensor' object has no attribute 'make_ndarray
打印y_pred参数类型后:<class 'tensorflow.python.framework.ops.Tensor'>
在寻找解决方案时,我发现这似乎是一个常见问题,并且有一些建议,但到目前为止它们对我不起作用:
1.“...所以只需在 Tensor 对象上调用 .numpy()。”:如何在 TensorFlow 中将张量转换为 numpy 数组?
所以我试过:
def custom_loss(y_true, y_pred):
npa = y_pred.numpy()
...
Run Code Online (Sandbox Code Playgroud)
给我 AttributeError: 'Tensor' object has no attribute 'numpy'
2.“使用tensorflow.Tensor.eval() to convert a tensor to …
问题
我在 Centos Linux 下使用 TensorFlow 2.1.0 进行图像分类。随着我的图像训练数据集不断增长,我必须开始使用生成器,因为我没有足够的 RAM 来保存所有图片。我已经根据本教程对生成器进行了编码。
它似乎工作正常,直到我的程序突然被杀死而没有错误消息:
Epoch 6/30
2020-03-08 13:28:11.361785: W tensorflow/core/kernels/data/generator_dataset_op.cc:103] Error occurred when finalizing GeneratorDataset iterator: Cancelled: Operation was cancelled
43/43 [==============================] - 54s 1s/step - loss: 5.6839 - accuracy: 0.4669
Epoch 7/30
2020-03-08 13:29:05.511813: W tensorflow/core/kernels/data/generator_dataset_op.cc:103] Error occurred when finalizing GeneratorDataset iterator: Cancelled: Operation was cancelled
7/43 [===>..........................] - ETA: 1:04 - loss: 4.3953 - accuracy: 0.5268Killed
Run Code Online (Sandbox Code Playgroud)
看着 linux 的 top 不断增长的内存消耗,我怀疑是内存泄漏?
我试过的