Main Content

Generate MATLAB Code to Train Model with New Data

After you create regression models interactively in the Regression Learner app, you can generate MATLAB® code for your best model. Then you can use the code to train the model with new data.

Generate MATLAB code to:

  • Train on huge data sets. Explore models in the app trained on a subset of your data, and then generate code to train a selected model on a larger data set.

  • Create scripts for training models without needing to learn syntax of the different functions.

  • Examine the code to learn how to train models programmatically.

  • Modify the code for further analysis, for example to set options that you cannot change in the app.

  • Repeat your analysis on different data and automate training.

To generate code and use it to train a model with new data:

  1. In the app, from the Models pane, select the model you want to generate code for.

  2. On the Learn tab, in the Export section, click Generate Function.

    The app generates code from your session and displays the file in the MATLAB Editor. The file includes the predictors and response, the model training methods, and the validation methods. Save the file.

  3. To retrain your model, call the function from the command line with your original data or new data as the input argument or arguments. New data must have the same shape as the original data.

    Copy the first line of the generated code, excluding the word function, and edit the trainingData input argument to reflect the variable name of your training data or new data. Similarly, edit the responseData input argument (if applicable).

    For example, to retrain a regression model trained with the cartable data set, enter:

    [trainedModel,validationRMSE] = trainRegressionModel(cartable)

    The generated code returns a trainedModel structure that contains the same fields as the structure you create when you export a model from Regression Learner to the workspace.

If you want to automate training the same model with new data, or learn how to programmatically train models, examine the generated code. The code shows you how to:

  • Process the data into the right shape.

  • Train a model and specify all the model options.

  • Perform cross-validation.

  • Compute statistics.

  • Compute validation predictions.

Note

If you generate MATLAB code from a trained optimizable model, the generated code does not include the optimization process.

See Also

Topics