Deploy Model Trained in Classification Learner to MATLAB Production Server
This example shows how to train a model in Classification Learner and export it for deployment to MATLAB® Production Server™. This workflow requires MATLAB Compiler SDK™.
Choose Trained Model to Deploy
In the Command Window, load the
patients
data set, and create a table from a subset of the variables in the data set. Each row inpatientTbl
corresponds to a patient, and each column corresponds to a diagnostic variable.load patients patientTbl = table(Age,Diastolic,Gender,Height, ... SelfAssessedHealthStatus,Systolic,Weight,Smoker);
Convert the
SelfAssessedHealthStatus
variable to an ordinal categorical predictor.patientTbl.SelfAssessedHealthStatus = categorical(patientTbl.SelfAssessedHealthStatus, ... ["Poor","Fair","Good","Excellent"],"Ordinal",true);
From the Command Window, open the Classification Learner app. Populate the New Session from Arguments dialog box with the predictor data in
patientTbl
and the response variableSmoker
.The default validation option is 5-fold cross-validation, to protect against overfitting. For this example, do not change the default validation setting.classificationLearner(patientTbl,"Smoker")
To accept the selections in the New Session from Arguments dialog box and continue, click Start Session.
Train all preset models. On the Learn tab, in the Models section, click the arrow to open the gallery. In the Get Started group, click All. In the Train section, click Train All and select Train All. The app trains all preset models, along with the default fine tree model, and displays the models in the Models pane.
Note
If you have Parallel Computing Toolbox™, then the Use Parallel button is selected by default. After you click Train All and select Train All or Train Selected, the app opens a parallel pool of workers. During this time, you cannot interact with the software. After the pool opens, you can continue to interact with the app while models train in parallel.
If you do not have Parallel Computing Toolbox, then the Use Background Training check box in the Train All menu is selected by default. After you select an option to train models, the app opens a background pool. After the pool opens, you can continue to interact with the app while models train in the background.
The app displays a confusion matrix for the second fine tree model (model 2.1). Blue values indicate correct classifications, and red values indicate incorrect classifications. The Models pane on the left shows the validation accuracy for each model.
Sort the models based on the validation accuracy. In the Models pane, open the Sort by list and select
Accuracy (Validation)
. The app outlines the metric for the model (or models) with the highest validation accuracy.Select the model in the Models pane with the highest validation accuracy.
Export Model for Deployment
Export the selected model for deployment to MATLAB Production Server. On the Learn tab, in the Export section, click Export Model and select Export Model for Deployment.
In the Select Project File for Model Deployment dialog box, select a location and name for your project file. For this example, use the default project name
ClassificationLearnerDeployedModel.prj
. Click Save.The software opens the Production Server Compiler app and the autogenerated
predictFunction.m
file.In the Compiler tab of the Production Server Compiler app, the Exported Functions section includes the files
modelInformation.m
andpredictFunction.m
. The section Additional files required for your archive to run includes the filesprocessInputData.m
andTrainedClassificationModel.mat
.Update the code in the files
processInputData.m
andpredictFunction.m
to include preprocessing steps performed before you imported data in Classification Learner. Open theprocessInputData.m
file from theClassificationLearnerDeployedModel_resources
folder, and change the code to include the conversion of theSelfAssessedHealthStatus
variable to an ordinal categorical predictor.function processedData = processInputData(T) T.SelfAssessedHealthStatus = categorical(T.SelfAssessedHealthStatus, ... ["Poor","Fair","Good","Excellent"],"Ordinal",true); processedData = T; end
In the
predictFunction.m
file, uncomment the following lines of code so that thepredictFunction
function calls theprocessInputData
function.processedData = processInputData(T); T = processedData;
Edit the
predictFunction.m
code so that the function returns two outputs,labels
andscores
, instead of the single outputresult
. Update the function signature in the first line of code.Then, update thefunction [labels,scores] = predictFunction(varargin)
result = model.predictFcn(T);
line of code to include the two output arguments.[labels,scores] = model.predictFcn(T);
Also update the commented-out description of the
predictFunction
function to include descriptions of the new output arguments.labels
contains the predicted labels returned by the trained model, andscores
contains the predicted scores returned by the trained model.Close the files
predictFunction.m
andprocessInputData.m
.
(Optional) Simulate Model Deployment
Before packaging your code for deployment to MATLAB Production Server, you can simulate the model deployment using a MATLAB client. Completing this process requires opening another instance of MATLAB. For an example that shows how to use a sample Java® client for sending data to a MATLAB function deployed on the server, see Evaluate Deployed Machine Learning Models Using Java Client (MATLAB Production Server).
In the Production Server Compiler app, click the Test Client button in the Test section on the Compiler tab.
On the Test tab, in the Server Actions section, click the Start button. Note the address listed in the Server Address pane, which in this example is
http://localhost:9910/DeployedClassificationModel
.Open a new instance of MATLAB.
In the new MATLAB instance, the Production Server Compiler app automatically opens. Close this instance of the app.
In the Command Window of the new MATLAB instance, load the predictor and response data. Ensure that the data has the same format as the training data used in Classification Learner.
load patients patientTbl = table(Age,Diastolic,Gender,Height, ... SelfAssessedHealthStatus,Systolic,Weight,Smoker); patientTbl.SelfAssessedHealthStatus = categorical(patientTbl.SelfAssessedHealthStatus, ... ["Poor","Fair","Good","Excellent"],"Ordinal",true);
Prepare the data to send it to MATLAB Production Server.
You must convert categorical variables and tables to cell arrays and structures, respectively, before sending them to MATLAB Production Server. Because
SelfAssessedHealthStatus
is a categorical variable andpatientTbl
is a table, process the input data further before sending it.inputTbl = patientTbl; columnNames = patientTbl.Properties.VariableNames; for i=1:length(columnNames) if iscategorical(patientTbl.(columnNames{i})) inputTbl.(columnNames{i}) = cellstr(patientTbl.(columnNames{i})); end end inputData = table2struct(inputTbl);
Send the input data to MATLAB Production Server. Use the server address displayed in the Production Server Compiler app.
jsonData = mps.json.encoderequest({inputData},"Nargout",2); URL = "http://localhost:9910/DeployedClassificationModel/predictFunction"; options = weboptions("MediaType","application/json","Timeout",30); response = webwrite(URL,jsonData,options);
In the original MATLAB instance, in the opened Production Server Compiler app, the MATLAB Execution Requests pane under the Test tab shows a successful request between the server and the MATLAB client.
In the Command Window of the new MATLAB instance, extract the predicted labels and scores from the
response
variable. Check that the predicted values are correct.labels = response.lhs{1}; scores = response.lhs{2};
In the original MATLAB instance, in the Production Server Compiler app, click Stop in the Server Actions section on the Test tab. In the Close section, click Close Test.
Package Code
Use the Production Server Compiler app to package your model and prediction function. On the Compiler tab, in the Package section, click the Package button.
In the Package dialog box, verify that the option Open output folder when process completes is selected.
After the deployment process finishes, examine the generated output.
for_redistribution
— Folder containing theDeployedClassificationModel.ctf
filefor_testing
— Folder containing the raw generated files required to create the installerPackagingLog.html
— Log file generated by MATLAB Compiler SDK
Related Topics
- Visualize and Assess Classifier Performance in Classification Learner
- Export Classification Model to Predict New Data
- Create Deployable Archive for MATLAB Production Server (MATLAB Production Server)
- Evaluate Deployed Machine Learning Models Using Java Client (MATLAB Production Server)
- Execute Deployed MATLAB Functions (MATLAB Production Server)