Issues converting tensorflow model with coremltools

First off, I'm mainly a wet-lab biologist, and Python is not my strong suit, so sorry if I seem a little clueless here. Anyways, I am having trouble converting a pretrained keras model (.h5 format) with coremltools. My code to try and convert the model:

DL_model = (path to .h5 file)
model_converted = ct.convert(DL_model, source = "tensorflow")

and it throws an error:

ValueError: Unknown metric function: binary_recall. Please ensure this object is passed to the custom_objects argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.

I assume I need to pass some sort of custom_objects = {"custom_obj": custom_obj} argument in ct.convert, but I don't know how. I tried:

 custom_objects = {"binary_recall": binary_recall})

but that caused

NameError: name 'binary_recall' is not defined

Can anyone give me some help here? It would be nice to speed up this model by converting it to Apple's format; I work with huge files and cutting down data processing time is important for me.

Thanks!!

Noah

Replies

The error here is not coming from the coremltools code base, but instead in the step when coremltools tries to load the keras model from the file path. What you should do here, is first load the keras model with custom objects (as described here: https://www.tensorflow.org/api_docs/python/tf/keras/models/load_model) and then pass the loaded model to the converter. So something like this:

keras_model = tf.keras.models.load_model(filepath, custom_objects=...)
model_converted = ct.convert(keras_model, source = "tensorflow")

how do I get the names of the custom objects? I will add, this is a pretrained model from a GitHub repository; I did not train it myself. There should be a way to view it though right?