Creating an Updatable Core ML Model

To create an updatable model, we need to set the isUpdatable flag on the model and some neural network layers.

Besides that, we need to define the training inputs, loss function, optimizers, and other parameters like epochs and batch size on our Core ML model.

We need to update coremltools to 3.0. At the time of writing, the beta 6 release was the latest. Just use the pip command to install it:

pip install coremltools==3.0b6

Converting Keras to Core ML model

Inspecting the neural network layers

First, load the specs from the existing Core ML model into a NeuralNetworkBuilder .

By inspecting the layers, we can determine the dense_layers that need to made updatable.

Along with that, we need to set the input parameters for the training input for on-device training.

Specifying updatable layers, loss functions, and optimisers

Now, we need to set the last two dense layers as updatable and set the loss-function input. The loss-function input is the output value from the softmax activation layer ( ‘output’ in our case):

The make_updatable method is used to make a layer updatable.

It requires a list of layer names. The layers are dense_5 and dense_6 in our case, available from neural network builder properties.

Specifying training-input descriptions

Now we just need to set the training-input description and save our specifications in a new model as shown below:

The specificationVersion property is important since it ensures the correct version number is used for the mlmodel .

Core ML 3 is version 4, so the above updatable model works on version 4 and above only.

Generating updatable model

Now that we’ve specified all the model specifications, we can generate our model, which is updatable on the device using the following line of code:

coremltools.utils.save_spec(model_spec, “CatDogUpdatable.mlmodel”)

Our Updatable Core ML model is now ready to use.

Let’s import it into an Xcode project. You shall see a model description similar to the one in the image below:

It’s clear from the image above that two new sections, Update and Properties, are added with Core ML 3. The Update section consists of the input descriptions for training the input.

Our above classifier model has two outputs: the label for the predicted class and a dictionary that has the confidence for all (both) of the classes.