Main Content

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

  1. 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 in patientTbl corresponds to a patient, and each column corresponds to a diagnostic variable.

    load patients
    patientTbl = table(Age,Diastolic,Gender,Height, ...

  2. Convert the SelfAssessedHealthStatus variable to an ordinal categorical predictor.

    patientTbl.SelfAssessedHealthStatus = categorical(patientTbl.SelfAssessedHealthStatus, ...

  3. 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 variable Smoker.

    The default validation option is 5-fold cross-validation, to protect against overfitting. For this example, do not change the default validation setting.

  4. To accept the selections in the New Session from Arguments dialog box and continue, click Start Session.

  5. Train all preset models. On the Classification Learner tab, in the Model Type section, click the arrow to open the gallery. In the Get Started group, click All. In the Training section, click Train. The app trains all preset models and displays the models in the Models pane.


    If you have Parallel Computing Toolbox™, you can train all the models (All) simultaneously by selecting the Use Parallel button in the Training section before clicking Train. After you click Train, the Opening Parallel Pool dialog box opens and remains open while the app opens a parallel pool of workers. During this time, you cannot interact with the software. After the pool opens, the app trains all the models simultaneously.

    The app displays a confusion matrix for the first model. Blue values indicate correct classifications, and red values indicate incorrect classifications. The Models pane on the left shows the validation accuracy for each model.

  6. 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.

  7. Select the model in the Models pane with the highest validation accuracy.

Export Model for Deployment

  1. Export the selected model for deployment to MATLAB Production Server. On the Classification Learner tab, in the Export section, click Export Model and select Export Model for Deployment.

  2. 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 and predictFunction.m. The section Additional files required for your archive to run includes the files processInputData.m and TrainedClassificationModel.mat.

  3. Update the code in the files processInputData.m and predictFunction.m to include preprocessing steps performed before you imported data in Classification Learner. Open the processInputData.m file from the ClassificationLearnerDeployedModel_resources folder, and change the code to include the conversion of the SelfAssessedHealthStatus variable to an ordinal categorical predictor.

    function processedData = processInputData(T)
        T.SelfAssessedHealthStatus = categorical(T.SelfAssessedHealthStatus, ...
        processedData = T;

  4. In the predictFunction.m file, uncomment the following lines of code so that the predictFunction function calls the processInputData function.

    processedData = processInputData(T);
    T = processedData;

  5. Edit the predictFunction.m code so that the function returns two outputs, labels and scores, instead of the single output result. Update the function signature in the first line of code.

    function [labels,scores] = predictFunction(varargin)
    Then, update the 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, and scores contains the predicted scores returned by the trained model.

  6. Close the files predictFunction.m and processInputData.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).

  1. In the Production Server Compiler app, click the Test Client button in the Test section on the Compiler tab.

  2. 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.

  3. Open a new instance of MATLAB.

    In the new MATLAB instance, the Production Server Compiler app automatically opens. Close this instance of the app.

  4. 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, ...
    patientTbl.SelfAssessedHealthStatus = categorical(patientTbl.SelfAssessedHealthStatus, ...

  5. 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 and patientTbl 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}));
    inputData = table2struct(inputTbl);

  6. 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.

  7. 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};

  8. 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

  1. 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.

  2. 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 the DeployedClassificationModel.ctf file

    • for_testing — Folder containing the raw generated files required to create the installer

    • PackagingLog.html — Log file generated by MATLAB Compiler SDK

Related Topics