1. Setup the Anaconda environment
- Download, install and run Anaconda.
- Select the Environments tab on the left.
- Click the Update index… button and wait for the update to finish.
- Click the Create button.
- Create a new environment with the following settings:
- Name: mxnet2onnx
- Leave Python checked and select the 3.7 version.
- Leave R unchecked.
2. Install the dependencies
- Open a new Terminal.
- Type the following command to activate the new environment:
conda activate mxnet2onnx
- Type the following command and press y when prompted:
conda install -c conda-forge protobuf numpy
- Type the following commands to install the version 1.2.1 of ONNX:
export ONNX_ML=1 pip install onnx==1.2.1
- Finally, type the following command to install the latest stable version of MXnet:
pip install mxnet
3. Convert the model
- Return to Anaconda and select the Home tab from the left.
- Make sure the mxnet2onnx environment is selected.
- Locate the jupyter notebook application and click the Install button.
- Wait for the installation to finish and the click the Launch button.
- Navigate to your Documents folder.
- Select New -> Python3 to create a new notebook.
- Type the following code in the first cell and the click Shift+Enter to execute it (and create a new cell at the same time). This will download a pre-trained MXnet model.
path='http://data.mxnet.io/models/imagenet/' [mx.test_utils.download(path+'resnet/18-layers/resnet-18-0000.params'), mx.test_utils.download(path+'resnet/18-layers/resnet-18-symbol.json'), mx.test_utils.download(path+'synset.txt')]
- Type the following code in a new cell and then press Shift+Enter:
import mxnet as mx import numpy as np from mxnet.contrib import onnx as onnx_mxnet import logging logging.basicConfig(level=logging.INFO) # Downloaded input symbol and params files sym = './resnet-18-symbol.json' params = './resnet-18-0000.params' # Standard Imagenet input - 3 channels, 224*224 input_shape = (1,3,224,224) # Path of the output file onnx_file = './mxnet_exported_resnet50.onnx' # Invoke export model API. It returns path of the converted onnx model converted_model_path = onnx_mxnet.export_model(sym, params, [input_shape], np.float32, onnx_file)
4. Check the new ONNX model
Type the following code in a new cell and then press Shift+Enter:
from onnx import checker import onnx # Load onnx model model_proto = onnx.load_model(converted_model_path) # Check if converted ONNX protobuf is valid checker.check_graph(model_proto.graph)
If you see no errors then you are good to go!
5. Common Errors
No conversion function registered for op type SoftmaxActivation yet.
SoftmaxActivation is deprecated:
Use softmax instead:
https://mxnet.incubator.apache.org/api/python/docs/api/symbol/op/index.html#mxnet.symbol.op.softmax
You must also use axis=1:
https://github.com/onnx/onnx/issues/2000
Leave a Reply