Main Content

Generate MATLAB Code to Train Model with New Data

After you create classification models interactively in Classification Learner, you can generate MATLAB® code for your best model. You can then 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, 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 classifiers 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

  1. In Classification Learner, in 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 classifier training methods, and validation methods. Save the file.

  3. To retrain your classifier 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 classifier trained with the fishertable data set, enter:

    [trainedModel,validationAccuracy] = trainClassifier(fishertable)

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

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

    • Process the data into the right shape

    • Train a classifier and specify all the classifier options

    • Perform cross-validation

    • Compute validation accuracy

    • Compute validation predictions and scores

    Note

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