Core ML Tools

9.0 · active · verified Sat Apr 11

Core ML Tools is an open-source Python package developed by Apple for converting, optimizing, and validating machine learning models into Apple's Core ML format. It supports models from popular frameworks like TensorFlow, PyTorch, scikit-learn, XGBoost, and LibSVM. The library is actively maintained, with frequent releases, and is currently at version 9.0, adding support for Python 3.13, PyTorch 2.7, and new iOS/macOS deployment targets.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to convert a pre-trained PyTorch MobileNetV2 model to the Core ML format using `coremltools`. It involves defining a PyTorch model, tracing it with a dummy input, and then using `ct.convert` to generate the `.mlpackage` file. Explicitly defining input types and preprocessing parameters is crucial for correct conversion.

import coremltools as ct
import torch
import torchvision

# 1. Define a PyTorch model
model = torchvision.models.mobilenet_v2(pretrained=True)
model.eval()

# 2. Create a dummy input for tracing
example_input = torch.rand(1, 3, 224, 224)

# 3. Trace the model (or use torch.export in newer PyTorch/coremltools versions)
traced_model = torch.jit.trace(model, example_input)

# 4. Convert the traced model to Core ML format
# Specify inputs explicitly for correct type and shape handling
# For image inputs, use ct.ImageType with appropriate preprocessing parameters
mlmodel = ct.convert(
    traced_model,
    inputs=[
        ct.ImageType(name="input_1", shape=example_input.shape, scale=1/255.0, bias=, channel_first=True)
    ],
    convert_to='mlprogram',
    minimum_deployment_target='iOS16'
)

# 5. Save the Core ML model
mlmodel.save("MobileNetV2.mlpackage")
print("Model converted and saved as MobileNetV2.mlpackage")

view raw JSON →