Convert PyTorch Trained Model To Core ML model

Viewed 35

I'm a newbie in python. I have model.ckpt file. I want to convert that model to core ML model .mlmodel to using in iOS project. I have spent a lots of time to research but I don't know how to do it. Someone told me use coremltools but I could not find tutorial how to do that. This code bellow is not work.

coreml_model = coremltools.converters.keras.convert('./model.ckpt',
                                                input_names='image',
                                                image_input_names='image',
                                                output_names='output',
                                                class_labels=['1', '2'],
                                                image_scale=1/255)
coreml_model.save('abc.mlmodel')
1 Answers

From the article:

convert_tf_keras_model

# Tested with TensorFlow 2.6.2
import tensorflow as tf
import coremltools as ct

tf_keras_model = tf.keras.Sequential(
    [
        tf.keras.layers.Flatten(input_shape=(28, 28)),
        tf.keras.layers.Dense(128, activation=tf.nn.relu),
        tf.keras.layers.Dense(10, activation=tf.nn.softmax),
    ]
)

# Pass in `tf.keras.Model` to the Unified Conversion API
mlmodel = ct.convert(tf_keras_model, convert_to="mlprogram")

# or save the keras model in SavedModel directory format and then convert
tf_keras_model.save('tf_keras_model')
mlmodel = ct.convert('tf_keras_model', convert_to="mlprogram")

# or load the model from a SavedModel and then convert
tf_keras_model = tf.keras.models.load_model('tf_keras_model')
mlmodel = ct.convert(tf_keras_model, convert_to="mlprogram")

# or save the keras model in HDF5 format and then convert
tf_keras_model.save('tf_keras_model.h5')
mlmodel = ct.convert('tf_keras_model.h5', convert_to="mlprogram")

To load tensorflow saved models, check this

Related