How to Convert TensorFlow h5 Models to Core ML
CreateML has made developing Machine Learning Models for use in Xcode remarkably easy. Almost Magic. However, as nice as the Apple’s rose garden is, there are times when other tools are needed.
I will go over converting a Keras h5 model file to CoreML in the quickest and simplest way I found.
Prerequisites
Sadly we will not be using XCode, we have to rely on python, CoreML Tools, and the third-party packages your model needs. To convert h5 Keras files, we need to install TensorFlow.
Assuming you already have python set up. You can use these two commands in your terminal.
pip install coremltools
pip install tensorflow
The Code
If python is not something you use often, I recommend Sublime Text as a lightweight IDE.
import coremltools
import tensorflow as tf
model_path = '/Users/You/YourModelPath.h5'
keras_model = tf.keras.models.load_model(model_path)
model = coremltools.convert(keras_model, convert_to="mlprogram")
model.save("Model Name Comes Here")
With that written and you can save the code as a python file. For example, “convert.py” and copy its directory path.
Open up the terminal and change the directory to where you want to save your CoreML file. Afterward, run the program like so, and its done. You can add the metadata to the model by opening it with Xcode and clicking “Edit” in the top right.
cd Developer/CoreMLFiles
python /Users/YourPathToThePythonFile/convert.py
Thanks for reading. I really appreciate it and hope that your project compiles bug-free.