After you create classification models interactively in Classification Learner, you can export your best model to the workspace. You can then use the trained model to make predictions using new data.
The final model Classification Learner exports is always trained using the full data set. The validation scheme that you use only affects the way that the app computes validation metrics. You can use the validation metrics and various plots that visualize results to pick the best model for your classification problem.
Here are the steps for exporting a model to the MATLAB®workspace:
In Classification Learner, select the model you want to export in the History list.
On the Classification Learner tab, in the Export section, click one of the export options:
If you want to include the data used for training the model, then select Export Model.
You export the trained model to the workspace as a structure
containing a classification object, such as a ClassificationTree
,
ClassificationDiscriminant
, ClassificationSVM
,
ClassificationNaiveBayes
, ClassificationKNN
,
ClassificationEnsemble
, and so on.
If you do not want to include the training data, select
Export Compact Model. This option
exports the model with unnecessary data removed where possible.
For some classifiers this is a compact classification object
that does not include the training data (for example, CompactClassificationTree
). You can use a compact
classification object for making predictions of new data, but
you can use fewer other methods with it.
In the Export Model dialog box, edit the name for your exported variable
if you want, and then click OK. The default name for
your exported model, trainedModel
, increments every time
you export to avoid overwriting your classifiers (for example,
trainedModel1
).
The new variable (for example, trainedModel
) appears in
your workspace.
The app displays information about the exported model in the command window. Read the message to learn how to make predictions with new data.
After you export a model to the workspace from Classification Learner, or run the
code generated from the app, you get a trainedModel
structure
that you can use to make predictions using new data. The structure contains a
classification object and a function for prediction. The structure allows you to
make predictions for models that include principal component analysis (PCA).
To use the exported classifier to make predictions for new data,
T
, use the form:
yfit = C.predictFcn(T)
C
is the name of your variable (for example,
trainedModel
).Supply the data T
with the same format and data type as
the training data used in the app (table or matrix).
If you supply a table, ensure it contains the same predictor
names as your training data. The predictFcn
function ignores additional variables in tables. Variable
formats and types must match the original training data.
If you supply a matrix, it must contain the same predictor columns or rows as your training data, in the same order and format. Do not include a response variable, any variables that you did not import in the app, or other unused variables.
The output yfit
contains a class prediction for each
data point.
Examine the fields of the exported structure. For help making predictions, enter:
C.HowToPredict
You can also extract the classification object from the exported structure for
further analysis (for example, trainedModel.ClassificationSVM
,
trainedModel.ClassificationTree
, and so on, depending on your
model type). Be aware that if you used feature transformation such as PCA in the
app, you will need to take account of this transformation by using the information
in the PCA fields of the structure.
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
In Classification Learner, in the History list, select the model you want to generate code for.
On the Classification Learner 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.
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.
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
If you generate MATLAB code from a trained optimizable model, the generated code does not include the optimization process.
If you train an SVM model using Classification Learner, you can generate C code for prediction.
C code generation requires:
MATLAB Coder™ license
SVM model (binary or multiclass)
No categorical predictors or response in your data set
After you train an SVM model in Classification Learner, export the model to the workspace.
Find the name of the classification model object in the exported
structure. Examine the fields of the structure to find the model name, for
example, C.ClassificationSVM
, where C
is the name of your structure (for example,
trainedModel
).
Model name depends on what type of SVM you trained (binary or multiclass)
and whether you exported a compact model or not. Models can be
ClassificationSVM
,
CompactClassificationSVM
,
ClassificationECOC
, or
CompactClassificationECOC
.
Use the function saveLearnerForCoder
to prepare the
model for code generation:
saveLearnerForCoder(Mdl,filename)
. For
example:
saveLearnerForCoder(C.ClassificationSVM, 'mySVM')
Create a function that loads the saved model and makes predictions on new data. For example:
function label = classifyX (X) %#codegen %CLASSIFYX Classify using SVM Model % CLASSIFYX classifies the measurements in X % using the SVM model in the file mySVM.mat, and then % returns class labels in label. CompactMdl = loadLearnerForCoder('mySVM'); label = predict(CompactMdl,X); end
Generate a MEX function from your function. For example:
codegen classifyX.m -args {data}
%#codegen
compilation directive indicates that the
MATLAB code is intended for code generation. To ensure that the MEX
function can use the same input, specify the data in the workspace as
arguments to the function using the -args
option.
data
must be a matrix containing only the predictor
columns used to train the model.Use the MEX function to make predictions. For example:
labels = classifyX_mex(data);
If you used feature selection or PCA feature transformation in the app, then you
need additional steps. If you used manual feature selection, supply the same columns
in X
. X
is the input to your function.
If you used PCA in the app, use the information in the PCA fields of the exported
structure to take account of this transformation. It does not matter whether you
imported a table or a matrix into the app, as long as X
contains
the matrix columns in the same order. Before generating code, follow these steps:
Save the PCACenters and PCACoefficients fields of the trained
classifier structure, C
, to file using the following
command:
save('pcaInfo.mat', '-struct', 'C', 'PCACenters', 'PCACoefficients');
In your function file, include additional lines to perform the PCA transformation. Create a function that loads the saved model, performs PCA, and makes predictions on new data. For example:
function label = classifyX (X) %#codegen %CLASSIFYX Classify using SVM Model % CLASSIFYX classifies the measurements in X % using the SVM model in the file mySVM.mat, and then % returns class labels in label. % If you used manual feature selection in the app, ensure that X contains only the columns you included in the model. CompactMdl = loadLearnerForCoder('mySVM'); pcaInfo = load('pcaInfo.mat', 'PCACenters', 'PCACoefficients'); % performs pca transformation pcaTransformedX = bsxfun(@minus, X, pcaInfo.PCACenters) * pcaInfo.PCACoefficients; [label, scores] = predict(CompactMdl, pcaTransformedX); end
For more information on C code generation workflow and limitations, see Code Generation. For examples, see
saveLearnerForCoder
and loadLearnerForCoder
.
After you export a model to the workspace from Classification Learner, you can deploy it using MATLAB Compiler™.
Suppose you export the trained model to MATLAB Workspace based on the instructions in Export Model to Workspace, with the name
trainedModel
. To deploy predictions, follow these steps.
Save the trainedModel
structure in a .mat
file.
save mymodel trainedModel
Write the code to be compiled. This code must load the trained model and use it to make a prediction. It must also have a pragma, so the compiler recognizes that Statistics and Machine Learning Toolbox™ code is needed in the compiled application. This pragma could be any function in the toolbox.
function ypred = mypredict(tbl) %#function fitctree load('mymodel.mat'); load('fishertable.mat') ypred = trainedModel.predictFcn(fishertable) end
Compile as a standalone application.
mcc -m mypredict.m
ClassificationBaggedEnsemble
| ClassificationDiscriminant
| ClassificationECOC
| ClassificationEnsemble
| ClassificationKNN
| ClassificationNaiveBayes
| ClassificationSVM
| ClassificationTree
| CompactClassificationDiscriminant
| CompactClassificationECOC
| CompactClassificationEnsemble
| CompactClassificationNaiveBayes
| CompactClassificationSVM
| CompactClassificationTree
| GeneralizedLinearModel