Skip to content

Instantly share code, notes, and snippets.

@AwayQu
Forked from boaerosuke/convert_model.py
Created April 8, 2018 08:12
Show Gist options
  • Save AwayQu/abab958b64fe154dcf0b57b01847efb0 to your computer and use it in GitHub Desktop.
Save AwayQu/abab958b64fe154dcf0b57b01847efb0 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')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment