如何使用自定义损失函数在 Python 中训练的 DL4J 中加载 Keras 模型文件

How to load Keras model file in DL4J that was trained in Python using a custom loss function

我正在使用一个 Keras 模型,该模型是在 Python 中使用 DL4J 在 Java 过程中训练的。这通常工作正常,但现在转向使用自定义损失函数。

模型在 Python 中使用自定义损失函数训练:

model = load_model('modelFile' , custom_objects={'loss': my_custom_loss_function(weight)})

我尝试在Java中使用它和dl4j(版本:1.0.0-beta6)加载模型:

String modelFile = "<location of hdf5 file on disk>";
MultiLayerNetwork multiLayerNetwork = KerasModelImport.importKerasSequentialModelAndWeights(modelFile);

但是现在会抛出这个错误:

org.deeplearning4j.nn.modelimport.keras.exceptions.UnsupportedKerasConfigurationException: 
Unknown Keras loss function loss. Please file an issue at https://github.com/eclipse/deeplearning4j/issues.

如何在java中给它一个损失函数?或者有没有办法在不给它损失函数的情况下加载它?

谢谢

遗憾的是,从 beta6 开始,DL4J 不支持为 keras 导入注册自定义损失函数。

如果您只想加载经过训练的模型进行推理,您应该可以通过将 keras 中的损失函数更改为受支持的损失函数之一(参见 https://deeplearning4j.konduit.ai/keras-import/supported-features#losses)然后将其导出来解决该问题再次。