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 process 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, ...
        SelfAssessedHealthStatus,Systolic,Weight,Smoker);

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

    patientTbl.SelfAssessedHealthStatus = categorical(patientTbl.SelfAssessedHealthStatus, ...
        ["Poor","Fair","Good","Excellent"],"Ordinal",true);

  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.

    classificationLearner(patientTbl,"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 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.

  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 to MATLAB Production Server

  1. Export the selected model for deployment to MATLAB Production Server. In the Export section of the Learn tab, click Export Model and select Export Model for Deployment to Production Server.

  2. In the Select Project File for Model Deployment dialog box, select a folder and name for your project file. If a folder already contains a project file, you cannot create a new project file in that folder or any of its subfolders. For this example, use the default project name ClassificationLearnerDeployedModel.prj. Click Save.

    Two new tabs appear in the MATLAB Editor window: predictFunction.m and DeployedClassificationModel.

  3. Click the DeployedClassificationModel tab. The Exported Functions section includes the files modelInformation.m and predictFunction.m. The section Files Required for Archive to Run includes the files TrainedClassificationModel.mat and processInputData.m.

  4. 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, ...
            ["Poor","Fair","Good","Excellent"],"Ordinal",true);
        processedData = T;
    end

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

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

  7. Save and 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. Click the DeployedClassificationModel tab in the Editor window and then click the Test Client button on the Deployment tab. A new tab named Test Client - DeployedClassificationModel appears in the Editor window.

  2. In the Server Actions section of the Test tab, 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.

  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, ...
        SelfAssessedHealthStatus,Systolic,Weight,Smoker);
    patientTbl.SelfAssessedHealthStatus = categorical(patientTbl.SelfAssessedHealthStatus, ...
        ["Poor","Fair","Good","Excellent"],"Ordinal",true);

  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 in the Command Window 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);
    

  6. Send the input data to MATLAB Production Server by entering the following commands in the Command Window. Use the server address displayed in the Test Client - DeployedClassificationModel tab.

    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 Test Client - DeployedClassificationModel tab, 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, click the Test Client - DeployedClassificationModel tab. Click Stop in the Server Actions section on the Test tab. In the Close section, click Close Test.

Package Code

  1. To use the MATLAB Production Server Archive Compiler to package your model and prediction function, click the DeployedClassificationModel tab in the Editor window.

  2. Click the Package button.

  3. After the build process is complete, click Open Output Folder in the Creating Production Server Archive dialog box. The build folder contains a readme.txt file with additional information about how to deploy the model.

See Also

Topics