Main Content

Deploy Model Trained in Regression Learner to MATLAB Production Server

This example shows how to train a model in Regression 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, simulate 100 observations from a regression model with four predictor variables. Create a random matrix X, whose rows correspond to observations and whose columns correspond to predictor variables. Add missing values to the matrix by randomly setting approximately 2% of the values in each column as NaNs. Create a response variable y from the variables in X.

    rng("default")
    numRows = 100;
    numCols = 4;
    X = rand(numRows,numCols);
    
    randIdx = randi(numRows*numCols,floor(0.02*numRows)*numCols,1);
    X(randIdx) = NaN;
    
    y = 10*X(:,1) + 5*X(:,2) + 3*X(:,3) + 7*X(:,4) + 0.1*randn(numRows,1);

  2. From the Command Window, open the Regression Learner app. Populate the New Session from Arguments dialog box with the predictor matrix X and the response variable y.

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

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

  4. 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 response plot for the linear regression model (model 2.1). Blue points are true values, and yellow points are predicted values. The Models pane on the left shows the validation RMSE (root mean squared error) for each model.

  5. Sort the models based on the validation RMSE. In the Models pane, open the Sort by list and select RMSE (Validation). The app outlines the metric for the model (or models) with the lowest validation RMSE.

  6. Select the model in the Models pane with the lowest validation RMSE.

Export Model for Deployment

  1. Export the selected model for deployment to MATLAB Production Server. On the Learn tab, click Export, 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 RegressionLearnerDeployedModel.prj. Click Save.

    The software opens the Production Server Compiler app and the autogenerated predictFunction.m file.

  3. 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 TrainedRegressionModel.mat. For an example where you must update the code in some of these files to include preprocessing steps, see Deploy Model Trained in Classification Learner to MATLAB Production Server. For this example, inspect the predictFunction.m code and close the file.

(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/DeployedRegressionModel.

  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 predictor data that has the same format as the training data used in Regression Learner.

    rng("default")
    numRows = 100;
    numCols = 4;
    X = rand(numRows,numCols);
    
    randIdx = randi(numRows*numCols,floor(0.02*numRows)*numCols,1);
    X(randIdx) = NaN;

  5. Send the data to MATLAB Production Server. Use the server address displayed in the Production Server Compiler app.

    Because X is a numeric matrix, the argument does not require further processing before being sent to MATLAB Production Server. You must convert categorical variables and tables to cell arrays and structures, respectively, before sending them to MATLAB Production Server. For an example, see Deploy Model Trained in Classification Learner to MATLAB Production Server.

    jsonData = mps.json.encoderequest({X},"Nargout",1, ...
        "OutputFormat","large");
    URL = "http://localhost:9910/DeployedRegressionModel/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.

  6. In the Command Window of the new MATLAB instance, extract the predicted responses from the response variable. Convert the predicted responses to a numeric vector, and check that the values are correct.

    cellResults = response.lhs.mwdata;
    numericResults = arrayfun(@str2double,string(cellResults));
    Note that the data type of response.lhs.mwdata changes depending on the presence of NaN values. For example, response.lhs.mwdata is a numeric vector when the predicted responses do not include NaN values.

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