The world’s leading publication for data science, AI, and ML professionals.

Run or Walk (Part 4): Using Keras Neural Network Classifier in iOS with Core ML

Read previous parts: – Run or Walk (Part 1): Detecting Motion Data Activity with Machine Learning and Core ML – Run or Walk (Part 2): Collecting Device Motion Data the Right Way – Run or Walk (Part 3): >99% Accuracy Neural Network Classifier for Detecting Motion Activity

Finally, I got to the final step of this journey. Now it’s time to utilize the model we trained in Part 3 inside the iOS application which predicts user motion activity.

Save Keras Model

First of all, I had to serialize my trained model to JSON and save its weights.

Keras provides a straightforward API to achieve this:

The same easy way one can save model’s weights to *.h5 file on disk:

Convert Keras Model to Core ML

Now it’s time to convert my saved model to Core ML format. Since I have a Keras model neural network, I can use Apple’s Core ML Tools Python package which does the job converting the model for me:

Use Converted Core ML Model in iOS App

Importing Core ML model to my iOS app was as easy as drag&drop it to Xcode project. The values I just used for setting model’s metadata, input and output description are now visible in the Core ML model’s window in Xcode.

Core ML model window in Xcode
Core ML model window in Xcode

Since Xcode has automatically generated a custom API for imported _accel_xmodel Core ML model, I’m ready to go with feeding the model with sensor data and reading its predictions.

Finish Line

It was really cool to see how the idea of detecting motion data activity evolved to such an interesting project requiring me not only learning new things about Machine Learning and its application in iOS with Core ML but also giving a chance to lose a couple of kilos when collecting data for the model.

iOS app detects motion activity in real time
iOS app detects motion activity in real time

It’s amazing what new possibilities there are with such an easy way to apply machine learning in mobile applications as Apple’s Core ML!

Follow me to get updated on my latest experiments with machine learning and iOS!


Related Articles