Deploy a Python Machine Learning Model on your iPhone
Last Updated on February 10, 2021 by Editorial Team
Author(s): Patrick Long, Ph.D.
A minimalist guide
This article describes the shortest path from training a python machine learning model to a proof of concept iOS app you can deploy on an iPhone. The goal is to provide the basic scaffolding while leaving room for further customization suited to oneβs specific use case. In the spirit of simplicity, we will overlook some tasks such as model validation and building a fully polished user interface (UI). By the end of this tutorial, you will have a trained model running on iOS that you can showcase as a prototype and load to yourΒ device.
Step 1. Set up your environment
First, letβs create a python virtual environment calledΒ .core_ml_demo and then install the necessary libraries i.e. pandas scikit-learn and coremltools. From your terminalΒ run:
Next we will install Xcode. Xcode is a development toolkit for Apple products. Note that Xcode is quite large (> 10 Gb). Iβd recommend grabbing a cup of coffee or running your install overnight. –Note, this guide uses Xcode Version 12.3 (12C33) on macOS CatalinaΒ 10.15.5.
Step 2. Train aΒ model
Weβll use scikit-learnβs Boston Housing Price toy dataset to train a linear regression model to predict home price based on property and socio-economic attributes. Since weβre aiming for simplicity, weβll limit the feature space to 3 predictors and use house price as our target variable.
Step 3. Convert the model to CoreΒ ML
Apple provides two avenues to develop models for iOS. The first, Create ML, allows one to produce models entirely within the Apple ecosystem. The second, Core ML, allows one to integrate models from third parties into the Apple platform by converting them to the Core ML format. Since weβre interested in running a python trained model on iOS, weβll use theΒ latter.
Weβll convert our sklearn model to the Core ML format (.mlmodel) using pythonβs coremltools package before importing to Xcode. coremltools allows one to assign metadata to a model object such as authorship information and model feature and outcome descriptions.
Step 4. Start a new XcodeΒ project
And thatβs it for python. From hereon, we can complete a prototype app using only Xcode and Swift. This can be done with the setupΒ below.
- Open up Xcode and create a new XcodeΒ project
- Choose βiOSβ as the Multiplatform type
- Select βAppβ as the Application type
- Next, name your project and select the βSwiftUIβ Interface.
- Now simply drag and drop theΒ .mlmodel file (saved above in step 3) into your Xcode directory. Xcode will automatically generate a Swift class for your model as shown in the editor below. If you inspect your model class, youβll notice that it includes the details we entered when saving our python model using coremltools such as feature and target field descriptions. This is handy for model stewardship.
Step 5. Build a modelΒ UI
Next weβll build a basic UI by modifying the ContentView.swift file in your Xcode project. The Swift code below sets up a UI that allows users to adjust house attributes and then to predict house price. There are several elements we can reviewΒ here.
The NavigationView contains our essential UI. It includes:
- Stepper structs (lines 19β30) for each of our three features, which enable users to modify feature values. Steppers are basically widgets that modify the @State of our house attribute variables (linesΒ 6β8).
- A Button on the navigation bar (lines 31β40) to call our model from within the predictPrice function (line 46). This yields an Alert message on the screen with the predicted price.
Outside of the NavigationView we have our predictPrice function (lines 46β62). The predictPrice function instantiates our Swift Core ML model class and generates a prediction according the values stored in our featureΒ states.
And at last the fun part. We can build and run a simulation of our app in Xcode to see our model in action. In the example below, Iβve created a simulation using the iPhoneΒ 12.
Conclusion
And thatβs it! Our initial prototype is complete. Thereβs plenty left to be done such as model validation, tests to confirm expected performance after import to iOS and a sleeker/more friendly UI. Nonetheless, I hope this serves as a useful reference for your mobile machine learning deployment endeavors.
New and improved tools continue to make mobile pursuits more widely accessible to the data science community and there are many creative opportunities waiting to be claimed in the mobile space. As mobile technology is inherently multi-media, it provides a richness of data types (e.g. audio, video, movement and location) along with unique point of use applications to expand oneβs data scienceΒ toolkit.
As always, I welcome any feedback or suggestions.
Thanks forΒ reading!
Resources
CoreML
iOS Deployment
SwiftUI
Deploy a Python Machine Learning Model on your iPhone was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.
Published via Towards AI