Running machine learning models directly on-device eliminates the latency and privacy risks associated with server-side API requests. Apple’s CoreML technology allows developers to train custom models using real-world data and execute them natively on iOS devices. This approach enables applications to predict user behavior - such as the likelihood of purchasing a premium upgrade - based on local signals like battery level and charging status.
This workflow is designed for iOS developers and data engineers who need to integrate predictive features without requiring extensive backend data science experience. Implementing on-device machine learning reduces server costs, ensures user data remains private, and allows applications to function seamlessly even when offline.
How to Train and Deploy Your CoreML Model
- Load the recorded data into a pandas DataFrame using Python. This prepares your raw dataset, such as user outcomes and battery levels, for processing.
import pandas as pd
rows = [
['Dismissed', 0.90, False],
['Dismissed', 0.10, False],
['Purchased', 0.24, True],
['Dismissed', 0.13, True]
]
data = pd.DataFrame(rows, columns=['Outcome', 'Battery Level', 'Phone Charging?'])
print(data)- Split the data into a training set and a test set using the sklearn library. This ensures you have isolated data to evaluate the model's accuracy after training, a concept explained further in this CGP Video.
from sklearn.model_selection import train_test_split
X = data.drop("Outcome", axis=1)
Y = data["Outcome"]
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, shuffle=True)- Train the model using a basic RandomForest classifier. This builds the predictive logic based on your training data and generates a classification report to verify accuracy.
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
classifier = RandomForestClassifier()
classifier.fit(X_train, Y_train)
Y_pred = classifier.predict(X_test)
print(classification_report(Y_test, Y_pred, zero_division=1))- Export the trained classifier into a.mlmodel file using Apple's CoreMLTools. This converts the Python model into a native format optimized for Apple's ML chips.
import coremltools
coreml_model = coremltools.converters.sklearn.convert(classifier, input_features="input")
coreml_model.short_description = "My first model"
coreml_model.save("MyFirstCustomModel.mlmodel")- Bundle the CoreML file by dragging and dropping it directly into your Xcode project. This allows Xcode to automatically generate a Swift class based on the model's inputs and outputs.
- Execute the Machine Learning model on-device by passing parameters to the generated Swift class. This runs the prediction locally, returning the probability of a user action without network latency.
let batteryLevel = UIDevice.current.batteryLevel
let batteryCharging = UIDevice.current.batteryState == .charging || UIDevice.current.batteryState == .full
do {
let modelInput = MyFirstCustomModelInput(input: [
Double(batteryLevel),
Double(batteryCharging ? 1.0 : 0.0)
])
let result = try MyFirstCustomModel(configuration: MLModelConfiguration()).prediction(input: modelInput)
let classProbabilities = result.featureValue(for: "classProbability")?.dictionaryValue
let upsellProbability = classProbabilities?["Purchased"]?.doubleValue ?? -1
print("Chances of Upsell: \(upsellProbability)")
} catch {
print("Error running CoreML file: \(error)")
}The Shift Toward Localized Intelligence
The transition from server-side processing to on-device inference represents a fundamental shift in how mobile applications handle user data. While this tutorial demonstrates a basic implementation using just two inputs, production environments scale this concept dramatically. Platforms like ContextSDK currently process over 180 different signals simultaneously, proving that modern Apple silicon is more than capable of handling complex, multi-variable predictive models without draining the battery.
Looking ahead, the real challenge for developers will not be training the models, but managing their lifecycle. Hardcoding models into the app bundle is a solid starting point, but it limits flexibility. The next logical step for teams adopting this architecture is implementing over-the-air (OTA) updates for CoreML files. This allows developers to deploy refined models, manage complex A/B tests, and adjust dynamic input parameters across millions of devices instantly, bypassing the standard App Store review cycle for logic updates.