Day 02 · From model to mobile
Machine learning in iOS apps.
Choose the right framework, convert your model and build a feature people can use. A practical guide to Core ML, Vision and the tools around them.
Start the lesson
Choose with purposeUnderstand where seven frameworks fit.
Keep the detailsFollow conversion examples and compatibility notes.
Check the resultUse simple maths and real-device validation.
In this lesson
Start with the feature, then choose the framework
Adding machine learning to an iOS app starts with a useful question: what should the app recognise, predict or recommend? A camera app might identify objects. A study app might organise text. A sound tool might recognise a short audio event. Each problem needs suitable data, a model and an interface that explains the result.
- Choose or trainDefine a useful task and prepare representative data.
- ExportConvert to a supported model format and target OS.
- IntegrateMatch image or text preparation to the model inputs.
- ValidateCheck predictions, speed and the experience on a real device.
For many Apple-platform projects, Core ML is the starting point for running a custom model on the device. Create ML can help train supported model types on a Mac. Vision adds image-analysis capabilities, including built-in requests and support for custom Core ML image models. These tools complement one another; they do not all do the same job.
This lesson keeps the frameworks and conversion routes from the original 2024 guide, with updated names, clearer code and explicit warnings around older tools. Technical review: 14 November 2026. A framework update can change its requirements, so check the documentation for the version you actually ship.
| Your immediate need | A sensible starting point | What to check |
|---|---|---|
| Run a custom model in an Apple app | Core ML | Supported operators, input format and deployment target |
| Train a supported classifier with your own examples | Create ML on a Mac | Data quality, labels and a separate evaluation set |
| Recognise text, detect faces or process camera images | Vision | Whether a built-in request already solves the task |
| Reuse a TensorFlow Lite mobile pipeline | LiteRT | Runtime, model format and iOS integration |
| Deploy through the PyTorch edge stack | ExecuTorch | Export support, backend and package requirements |
| Build lower-level GPU work or an Apple-silicon research pipeline | Metal or MLX, depending on the task | Platform support, engineering effort and measured device performance |
Choose one small feature first. Write down an acceptable error rate, response time and memory budget before comparing tools. A working prototype on your oldest supported iPhone is more useful than a framework comparison based only on promotional descriptions.
Seven frameworks and tools, explained clearly
1. Core ML: run a model inside your app
Core ML is Apple’s framework for integrating machine learning models into apps. It can use available CPU, GPU and Neural Engine resources according to the model, device and configuration. Common uses include image classification, numerical prediction and language-related models.
On-device inference can reduce dependence on a network connection and keep the model’s input processing local. That is an architectural benefit, not a complete privacy guarantee: analytics, crash reports or other app code may still send information elsewhere. Check the entire data flow before making a privacy promise.
Example: an app can classify a photo locally and display the most likely label. It should also explain uncertain results and offer a useful fallback rather than presenting every prediction as a fact.
2. Create ML: train supported models on your Mac
Create ML provides tools for training supported model types, including image and sound classification. Its application is available through Xcode’s developer tools on a Mac, and its framework supports programmatic workflows. The resulting model can be integrated into an app with Core ML.
The accessible interface does not remove the need for careful data preparation. If all examples of one label use the same background, a model may learn the background instead of the intended object. Keep training and evaluation examples separate, inspect mistakes, and include realistic variations in lighting, distance and device capture.
3. Vision: image analysis and custom image-model requests
Vision offers image-analysis requests for tasks such as text recognition, face detection and tracking. A face detector locates a face; it does not automatically identify the person. Vision can also work with custom Core ML image models, but its built-in requests do not all require you to supply one.
For a custom image classifier, pay attention to orientation, image resizing and crop policy. Changing the crop can remove the very object you want to identify. Test the actual camera-to-model path, including the way you present results, rather than testing only a neatly prepared image in a notebook.
4. TensorFlow Lite, now LiteRT: another mobile deployment route
TensorFlow Lite is now known as LiteRT. It supports on-device deployment across platforms, and Google documents iOS integration through Swift and Objective-C. Existing guides and package names may still use TensorFlow Lite terminology.
This route is useful when your team already maintains compatible mobile models or shares a deployment pipeline across platforms. It does not mean every TensorFlow model will run unchanged. Check conversion support, the model’s required operations and the runtime you include. Compare model quality, latency and app size on your target devices.
5. PyTorch Mobile and ExecuTorch: distinguish the old and current paths
PyTorch Mobile is no longer actively supported. For a new PyTorch edge-deployment project, investigate ExecuTorch’s iOS integration. It provides a deployment runtime and supports platform-specific backends; it is a separate route from converting a PyTorch model to Core ML with coremltools.
Check the requirements of the particular ExecuTorch package and release. The current documented iOS package requires iOS 17 or later, but requirements can differ across releases and integration methods. Do not assume an older iPhone target is supported merely because a model runs on your development Mac.
The original guide associated PyTorch Mobile with dynamic networks and on-device training. That wording was too broad. Exporting and executing a model is not the same as supporting arbitrary Python control flow or training that model inside a shipping iOS app.
6. Metal: lower-level access to Apple GPUs
Metal provides graphics and GPU-compute capabilities. It matters to machine learning through Apple’s compute ecosystem and specialised implementations, but most beginners do not need to write GPU kernels to use a Core ML model.
Consider lower-level GPU work when profiling exposes a specific bottleneck or your algorithm needs an operation that the higher-level path cannot provide appropriately. A custom implementation adds development and testing work. Measure it against a simpler baseline before concluding that it improves performance or battery use.
7. MLX: an Apple-silicon machine learning ecosystem
MLX is an array framework for machine learning on Apple silicon. It is useful for experimentation and model development; related projects provide additional language and model tooling. It is not a promise that every MLX Python workflow can be dropped directly into an iPhone app.
MLX Swift provides real Apple-platform examples, including model evaluation and training examples. Check the supported platform, model implementation and package requirements of the particular project. Keep the distinction clear between training or experimenting on a Mac and shipping an inference feature on an iPhone. The best framework is the one that meets the app’s constraints with a maintainable integration.
8. Convert PyTorch or TensorFlow models to Core ML
A model developed in Python often needs an export step before an iOS app can use it. Apple’s Core ML Tools supports conversion, inspection and optimisation workflows. Conversion changes the model representation; it does not automatically reproduce your resizing, tokenisation, label mapping or other application code.
Two names are especially important. A neural-network-format Core ML model can use .mlmodel. An ML program is saved as a .mlpackage, which includes its weights. ML programs require iOS 15 or later. Specify the output representation and deployment target deliberately; the current default conversion output should not be saved blindly with the older filename extension.
Route A: direct PyTorch conversion with tracing
Tracing records operations performed for an example input. Here, a random tensor supplies the expected shape. It is not a realistic photograph and does not validate prediction quality. The example uses the current torchvision weights API instead of the older pretrained=True argument.
Python · example 1
import torch
import torchvision
import coremltools as ct
weights = torchvision.models.MobileNet_V2_Weights.DEFAULT
model = torchvision.models.mobilenet_v2(weights=weights)
model.eval()
example_input = torch.rand(1, 3, 224, 224)
traced_model = torch.jit.trace(model, example_input)
mlmodel = ct.convert(
traced_model,
inputs=[ct.TensorType(name="input", shape=example_input.shape)],
convert_to="mlprogram",
minimum_deployment_target=ct.target.iOS15,
)
mlmodel.save("MobileNetV2.mlpackage")
Before using it: use a compatible Python, PyTorch, torchvision and Core ML Tools environment. Downloading pretrained weights requires a network connection. The tensor input expects correctly prepared numerical data; use the weights’ documented transforms for resizing and normalisation. An image-input conversion needs an explicitly matched preprocessing design.
Calling model.eval() changes training-specific behaviour such as dropout and batch-normalisation handling. It does not make tracing safe for every model. If the model takes different branches for different input values, a trace may record only the branch exercised by the example.
What about scripting and dynamic control flow?
The original branching example is useful for understanding why tracing and scripting differ. TorchScript scripting analyses supported model code and can represent a data-dependent branch:
Python · example 2
import torch
class MyModel(torch.nn.Module):
def forward(self, x):
return x * 2 if x.sum() > 0 else x - 2
model = MyModel().eval()
scripted_model = torch.jit.script(model)
Keep this as a representation example, not a guarantee of Core ML deployment. Apple documents limited support for scripted models. Test the operators and both branches with the converter version you use. For a production model, follow its supported export workflow and compare the converted results with the original.
Route B: direct TensorFlow conversion
Apple documents conversion paths for supported TensorFlow models, including tf.keras.Model, SavedModel, HDF5 and concrete functions. Support depends on the model and toolchain; this is not a guarantee that every current TensorFlow or Keras installation works together.
Python · example 3
import tensorflow as tf
import coremltools as ct
tf_model = tf.keras.applications.MobileNetV2(
weights="imagenet",
input_shape=(224, 224, 3),
)
mlmodel = ct.convert(
tf_model,
inputs=[ct.TensorType(shape=(1, 224, 224, 3))],
convert_to="mlprogram",
minimum_deployment_target=ct.target.iOS15,
)
mlmodel.save("TensorFlowMobileNetV2.mlpackage")
This example is illustrative and needs a compatible, tested environment. TensorFlow MobileNetV2 expects its documented preprocessing, which scales image inputs to the range −1 to 1. That differs from the torchvision model’s convention. Also notice the tensor layouts: the PyTorch example uses channels first; this TensorFlow example uses channels last. A model can accept a correctly shaped tensor and still produce poor results if its values were prepared incorrectly.
Older TensorFlow 1 and 2 conversion examples remain useful background, but use the supported TensorFlow conversion guide for the actual input formats and version restrictions.
Route C: ONNX, with an important legacy warning
ONNX is an intermediate representation used to move models between compatible tools. PyTorch can export models to ONNX, and TensorFlow projects may use tf2onnx. Export support still depends on operators, shapes and exporter versions.
Python · example 4
import torch
import torchvision
weights = torchvision.models.ResNet18_Weights.DEFAULT
model = torchvision.models.resnet18(weights=weights).eval()
example_input = torch.rand(1, 3, 224, 224)
torch.onnx.export(model, example_input, "model.onnx")
The earlier guide then used the following bridge. It is retained here to explain existing projects, not as a recommended installation recipe for a new app:
Python · example 5
from onnx_coreml import convert
mlmodel = convert(model="model.onnx")
mlmodel.save("model_name.mlmodel")
The ONNX–Core ML converter repository is archived and unmaintained. Its older model format and supported operators differ from modern Core ML workflows. Do not assume modern coremltools accepts an ONNX file through this historical bridge. Prefer a supported direct conversion path when it fits your source model. An old environment may be needed to reproduce a legacy export, with careful validation before any migration.
The related INGOAMPT ONNX-versus-Core-ML article provides further background; apply the current compatibility warnings here when reading older examples.
Route D: specialised third-party exporters
Some model families need specialised export code. Hugging Face’s Exporters repository documents a Core ML command-line workflow for supported Transformer models. Its installation begins with the repository:
Shell · example 6
git clone https://github.com/huggingface/exporters.git
cd exporters
pip install -e .
python -m exporters.coreml \
--model=distilbert-base-uncased-finetuned-sst-2-english \
--feature=sequence-classification \
exported/
This replaces the earlier article’s undocumented export_model(...) Python call with the repository’s documented CLI pattern. Check the supported model and task, the exported package and compatible dependencies. A text app also needs the correct tokenizer, vocabulary and input shapes; a model file alone does not recreate the complete text-processing pipeline. Pin versions after you have a reproducible working export.
Put the exported model into your Xcode project
Add the supported .mlpackage or .mlmodel to your Xcode project and check that it belongs to the intended app target. Xcode can compile the model and generate a Swift interface. Inspect the model’s actual input names, types and dimensions in Xcode instead of copying a wrapper name from an unrelated tutorial.
Connect that interface to the same image preparation, tokenisation and label mapping used during evaluation. An image classifier exported with a tensor input still needs correctly prepared numerical arrays; a raw camera frame is not automatically the same input. For image-based models, consider whether an explicit image-input conversion and a Vision request would simplify your pipeline.
Run prediction work without blocking the interface. Keep the original source model and a few reference input/output pairs so you can check an app update later. Adding the model file is one integration step, not proof that the completed feature behaves correctly.
Test compatibility, accuracy and performance separately
A successful conversion is the beginning of validation. Keep a small, representative evaluation set that was not used for model training or framework selection. Include ordinary cases and difficult ones: rotated photos, poor lighting, unexpected text, empty inputs or background noise, depending on the feature.
- Check compatibility. Inspect the model’s input names, shapes, data types, output labels and minimum operating-system requirement. Confirm that the app applies the same preprocessing as the source model.
- Compare predictions. Run the original and converted models on identical prepared inputs. Inspect numerical differences and the resulting user-facing decisions, especially close to a classification boundary.
- Measure on real devices. Record model loading, first prediction and repeated inference separately. Test memory, energy and responsiveness on the oldest supported device, not only the simulator.
- Optimise and retest. Compression, quantisation or a different compute configuration can change model size, speed and output quality. Evaluate the trade-off again after each meaningful change.
Keep expensive work away from the main user-interface thread, show a useful loading state and provide a cancellation or fallback path where appropriate. If the result could be wrong, let the interface communicate that uncertainty. Better integration includes the experience around the model.
Readable maths: did conversion preserve useful results?
You do not need a complicated equation to start checking a converted model. These two measurements answer different questions: how much did the numerical outputs change, and how often did the classifier choose the correct label?
A preprocessing calculation you can check
Prepared value = pixel value ÷ 127.5 − 1
For this TensorFlow MobileNetV2 convention, an RGB channel value of 0 becomes −1, 127.5 becomes 0, and 255 becomes 1. This explains the input range in the TensorFlow example. It is not a universal formula for every model: the torchvision weights use their own documented normalisation.
Maximum absolute output difference
Maximum difference = max |original output − converted output|
Calculate the absolute difference for each corresponding output value, then take the largest. Suppose the original scores are [0.10, 0.70, 0.20] and the converted scores are [0.11, 0.68, 0.21]. The absolute differences are [0.01, 0.02, 0.01], so the maximum difference is 0.02. Both vectors select the second class in this example.
This is a fictional teaching example. A difference of 0.02 is not a universal pass threshold. Decide an acceptable tolerance for the model, precision and application. A tiny score change can still change the top label when two classes are nearly tied.
Classification accuracy
Accuracy = correct predictions ÷ total examples × 100%
If the converted model gets 45 of 50 independently labelled test images right, its accuracy on that set is 45 ÷ 50 × 100% = 90%. That does not establish 90% accuracy for every future photo, and it does not reveal which classes fail most often. Examine the five errors and compare per-class results before shipping.
Use both measurements with performance testing. A model that converts closely but repeatedly misclassifies your users’ inputs is still unsuitable. A model with useful accuracy can also be impractical if it stalls the interface or exceeds the device’s memory budget.
Try it: plan one small iOS feature
Choose a simple feature, such as organising your own photos into two categories. Write down the input, desired output, chosen framework, oldest supported device and one possible failure. Then describe how you would collect an evaluation set without reusing training examples.
Show a worked planning answer
For a two-class photo organiser, I could train a supported image classifier with Create ML and deploy it with Core ML, optionally using Vision to manage image requests. I would keep independently collected test photos, check orientation and cropping, compare source and deployed predictions, and measure real-device latency. If confidence is low, the app could ask the user to choose a category rather than filing the photo automatically.
To see INGOAMPT’s own app projects and their stated features, visit the iOS app catalog. Product pages explain what each app does; do not assume every app uses the same model or framework discussed in this lesson.
Frequently asked questions
Which machine learning framework should I start with for an iOS app?
For many Apple-platform apps, start by checking whether Vision already provides the feature you need. Use Core ML for a compatible custom model, and consider Create ML when you need to train a supported model on your Mac. Your data, device requirements and existing model pipeline determine the final choice.
Does using Core ML guarantee that my app is private or works offline?
No. On-device inference can process model inputs locally, but privacy and offline behaviour depend on the whole app. Check downloads, analytics, network features and any other processing before making those promises.
Should a converted model use .mlmodel or .mlpackage?
It depends on the representation. ML programs are saved as .mlpackage and require iOS 15 or later. Older neural-network-format models may use .mlmodel. Specify the conversion target and follow the format requirements for your model.
Can I still follow a TensorFlow Lite tutorial?
TensorFlow Lite is now called LiteRT. Older tutorials may explain useful concepts, but check Google’s current iOS documentation for supported runtimes, package names, model conversion and integration details.
Is ONNX-to-Core-ML conversion still the recommended default?
No. The old onnx-coreml repository is archived and unmaintained. Keep that route as legacy background, and prefer a supported direct conversion workflow when it fits your model. Always validate operators and results.
Does a successful conversion mean the model is ready to ship?
No. Check preprocessing, numerical outputs, task accuracy, operating-system compatibility and real-device performance. Include difficult inputs and a useful fallback in the app before releasing the feature.
Sources and further reading
Use these primary references to verify an API or check what changed after this lesson’s review. Documentation examples are starting points; the conversion snippets above have not been runtime-tested against your own model or dependency environment.
- Apple: Core ML and Create ML.
- Apple: Vision and Metal.
- Apple Core ML Tools: ML programs and package format.
- Apple Core ML Tools: PyTorch conversion and TensorFlow conversion.
- Torchvision: MobileNetV2 weights and preprocessing.
- Google: LiteRT for iOS.
- PyTorch: ExecuTorch on iOS.
- MLX project, archived ONNX–Core ML converter and Hugging Face Exporters.
Keep learning, then build something useful.
Continue the series or explore INGOAMPT’s iOS app projects.
