How to import a random forest regression model (made with sklearn (scikit-learn) in python) into Simulink?

Hi, I created a random forest regression model in python using sklearn with the following function:
Now, I need to implement this model in Simulink for further use, I tried to save the files with Joblib, ONNX and HDF5 files in python, read these files in MATLAB and then implement it in Simunlink as an LTI-system but with no succes.
used py.pickle.load(py.open('Filename.sav','rb'))
ONNX: https://onnx.ai/sklearn-onnx/
used importONNXNetwork('Filename.onnx')
Any Idea how to import a model created with sklearn in python into Simulink?
Thanks in advance

Answers (1)

Hi,
You can make use of MATLAB Python interface. check
You can create a MATLAB function block in Simulink and use python commands directly in the function.
Example MATLAB funtion (For training):
regressor = py.sklearn.ensemble.RandomForestRegressor(n_estimators=100, random_state=0)
regressor.fit(x, y)
py.joblib.dump(regressor, "./random_forest.joblib")
Example MATLAB funtion (For loading the model):
loaded_rf = py.joblib.load("./random_forest.joblib")
For this to work, you need python installed in you system which is compatible with MATLAB. check compatibility
Install required libraries in Python using pip.
Hope it helps.

Asked:

on 27 Feb 2023

Edited:

on 20 Apr 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!