Skip to content

Instantly share code, notes, and snippets.

@boaerosuke
Last active July 29, 2023 21:50
Show Gist options
  • Save boaerosuke/ac4dffebad9198cae7817efcf72e5d36 to your computer and use it in GitHub Desktop.
Save boaerosuke/ac4dffebad9198cae7817efcf72e5d36 to your computer and use it in GitHub Desktop.
Using coremltools to convert a Keras model into mlmodel for iOS
import coremltools
import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.utils import np_utils
from keras.models import load_model
def convert_model(model):
print('converting...')
coreml_model = coremltools.converters.keras.convert(model,input_names=['image'],image_input_names='image')
coreml_model.author = 'YOUR NAME'
coreml_model.license = 'MIT'
coreml_model.short_description = 'Reads a handwritten digit. The model is based on keras mnist examples here. https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py but altered to strictly set up channels last as input_shape.'
coreml_model.input_description['image'] = 'A 28x28 pixel Image'
coreml_model.output_description['output1'] = 'A one-hot Multiarray were the index with the biggest float value (0-1) is the recognized digit. '
coreml_model.save('keras_mnist_cnn.mlmodel')
print('model converted')
import os.path
if os.path.isfile('my_mnist_keras_cnn_model.h5'):
model = load_model('my_mnist_keras_cnn_model.h5')
convert_model(model)
else:
print('no model found')
@asonthalia
Copy link

Hi @jiayulinfs,
The problem is that currently coremltools supports Keras 1.2.2+ but it would be better if you pip the 1.2.2 itself; also, Tensorflow(if you're using it instead of Theano) should be 1.2.1 instead of 1.4.1. Then try removing the input_names parameter; worked for me, worth giving a shot.
Peace,
Akash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment