importNetworkFromONNX - Import ONNX network as MATLAB network - MATLAB (original) (raw)

Import ONNX network as MATLAB network

Since R2023b

Syntax

Description

[net](#mw%5F1aabd2ec-7766-470c-9aab-985ed88d5a99) = importNetworkFromONNX([modelfile](#mw%5Fecee971f-ed4f-40eb-9700-5c75d720c53e)) imports a pretrained Open Neural Network Exchange (ONNX™) network from the file modelfile. The function returns the network net as an initialized dlnetwork object.

importNetworkFromONNX requires the Deep Learning Toolbox™ Converter for ONNX Model Format support package. If this support package is not installed, thenimportNetworkFromONNX provides a download link.

Note

The importNetworkFromONNX function can generate a custom layer when importing an ONNX layer. For more information, see Algorithms. The function saves the generated custom layers in the+ modelfile namespace.

example

[net](#mw%5F1aabd2ec-7766-470c-9aab-985ed88d5a99) = importNetworkFromONNX([modelfile](#mw%5Fecee971f-ed4f-40eb-9700-5c75d720c53e),[Name=Value](#namevaluepairarguments)) imports a pretrained ONNX network with additional options specified by one or more name-value arguments. For example, Namespace="CustomLayers" saves any generated custom layers and associated functions in the +CustomLayers namespace in the current folder.

example

Examples

collapse all

Import a pretrained ONNX network as a dlnetwork object and use the imported network to classify an image.

Generate an ONNX model of the SqueezeNet convolution neural network.

[squeezeNet,ClassNames] = imagePretrainedNetwork("squeezenet"); exportONNXNetwork(squeezeNet,"squeezeNet.onnx");

Import the pretrained squeezeNet.onnx model.

net = importNetworkFromONNX("squeezeNet.onnx")

net = dlnetwork with properties:

     Layers: [70×1 nnet.cnn.layer.Layer]
Connections: [77×2 table]
 Learnables: [52×3 table]
      State: [0×3 table]
 InputNames: {'data'}
OutputNames: {'prob_flatten_ReshapeOutput'}
Initialized: 1

View summary with summary.

Read the image you want to classify and display the size of the image. The image has a size of 384-by-512 pixels and has three color channels (RGB).

I = imread("peppers.png"); size(I)

Resize the image to the input size of the network. Show the image.

I = imresize(I,[227 227]); imshow(I)

Figure contains an axes object. The hidden axes object contains an object of type image.

Convert the image to a dlarray object. Format the images with the dimensions "SSCB" (spatial, spatial, channel, batch). In this case, the batch size is 1 and you can omit it ("SSC").

I_dlarray = dlarray(single(I),"SSC");

Classify the sample image and find the predicted label.

prob = predict(net,I_dlarray); [~,label] = max(prob);

Display the classification result.

Import a pretrained ONNX network that results in an uninitialized network. Then initialize the network.

Specify the model file and import the model using the importNetworkFromONNX function. Since this model has an input layer with an unknown format or size, the function imports the model as an uninitialized dlnetwork object. The software displays a warning that describes how to initialize the network.

ScalarOutputModel = 'dScalarGraphOutput.onnx'; net = importNetworkFromONNX(ScalarOutputModel);

Warning: Returning an uninitialized dlnetwork because some input layers have unknown data formats or undetermined image sizes. Initialize the network by passing example input data to the initialize object function.

The custom input layer describes how to find the required input information.

ans = 4×1 Layer array with layers:

 1   'input_1'                         Custom input ('UUU')                               See the InputInformation property to find the required input dimension ordering for this layer.
 2   'Transpose_To_SoftmaxLayer1000'   dScalarGraphOutput.Transpose_To_SoftmaxLayer1000   dScalarGraphOutput.Transpose_To_SoftmaxLayer1000
 3   'x16Output'                       Custom output ('UUU')                              See the OutputInformation property to find the output dimension ordering that is produced by this layer.
 4   'x19Output'                       Custom output ('UU')                               See the OutputInformation property to find the output dimension ordering that is produced by this layer.

net.Layers(1).InputInformation

ans = "Layer input must be a labeled dlarray with the dimension order shown in the ONNX model file. You must pass the size: (1, 1, 320) The dlarray must have a format string consisting of one 'U' for each dimension: 'dlarray(data, 'UUU')'"

Create a labeled dlarray example input with the required size and initialize the network.

X = dlarray(rand(1, 1, 320), 'UUU'); net = initialize(net, X); summary(net)

Initialized: true

Number of learnables: 53.7k

Inputs: 1 'input_1' Initialized using data of size 1×1×320 (UUU)

Import a pretrained ONNX network as a dlnetwork object and use the imported network to classify a preprocessed image.

Specify the model file to import as shufflenet with operator set 9 from the ONNX Model Zoo. shufflenet is a convolutional neural network that is trained on more than a million images from the ImageNet database. As a result, the network has learned rich feature representations for a wide range of images. The network can classify images into 1000 object categories, such as keyboard, mouse, pencil, and many animals.

modelfile = "shufflenet-9.onnx";

Import the class names from SqueezeNet, which is also trained with images from the ImageNet database.

[~,ClassNames] = imagePretrainedNetwork("squeezenet");

Import shufflenet. By default, importNetworkFromONNX imports the network as a dlnetwork object. Specify the namespace to save custom layers in as shufflenet_9.

net = importNetworkFromONNX(modelfile,Namespace="shufflenet_9")

net = dlnetwork with properties:

     Layers: [174×1 nnet.cnn.layer.Layer]
Connections: [189×2 table]
 Learnables: [198×3 table]
      State: [98×3 table]
 InputNames: {'gpu_0_data_0'}
OutputNames: {'gpu_0_softmax_1Output'}
Initialized: 1

View summary with summary.

Read the image you want to classify and display the size of the image. The image has a size of 792-by-1056 pixels and has three color channels (RGB).

I = imread("peacock.jpg"); size(I)

Check the input size of the network and resize the input image. Show the resized image.

I = imresize(I,[224 224]); imshow(I)

The inputs to shufflenet require further preprocessing (for details, see ShuffleNet in ONNX Model Zoo). Rescale the image. Normalize the image by subtracting the mean of the training images and dividing by the standard deviation of the training images.

I = rescale(I,0,1);

meanIm = [0.485 0.456 0.406]; stdIm = [0.229 0.224 0.225]; I = (I - reshape(meanIm,[1 1 3]))./reshape(stdIm,[1 1 3]);

imshow(I)

Classify the image using the imported network.

prob = predict(net,I); [~,label] = max(prob); ClassNames{label}

Import a pretrained ONNX network, which contains operators that the software cannot convert to built-in MATLAB layers. The software automatically generates custom layers when you import this network.

This example uses the findCustomLayers helper function. To view the code for this function, see Helper Function.

Specify the model file to import as shufflenet with operator set 9 from the ONNX Model Zoo. shufflenet is a convolutional neural network that is trained on more than a million images from the ImageNet database. As a result, the network has learned rich feature representations for a wide range of images. The network can classify images into 1000 object categories, such as keyboard, mouse, pencil, and many animals.

modelfile = "shufflenet-9.onnx";

Import shufflenet. By default, importNetworkFromONNX imports the network as a dlnetwork object. importNetworkFromONNX saves each generated custom layer to a separate M file in the +shufflenet_9 namespace in the current folder.

net = importNetworkFromONNX(modelfile,Namespace="shufflenet_9")

net = dlnetwork with properties:

     Layers: [174×1 nnet.cnn.layer.Layer]
Connections: [189×2 table]
 Learnables: [198×3 table]
      State: [98×3 table]
 InputNames: {'gpu_0_data_0'}
OutputNames: {'gpu_0_softmax_1Output'}
Initialized: 1

View summary with summary.

Find the indices of the automatically generated custom layers by using the findCustomLayers helper function and display the custom layers.

ind = findCustomLayers(net.Layers,'+shufflenet_9'); net.Layers(ind)

ans = 16×1 Layer array with layers:

 1   'Reshape_To_ReshapeLayer1285'   shufflenet_9.Reshape_To_ReshapeLayer1285   shufflenet_9.Reshape_To_ReshapeLayer1285
 2   'Reshape_To_ReshapeLayer1290'   shufflenet_9.Reshape_To_ReshapeLayer1290   shufflenet_9.Reshape_To_ReshapeLayer1290
 3   'Reshape_To_ReshapeLayer1295'   shufflenet_9.Reshape_To_ReshapeLayer1295   shufflenet_9.Reshape_To_ReshapeLayer1295
 4   'Reshape_To_ReshapeLayer1300'   shufflenet_9.Reshape_To_ReshapeLayer1300   shufflenet_9.Reshape_To_ReshapeLayer1300
 5   'Reshape_To_ReshapeLayer1305'   shufflenet_9.Reshape_To_ReshapeLayer1305   shufflenet_9.Reshape_To_ReshapeLayer1305
 6   'Reshape_To_ReshapeLayer1310'   shufflenet_9.Reshape_To_ReshapeLayer1310   shufflenet_9.Reshape_To_ReshapeLayer1310
 7   'Reshape_To_ReshapeLayer1315'   shufflenet_9.Reshape_To_ReshapeLayer1315   shufflenet_9.Reshape_To_ReshapeLayer1315
 8   'Reshape_To_ReshapeLayer1320'   shufflenet_9.Reshape_To_ReshapeLayer1320   shufflenet_9.Reshape_To_ReshapeLayer1320
 9   'Reshape_To_ReshapeLayer1325'   shufflenet_9.Reshape_To_ReshapeLayer1325   shufflenet_9.Reshape_To_ReshapeLayer1325
10   'Reshape_To_ReshapeLayer1330'   shufflenet_9.Reshape_To_ReshapeLayer1330   shufflenet_9.Reshape_To_ReshapeLayer1330
11   'Reshape_To_ReshapeLayer1335'   shufflenet_9.Reshape_To_ReshapeLayer1335   shufflenet_9.Reshape_To_ReshapeLayer1335
12   'Reshape_To_ReshapeLayer1340'   shufflenet_9.Reshape_To_ReshapeLayer1340   shufflenet_9.Reshape_To_ReshapeLayer1340
13   'Reshape_To_ReshapeLayer1345'   shufflenet_9.Reshape_To_ReshapeLayer1345   shufflenet_9.Reshape_To_ReshapeLayer1345
14   'Reshape_To_ReshapeLayer1350'   shufflenet_9.Reshape_To_ReshapeLayer1350   shufflenet_9.Reshape_To_ReshapeLayer1350
15   'Reshape_To_ReshapeLayer1355'   shufflenet_9.Reshape_To_ReshapeLayer1355   shufflenet_9.Reshape_To_ReshapeLayer1355
16   'Reshape_To_ReshapeLayer1360'   shufflenet_9.Reshape_To_ReshapeLayer1360   shufflenet_9.Reshape_To_ReshapeLayer1360

Helper Function

This section defines the findCustomLayers helper function. findCustomLayers returns the indices of the custom layers that importNetworkFromONNX automatically generates.

function indices = findCustomLayers(layers,Namespace)

s = what(['.' Namespace]);

indices = zeros(1,length(s.m)); for i = 1:length(layers) for j = 1:length(s.m) if strcmpi(class(layers(i)),[Namespace(2:end) '.' s.m{j}(1:end-2)]) indices(j) = i; end end end

end

Input Arguments

collapse all

Name of ONNX model file , specified as a character vector or string scalar. Themodelfile must be in the current folder, or you must include a full or relative path to the file.

Example: "cifarResNet.onnx"

Name-Value Arguments

collapse all

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Example: importNetworkFromONNX(modelfile,InputDataFormats="BCSS") imports the network in modelfile as a dlnetwork object where the dimension order of each input to the ONNX network is batch, channel, spatial, spatial.

Name of the custom layers namespace in which importNetworkFromONNX saves custom layers, specified as a character vector or string scalar.importNetworkFromONNX saves the custom layers namespace+`Namespace` in the current folder. If you do not specify Namespace, then importNetworkFromONNX saves the custom layers in a namespace named+[modelfile](#mw%5Fecee971f-ed4f-40eb-9700-5c75d720c53e) in the current folder. For more information about namespaces, see Create Namespaces.

Example: Namespace="shufflenet_9"

Example: Namespace="CustomLayers"

Data format of the ONNX network inputs, specified as a character vector, string scalar, or string array. importNetworkFromONNX tries to interpret the input data formats from the ONNX file. Use this name-value argument when importNetworkFromONNX cannot determine the input data formats.

Set InputDataFomats to a data format in the ordering of an ONNX input tensor. For example, if you specifyInputDataFormats as "BCSS" (batch channel spatial spatial), the imported MATLAB® network has one imageInputLayer input, where the dimension order of each input is "SSCB" (spatial spatial channel batch). For more information about how importNetworkFromONNX interprets the data format of ONNX input tensors and how to specify InputDataFormats for different Deep Learning Toolbox input layers, see Conversion of ONNX Input Tensors into Deep Learning Toolbox Layers.

If you specify an empty data format ([] or""), importNetworkFromONNX automatically interprets the input data format.

Example: InputDataFormats='BCSS'

Example: InputDataFormats="BCSS"

Example: InputDataFormats=["BCSS","","BC"]

Example: InputDataFormats={'BCSS',[],'BC'}

Data Types: char | string | cell

Data format of the ONNX network outputs, specified as a character vector, string scalar, or string array. importNetworkFromONNX tries to interpret the output data formats from the ONNX file. Use this name-value argument when importNetworkFromONNX cannot determine the output data formats.

Set OutputDataFormats to a data format in the ordering of an ONNX output tensor. For example, if you specifyOutputDataFormats as "BC" (batch,channel), the imported MATLAB network has one nnet.onnx.layer.CustomOutputLayer output where the dimension order of each output is "CB" (channel,batch). For more information about how importNetworkFromONNX interprets the data format of ONNX output tensors and how to specify OutputDataFormats for different Deep Learning Toolbox output formats, see Conversion of ONNX Output Tensors into MATLAB Output Formats.

If you specify an empty data format ([] or""), importNetworkFromONNX automatically interprets the output data format.

Example: OutputDataFormats='BC'

Example: OutputDataFormats="BC"

Example: OutputDataFormats=["BCSS","","BC"]

Example: OutputDataFormats={'BCSS',[],'BC'}

Data Types: char | string | cell

Since R2025a

Flag to generate coder files for automatically generated custom layers, specified as logical 1(true) or 0(false). IfGenerateCoderFiles=true, then importNetworkFromONNX generates a +`coder` namespace inside the custom layer namespace denoted by Namespace. The+`coder` namespace contains the MATLAB Coder™ compatible custom layers and operators that are used for generic C/C++ code generation. Disable generation of coder files by specifyingGenerateCoderFiles=false for faster import of ONNX network if you do not intend to do code generation.

If the network has no layers imported as automatically generated custom layers, then no coder files are generated.

To learn more about code generation, see Generate Generic C/C++ Code for Deep Learning Networks (MATLAB Coder).

Example: GenerateCoderFiles=false

Data Types: logical

Output Arguments

collapse all

Pretrained ONNX network, returned as a dlnetwork object. In some cases, the software cannot input data formats, sizes, or imports ONNX operators as placeholder functions, resulting in an uninitialized network. If so, you must initialize the network by using the initialize function. You can predict class labels by using the predict function with this network. Specify the input data as a dlarray object using the correct data format. For more information, see the fmt argument of dlarray.

Limitations

Note

If you import an exported network, layers of the reimported network might differ from layers of the original network, and might not be supported.

More About

collapse all

importNetworkFromONNX supports these ONNX operators for conversion into built-in MATLAB layers, with some limitations.

* If importNetworkFromONNX imports theConv ONNX operator as a convolution2dLayer object and theConv operator is a vector with only two elements[p1 p2], importNetworkFromONNX sets thePadding option of convolution2dLayer to[p1 p2 p1 p2].

ONNX Operator ONNX Importer Custom Layer
Clip nnet.onnx.layer.ClipLayer
Div nnet.onnx.layer.ElementwiseAffineLayer
Flatten nnet.onnx.layer.FlattenLayer ornnet.onnx.layer.Flatten3dLayer
ImageScaler nnet.onnx.layer.ElementwiseAffineLayer
Reshape nnet.onnx.layer.FlattenLayer
Sub nnet.onnx.layer.ElementwiseAffineLayer

importNetworkFromONNX tries to interpret the data format of the ONNX network's input and output tensors, and then convert them into built-in MATLAB input layers and output formats. For details about the interpretation, seeConversion of ONNX Input Tensors into Deep Learning Toolbox Layers and Conversion of ONNX Output Tensors into MATLAB Output Formats.

In Deep Learning Toolbox, each data format character must be one of these labels:

Conversion of ONNX Input Tensors into Deep Learning Toolbox Layers

Data Formats Data Interpretation Deep Learning Toolbox Layer
ONNX Input Tensor MATLAB Input Format Shape Type
BC CB c_-by-n array, where_c is the number of features and n is the number of observations Features featureInputLayer
BCSS, BSSC, CSS,SSC SSCB _h_-by-_w_-by-_c_-by-n numeric array, where h, w,c, and n are the height, width, number of channels of the images, and number of observations, respectively 2-D image imageInputLayer
BCSSS, BSSSC, CSSS,SSSC SSSCB _h_-by-_w_-by-_d_-by-_c_-by-n numeric array, where h, w,d, c, and n are the height, width, depth, number of channels of the images, and number of image observations, respectively 3-D image image3dInputLayer
TBC CBT _c_-by-_s_-by-n matrix, where c is the number of features of the sequence,s is the sequence length, and n is the number of sequence observations Vector sequence sequenceInputLayer
TBCSS SSCBT _h_-by-_w_-by-_c_-by-s_-by-n array, where h, w, c, and n correspond to the height, width, and number of channels of the image, respectively, s is the sequence length, and_n is the number of image sequence observations 2-D image sequence sequenceInputLayer
TBCSSS SSSCBT _h_-by-_w_-by-_d_-by-_c_-by-_s_-by-n array, where h, w, d, and c correspond to the height, width, depth, and number of channels of the image, respectively, s is the sequence length, and n is the number of image sequence observations 3-D image sequence sequenceInputLayer

Conversion of ONNX Output Tensors into MATLAB Output Formats

Data Formats
ONNX Output Tensor MATLAB Output Format
BC, TBC CB, CBT
BCSS, BSSC, CSS,SSC, BCSSS, BSSSC,CSSS, SSSC SSCB, SSSCB
TBCSS, TBCSSS SSCBT, SSSCBT

You can use MATLAB Coder or GPU Coder™ software with Deep Learning Toolbox software to generate MEX, standalone CPU, CUDA® MEX, or standalone CUDA code for an imported network. For more information, see Generate Code and Deploy Deep Neural Networks.

importNetworkFromONNX returns the networknet as a dlnetwork object. This object supports code generation. For more information about MATLAB Coder and GPU Coder support for Deep Learning Toolbox objects, see Supported Classes (MATLAB Coder) and Supported Classes (GPU Coder), respectively.

You can generate code for any imported network whose layers support code generation. For lists of the layers that support code generation with MATLAB Coder and GPU Coder, see Supported Layers (MATLAB Coder) and Supported Layers (GPU Coder), respectively. For more information about the code generation capabilities and limitations of each built-in MATLAB layer, see the Extended Capabilities section of the layer. For example, seeCode Generation and GPU Code Generation of imageInputLayer.

importNetworkFromONNX does not execute on a GPU. However,importNetworkFromONNX imports a pretrained neural network for deep learning as a dlnetwork object, which you can use on a GPU.

Using a GPU requires a Parallel Computing Toolbox™ license and a supported GPU device. For information about supported devices, see GPU Computing Requirements (Parallel Computing Toolbox).

Tips

Algorithms

The importNetworkFromONNX function imports an ONNX operator into MATLAB by trying these steps in order:

  1. The function tries to import the ONNX operator as a built-in MATLAB layer. For more information, see ONNX Operators Supported for Conversion into Built-In MATLAB Layers.
  2. The function tries to import the ONNX operator as a custom layer. importNetworkFromONNX saves the generated custom layers and the associated functions in the+[Namespace](#mw%5F211c6450-1fc1-4a0b-b7da-2dba60892857%5Fsep%5Fmw%5Fa36c5ab1-de33-4d97-a738-f615ec8855d4) namespace. For an example, seeImport ONNX Network with Automatically Generated Custom Layers.
  3. The function imports the ONNX operator as a custom layer with a placeholder function. You must complete the placeholder function before you can use the network.

If these steps do not result in an imported network, you can use the importONNXFunction function. importONNXFunction imports the model as an ONNXParameters object, which contains the network parameters, and a model function, which contains the network architecture.

In some cases, the software indicates that you need to initialize the imported network.

Alternative Functionality

Block

You can also work with ONNX networks by using the ONNX Model Predict block. This block additionally allows you to load ONNX functions to preprocess and postprocess data, and to configure input and output ports interactively.

References

Version History

Introduced in R2023b

expand all

You can now generate MATLAB Coder compatible files used in generic C/C++ code generation of automatically generated custom layers. MATLAB Coder files are generated by default using the newGenerateCoderFiles name-value argument.

You can import the following ONNX operators into Deep Learning Toolbox layers:

You can import the following ONNXHardSwish operator into a custom layer.

importNetworkFromONNX supports ONNX operator sets 6 to 20.

When importing networks resulting in placeholders for custom layers and unsupported operators, you can now define the placeholder function once in the generated placeholder function template present in the +modelfile/+ops namespace. The automatically generated custom layers also have the specific placeholder function calls instead of the previously generic PLACEHODLER function calls. For e.g. the generated placeholder function template onnxAcos.m contains

function varargout = onnxAcos(varargin) % Placeholder function implementation for ONNX operator: Acos error("Operator function 'Acos' is not supported. The placeholder function 'onnxAcos.m' must be implemented before the network can be used."); end

Now, the specific placeholder function call will be as follows:

% Execute the operators: % PLACEHOLDER FUNCTION FOR UNSUPPORTED OPERATOR (Acos): [output] = modelfile.ops.onnxAcos(input);

where before R2025a it was as follows:

% Execute the operators: % PLACEHOLDER FUNCTION FOR UNSUPPORTED OPERATOR (Acos): [output] = PLACEHOLDER(input);

The importNetworkFromONNX function shows improved performance in downstream inference using the imported network due to internal optimizations in the automatically generated custom layer representation. These performance improvements are more noticeable with larger models and result in more concise custom layer code. For example, the inference prediction in this code is about 1.4x faster than in the previous release:

url = "https://github.com/onnx/models/raw/main/Computer_Vision/" + ... "convnext_base_Opset18_torch_hub/convnext_base_Opset18.onnx"; filename = "convnext_base_Opset18.onnx"; websave(filename,url,weboptions("Timeout",10));

function timingTest(net,x) net.predict(x); end net = importNetworkFromONNX('convnext_base_Opset18.onnx'); x = dlarray(rand([1,3,224,224], 'single'), "BCSS"); % input image f = @()timingTest(net, x);

for i = 1:10 timeit(f) % the first 5 runs are inference warmup rounds end % the recorded time uses the mean of the next 5 runs

The approximate execution times are:

The code was timed on a Windows® 11, Intel Xeon® W-2133CPU @ 3.6 GHz test system by calling the functiontimeit.

You can import the following ONNX operators into Deep Learning Toolbox layers:

You can import the following ONNX operators into custom layers:

importNetworkFromONNX supports ONNX intermediate representation version 9 and ONNX operator sets 6 to 18.