Main Content

Predict Responses Using TensorFlow Model Predict Block

This example shows how to use the TensorFlow Model Predict block for prediction in Simulink®. The block accepts observations (predictor data), and returns the predicted responses using a trained machine learning model that is executed in Python®. 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. Your MATLAB Python environment must have the tensorflow module installed.

The TensorFlow Model Predict block requires a pretrained TensorFlow™ model that you saved in SavedModel format or as a Keras HDF5 file in Python. This example provides the saved model tfmodel.zip, which is a neural network binary classification model trained on half of the ionosphere radar signal data set from the UCI Machine Learning Repository [1]. The example also provides the Python files tfScaler.pkl, tfmodel.py, and tfpreprocessor.py. All of the supporting Python files were saved using tensorflow version 2.14.0.

Open Provided Simulink Model

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

Open the Simulink model slexTensorFlowPredictExample.slx.

open_system("slexTensorFlowPredictExample");

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 slexTensorFlowPredictExample includes code to check if your workspace contains the modelInput variable for the trained model. If the workspace does not contain the variable, PreLoadFcn loads the sample data and creates an input signal 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 TensorFlow Model Predict block from the Statistics and Machine Learning Toolbox™ library.

Add an Inport block and an Outport block, and connect them to the TensorFlow Model Predict block.

Double-click the TensorFlow Model Predict block to open the Block Parameters dialog box. Enter tfmodel in the Path to model (SavedModel folder or Keras HDF5 file) text box.

tfblockexample.png

On the Pre/Post-processing tab, enter tfpreprocessor.py in the Path to Python file defining preprocess() text box. Click OK.

The TensorFlow Model Predict block expects observations containing 34 predictor values, because the Python model was trained using a data set with 34 predictor variables. Double-click the Inport block, and set Port dimensions to 34 on the Signal Attributes tab.

To specify that the output signals have the same length as the input signal, set Sample Time to 1 on the Execution tab.

Clear the Interpolate data check box and click OK.

Load the ionosphere data set. This data set has 34 predictors (X) and 351 binary responses (Y) for radar returns, either bad ("b") or good ("g").

load ionosphere

Create an appropriate structure array for the input data. For more information, see Control How Models Load Input Data (Simulink).

modelInput.time = (1:size(X,1))' - 1;
modelInput.signals.values = X;
modelInput.signals.dimensions = size(X,2);

Import the signal data from the workspace:

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

  • On the left of the dialog box, click Data Import/Export. Then select the Input check box and enter modelInput in the adjacent text box.

  • On the left, click Solver. Under Simulation time, set Stop time to size(X,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 slexTensorFlowPredictExample.slx in Simulink.

Simulate Simulink Model

Unzip the tfmodel.zip file containing the Python TensorFlow model.

if ~exist("tfmodel","file")
    unzip("tfmodel.zip")
end

Simulate the Simulink model to predict responses for the input observations. You may receive a warning message if your Python installation uses a tensorflow version prior to 2.14.0.

simOut=sim("slexTensorFlowPredictExample");
WARNING:tensorflow:From C:\Users\eanderse\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\losses.py:2976: The name tf.losses.sparse_softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.sparse_softmax_cross_entropy instead.

WARNING:tensorflow:From C:\Users\eanderse\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\saving\legacy\saved_model\load.py:107: The name tf.gfile.Exists is deprecated. Please use tf.io.gfile.exists instead.

WARNING:tensorflow:From C:\Users\eanderse\AppData\Local\Programs\Python\Python311\Lib\site-packages\keras\src\utils\tf_utils.py:585: The name tf.executing_eagerly_outside_functions is deprecated. Please use tf.compat.v1.executing_eagerly_outside_functions instead.

C:\Users\eanderse\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\base.py:376: InconsistentVersionWarning: Trying to unpickle estimator StandardScaler from version 1.3.2 when using version 1.4.2. This might lead to breaking code or invalid results. Use at your own risk. For more info please refer to:
https://scikit-learn.org/stable/model_persistence.html#security-maintainability-limitations
  warnings.warn(
WARNING:tensorflow:From C:\Users\eanderse\AppData\Local\Programs\Python\Python311\Lib\site-packages\tensorflow\python\util\decorator_utils.py:153: GraphKeys.VARIABLES (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.GraphKeys.GLOBAL_VARIABLES` instead.

When the Inport block detects input data, it places the data in the TensorFlow Model Predict block. The TensorFlow Model Predict block converts the input 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 passes the data to Python, where the software preprocesses the data using the function defined in preprocessor.py and then sends the data to the Python model. The Python model returns the predicted response for the observation. You can use the Simulation Data Inspector (Simulink) to view the logged data of the Outport block.

Visualize Model Predictions

Plot the predicted response for each observation.

Resp = round(squeeze(simOut.yout.getElement(1).Values.Data));
plot(Resp,LineStyle="none",Marker="*")
xlabel("Observation")
ylabel("Predicted Response")

Figure contains an axes object. The axes object with xlabel Observation, ylabel Predicted Response contains a line object which displays its values using only markers.

The bad ("b") and good ("g") predicted response values are indicated as 0 and 1, respectively.

References

[1] Lichman, M. UCI Machine Learning Repository, Irvine, CA: University of California, School of Information and Computer Science, 2013. https://archive.ics.uci.edu.

See Also

| | |

Related Topics