Main Content

Predict Responses Using Custom Python Model in Simulink

This example shows how to use the Custom Python Model Predict block for prediction in Simulink®. The block accepts an observation (consisting of predictor data and a noisy response), and sends it to a custom Python® model that is configured for prediction. The block executes the custom model in Python and returns the predicted response and mean squared error for the observation.

MATLAB® supports the reference implementation of Python, often called CPython. If you use a Mac or Linux® platform, you already have Python installed. If you use Windows®, you need to install a distribution, such as those found at https://www.python.org/downloads/. For more information, see Configure Your System to Use Python.

The Custom Python Model Predict block requires a custom Python model that defines a load_model() function and a predict() function. This example provides the saved model custom.py, which defines a load_model() function that loads the coefficients for a multiple linear regression model with two predictors, and a predict() function that returns the predicted response and mean squared error for the input observation.

Open Provided Simulink Model

This example provides the Simulink model slexCustomPythonModelPredictExample.slx, which includes the Custom Python Model Predict block. You can open the Simulink model or create a new model as described in the next section.

Open the Simulink model slexCustomPythonModelPredictExample.slx.

open_system("slexCustomPythonModelPredictExample");

When you open the Simulink model, the software runs the code in the PreLoadFcn callback function before loading the Simulink model. The PreLoadFcn callback function of slexCustomPythonModelPredictExample includes code to check if your workspace contains the Xin variable for the trained model. If the workspace does not contain the variable, PreLoadFcn generates the sample observations and creates input signals for the Simulink model. To view the callback function, in the Setup section on the Modeling tab, click Model Settings and select Model Properties. Then, on the Callbacks tab, select the PreLoadFcn callback function in the Model callbacks pane.

Create Simulink Model

To create a new Simulink model, open the Blank Model template and add the Custom Python Model Predict block from the Statistics and Machine Learning Toolbox™ library.

Double-click the Custom Python Model Predict block to open the Block Parameters dialog box. Enter custom.py in the Path to Python file defining load_model() and predict() text box.

Specify the model coefficients to pass to the Python model by entering 1,2,-3 in the Arguments to load_model() text box.

On the Inputs tab, click New to add a second input port to the Custom Python Model Predict block.

On the Outputs tab, click New to add a second output port. Click OK.

Add two From Workspace blocks and connect them to the input ports of the Custom Python Model Predict block..

Double-click the first From Workspace block. In the Parameters section, under Data, enter Xin. Under Sample time (-1 for inherited) enter 1. Click OK.

Double-click the second From Workspace block. In the Parameters section, under Data, enter Yin. Under Sample time (-1 for inherited) enter 1. Click OK.

Add two Outport blocks and connect them to the output ports of the Custom Python Model Predict block.

Generate a data set in the MATLAB workspace that consists of 100 observations. Each observation consists of two predictors (X) and one response (y). To simulate noisy responses, generate them using the same linear regression coefficients as the custom Python model and add random Gaussian noise.

rng(0,"twister") % For reproducibility
n = 100;
X = rand(n,2);
beta = [1,2,-3];
y = randn(n,1) + beta(1)*ones(n,1) + beta(2)*X(:,1) + beta(3)*X(:,2);

Create an input signal for the Simulink model.

time = (0:n-1)';
Xin = [time,X];
Yin = [time,y];

Import the signal data from the workspace:

  • Open the Configuration Parameters dialog box. On the Modeling tab, click Model Settings.

  • On the left of the dialog box, click Solver. Under Simulation time, set Stop time to size(Yin,1)-1. Under Solver selection, set Type to Fixed-step, and set Solver to discrete (no continuous states). Click OK.

For more details, see Load Signal Data for Simulation (Simulink).

Save the model as slexCustomPythonModelPredictExample.slx in Simulink.

Simulate Simulink Model

Simulate the Simulink model to predict responses for the input observations.

simOut=sim("slexCustomPythonModelPredictExample");

When the Custom Python Model Predict block detects observations, it converts the predictor data to the Python or NumPy datatype specified in the Python datatype column on the Input tab of the Block Parameters dialog box. The block then passes the predictor data and noisy responses to Python, and the custom Python predict() function returns predicted responses and mean squared errors for the observations. You can use the Simulation Data Inspector (Simulink) to view the logged data of the Outport blocks.

Visualize Model Prediction Errors

Plot the mean squared error values.

mse = squeeze(simOut.yout.getElement(2).Values.data);
plot(mse,marker="+")
xlabel("Observation")
ylabel("MSE")

Figure contains an axes object. The axes object with xlabel Observation, ylabel MSE contains an object of type line.

The plot shows the mean squared difference between the input noisy response and the predicted model response for each observation.

See Also

|