So you’ve got your Keras model set up, and it can do everything you want it to do. But how do you get it onto an iOS device? Thanks to Apple’s Core ML library, this process is painless and can be done in less than 10 lines of code. Better yet, once you write the code I’ll show you below, there’s very little you’ll have to change for the next time you need to convert a model. Here’s a link to the GitHub repo:

Now let’s begin!

Overview

Before we start, what does the whole process look like? Let me break it down step by step:

Create our model in Keras Install coremltools with pip (if you haven’t done so before) Save model as .h5 Set Xcode meta data (optional) Convert our model Save as .mlmodel

This may seem like quite a few steps, but most of them only require 1 or 2 lines of code. Let’s start with our model.

Creating our model in Keras

First we have to have a model to port. I’m not going to go into Keras in depth in this tutorial since there are plenty of resources online. I’ll just show you the code for the model I’m porting over.

Convolutional Neural Net Trained on MNIST Data

If you’ve used Keras before, you’ll know that there’s nothing special here. The model above is a Convolutional Neural Net trained on the famous MNIST digits database. The model takes as input an image of a handwritten number and predicts the digit that is in that image. Here is the Wikipedia of the database for more info. I’ve also gone ahead and linked to a reference on CNN’s above in case you’re not familiar with them. Now we can move onto porting our model.