MATLAB: How to implement the trained regression model from the Regression Learner App in Simulink

applearnermodelregressionsimulink

I have trained a model using Regression Learner App. How can I use the trained model to predict new output by using in a Simulink model?

Best Answer

Please refer to the following documentation page which explains the required workflow using a classification model example.
In R2019, we introduced new capabilities for implementing trained machine learning models in Simulink using "saveLearnerForCoder" and "loadLearnerForCoder" functions.
For R2019a and previous releases:
In general, predictions from trained machine learning models can be obtained using "MATLAB Function Block" in Simulink models. Please refer to the following documentation page for more information about "MATLAB Function Block".
Please use following steps to implement this workflow.
1) Train ML model
The trained ML model can be obtained using the following ways. Here "Linear SVM" regression model is used as an example.
  • Train model in Regression Learner app and then export the model to workspace. A structure variable with some metadata will be saved in workspace. Extract the trained model from that variable.
Mdl = trainedModel.RegressionSVM;
Please refer to following article for more information.
  • Train the model programmatically.
Mdl = fitrsvm(X, y, 'KernelFunction', 'linear', 'PolynomialOrder', [], 'KernelScale', 'auto', 'Standardize', true);
2) Save trained model in MAT-file
save('RegressionModel.mat','Mdl')
3) Create a MATLAB Function Block in Simulink Model
In a Simulink model, create a MATLAB Function Block that will load the trained model and give new prediction for input data.
function y = RegressionPredict(X)
% X should have same number of columns/predictors
% as were used while training model
load('RegressionModel.mat');
% declare predict as extrinsic function
coder.extrinsic('predict')
y = predict(Mdl,X);
Please refer to the following documentation for more information about "coder.extrinsic"