Python in Matlab for ONNX
19 views (last 30 days)
Show older comments
Hello
Currently, Matlab only allows you to convert net.mat to ONNX format as Deep Learning. What if it's a simple Mdl-type machine? How can I convert it to ONNX?
I read on forums that this can be done in Python, apparently.
Has anyone gone down this route and used the online version of MATLAB Drive?
Thanks in advance for any information.
0 Comments
Answers (1)
Aditya
on 24 Sep 2025 at 16:59
Hi Bartlomiej ,
MATLAB only supports exporting deep learning models (such as those created with the Deep Learning Toolbox) directly to ONNX format. Classic machine learning models, typically saved as Mdl objects (like decision trees, SVMs, or ensembles), cannot be exported to ONNX from MATLAB itself. If you want to convert such models to ONNX, the most practical solution is to transfer your model parameters or training data to Python, reconstruct or retrain the model using a library like scikit-learn, and then use the skl2onnx package to export the model to ONNX format. MATLAB Drive can help you move files between MATLAB and Python, but it doesn't provide any additional conversion capabilities.
% Train a classification tree and save it
Mdl = fitctree(X, Y);
saveCompactModel(Mdl, 'treeModel');
% Or save your training data:
save('trainingData.mat', 'X', 'Y');
For python code:
# Load your training data (exported from MATLAB)
import scipy.io
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType
mat = scipy.io.loadmat('trainingData.mat')
X = mat['X']
y = mat['Y'].ravel() # Ensure y is 1D
# Train a similar model in Python
clf = DecisionTreeClassifier()
clf.fit(X, y)
# Convert to ONNX
initial_type = [('float_input', FloatTensorType([None, X.shape[1]]))]
onnx_model = convert_sklearn(clf, initial_types=initial_type)
with open("tree_model.onnx", "wb") as f:
f.write(onnx_model.SerializeToString())
0 Comments
See Also
Categories
Find more on Classification Ensembles in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!