Hello there π,
In this post, I will show you how to convert a FastAI model to ONNX and CoreML.
Convert a FastAI model to Pytorch
Before we can convert the model to ONNX format or CoreML, we need to convert it to Pytorch first.
This is a simple process. Assuming that the model is trained, we need to call torch.save
to export the model:
|
|
Convert a FastAI model to ONNX
ONNX is a standard for machine learning models. It allows you to convert a model from a framework like PyTorch or TensorFlow to its format in order to be used in different runtimes, for exampl Windows, Android, Linux, MacOS and iOS and from various programming languages like C#, C++, Java, JavaScript and Python.
To convert your FastAI model to ONNX, follow these steps:
Assuming that you have the torch
package installed, to convert the model to ONNX you need to run the following:
|
|
I’m using torch.randn
to create a dummy input. This is required by the torch.onnx.export
function.
Since I am exporting a image classification model, the input shape is (1, 3, 224, 224)
. The first dimension is the
batch size, the second is the number of channels, and the last two are the width and height of the image.
Convert a FastAI model to CoreML
CoreML is a framework developed by Apple that allows you to run machine learning models on the Apple ecosystem, which includes: iOS, MacOS, iPadOS, watchOS and tvOS.
According to the CoreML documentation, you will need a MacOS or a Linux machine to convert your model to CoreML. I tried to convert the model on Windows, but I got an error.
To convert your FastAI model to CoreML, follow these steps, in a new project:
- Create a new Python project with Python 3.10 and install the following packages:
|
|
- Create a new file called
main.py
and add the following code:
|
|
- Run the script:
|
|
You should get a file called resnet151.mlpackage
. This is the CoreML model.
That’s it! Thank you for reading! π