predict - Predict responses of linear regression model - MATLAB (original) (raw)

Predict responses of linear regression model

Syntax

Description

[ypred](#bszh804-1%5Fsep%5Fshared-ypred) = predict([mdl](#bszh804-1%5Fsep%5Fshared-mdl),[Xnew](#bszh804-1%5Fsep%5Fshared-Xnew)) returns the predicted response values of the linear regression modelmdl to the points in Xnew.

example

[[ypred](#bszh804-1%5Fsep%5Fshared-ypred),[yci](#bszh804-1%5Fsep%5Fshared-yci)] = predict([mdl](#bszh804-1%5Fsep%5Fshared-mdl),[Xnew](#bszh804-1%5Fsep%5Fshared-Xnew)) also returns confidence intervals for the responses atXnew.

[[ypred](#bszh804-1%5Fsep%5Fshared-ypred),[yci](#bszh804-1%5Fsep%5Fshared-yci)] = predict([mdl](#bszh804-1%5Fsep%5Fshared-mdl),[Xnew](#bszh804-1%5Fsep%5Fshared-Xnew),[Name,Value](#namevaluepairarguments)) specifies additional options using one or more name-value arguments. For example, you can specify the confidence level of the confidence interval and the prediction type.

example

Examples

collapse all

Create a quadratic model of car mileage as a function of weight from the carsmall data set.

load carsmall X = Weight; y = MPG; mdl = fitlm(X,y,'quadratic');

Create predicted responses to the data.

Plot the original responses and the predicted responses to see how they differ.

plot(X,y,'o',X,ypred,'x') legend('Data','Predictions')

Figure contains an axes object. The axes object contains 2 objects of type line. One or more of the lines displays its values using only markers These objects represent Data, Predictions.

Fit a linear regression model, and then save the model by using saveLearnerForCoder. Define an entry-point function that loads the model by using loadLearnerForCoder and calls the predict function of the fitted model. Then use codegen (MATLAB Coder) to generate C/C++ code. Note that generating C/C++ code requires MATLAB® Coder™.

This example briefly explains the code generation workflow for the prediction of linear regression models at the command line. For more details, see Code Generation for Prediction of Machine Learning Model at Command Line. You can also generate code using the MATLAB Coder app. For details, see Code Generation for Prediction of Machine Learning Model Using MATLAB Coder App.

Train Model

Load the carsmall data set, and then fit the quadratic regression model.

load carsmall X = Weight; y = MPG; mdl = fitlm(X,y,'quadratic');

Save Model

Save the fitted quadratic model to the file QLMMdl.mat by using saveLearnerForCoder.

saveLearnerForCoder(mdl,'QLMMdl');

Define Entry-Point Function

Define an entry-point function named mypredictQLM that does the following:

function [yhat,ci] = mypredictQLM(x,varargin) %#codegen %MYPREDICTQLM Predict response using linear model % MYPREDICTQLM predicts responses for the n observations in the n-by-1 % vector x using the linear model stored in the MAT-file QLMMdl.mat, and % then returns the predictions in the n-by-1 vector yhat. MYPREDICTQLM % also returns confidence interval bounds for the predictions in the % n-by-2 vector ci. CompactMdl = loadLearnerForCoder('QLMMdl'); [yhat,ci] = predict(CompactMdl,x,varargin{:}); end

Add the %#codegen compiler directive (or pragma) to the entry-point function after the function signature to indicate that you intend to generate code for the MATLAB algorithm. Adding this directive instructs the MATLAB Code Analyzer to help you diagnose and fix violations that would result in errors during code generation.

Note: If you click the button located in the upper-right section of this example and open the example in MATLAB®, then MATLAB opens the example folder. This folder includes the entry-point function file.

Generate Code

Generate code for the entry-point function using codegen (MATLAB Coder). Because C and C++ are statically typed languages, you must determine the properties of all variables in the entry-point function at compile time. To specify the data type and exact input array size, pass a MATLAB® expression that represents the set of values with a certain data type and array size. Use coder.Constant (MATLAB Coder) for the names of name-value pair arguments.

If the number of observations is unknown at compile time, you can also specify the input as variable-size by using coder.typeof (MATLAB Coder). For details, see Specify Variable-Size Arguments for Code Generation and Specify Types of Entry-Point Function Inputs (MATLAB Coder).

codegen mypredictQLM -args {X,coder.Constant('Alpha'),0.1,coder.Constant('Simultaneous'),true}

Code generation successful.

codegen generates the MEX function mypredictQLM_mex with a platform-dependent extension.

Verify Generated Code

Compare predictions and confidence intervals using predict and mypredictQLM_mex. Specify name-value pair arguments in the same order as in the -args argument in the call to codegen.

Xnew = sort(X); [yhat1,ci1] = predict(mdl,Xnew,'Alpha',0.1,'Simultaneous',true); [yhat2,ci2] = mypredictQLM_mex(Xnew,'Alpha',0.1,'Simultaneous',true);

The returned values from mypredictQLM_mex might include round-off differences compared to the values from predict. In this case, compare the values allowing a small tolerance.

find(abs(yhat1-yhat2) > 1e-6)

ans =

0×1 empty double column vector

find(abs(ci1-ci2) > 1e-6)

ans =

0×1 empty double column vector

The comparison confirms that the returned values are equal within the tolerance 1e–6.

Plot the returned values for comparison.

h1 = plot(X,y,'k.'); hold on h2 = plot(Xnew,yhat1,'ro',Xnew,yhat2,'gx'); h3 = plot(Xnew,ci1,'r-','LineWidth',4); h4 = plot(Xnew,ci2,'g--','LineWidth',2); legend([h1; h2; h3(1); h4(1)], ... {'Data','predict estimates','MEX estimates','predict CIs','MEX CIs'}); xlabel('Weight'); ylabel('MPG');

Figure contains an axes object. The axes object with xlabel Weight, ylabel MPG contains 7 objects of type line. One or more of the lines displays its values using only markers These objects represent Data, predict estimates, MEX estimates, predict CIs, MEX CIs.

Input Arguments

collapse all

Data Types: single | double | table

Name-Value Arguments

collapse all

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Example: [ypred,yci] = predict(Mdl,Xnew,'Alpha',0.01,'Simultaneous',true) returns the confidence interval yci with a 99% confidence level, computed simultaneously for all predictor values.

Data Types: single | double

Data Types: string | char

Output Arguments

collapse all

Predicted response values evaluated at Xnew, returned as a numeric vector.

Confidence intervals for the responses, returned as a two-column matrix in which each row provides one interval. The meaning of the confidence interval depends on the settings of the name-value arguments Alpha,Prediction, and Simultaneous.

Alternative Functionality

Extended Capabilities

expand all

Usage notes and limitations:

For more information, see Introduction to Code Generation.

Version History

Introduced in R2012a