Search code examples
javapythonkerasdl4j

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


I am using a Keras model that was trained in Python in a Java process with DL4J. This has been generally working fine, but now moved to using a custom loss function.

The model was trained in Python with a custom loss-function:

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

I try to use it in Java with dl4j (version: 1.0.0-beta6) to load the model:

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

But that now throws this error:

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

How can I give it a loss function in java? Or is there a way to load it without giving it a loss function?

Thanks


Solution

  • Unfortunately DL4J doesn't support registering custom loss function for keras import as of beta6.

    If you just want to load the trained model for inference, you should be able to workaround the problem by changing the loss function in keras to one of the supported ones (see https://deeplearning4j.konduit.ai/keras-import/supported-features#losses) and then export it again.