Accelerating the pace of engineering and science

# NonLinearModel class

Nonlinear regression model class

## Description

An object comprising training data, model description, diagnostic information, and fitted coefficients for a nonlinear regression. Predict model responses with the predict or feval methods.

## Construction

nlm = fitnlm(tbl,modelfun,beta0) or nlm = fitnlm(X,y,modelfun,beta0) create a nonlinear model of a table or dataset array tbl, or of the responses y to a data matrix X. For details, see fitnlm.

expand all

### tbl — Input datatable | dataset array

Input data, specified as a table or dataset array. When modelspec is a formula, it specifies the variables to be used as the predictors and response. Otherwise, if you do not specify the predictor and response variables, the last variable is the response variable and the others are the predictor variables by default.

Predictor variables can be numeric, or any grouping variable type, such as logical or categorical (see Grouping Variables). The response must be numeric or logical.

To set a different column as the response variable, use the ResponseVar name-value pair argument. To use a subset of the columns as predictors, use the PredictorVars name-value pair argument.

Data Types: single | double | logical

### X — Predictor variablesmatrix

Predictor variables, specified as an n-by-p matrix, where n is the number of observations and p is the number of predictor variables. Each column of X represents one variable, and each row represents one observation.

By default, there is a constant term in the model, unless you explicitly remove it, so do not include a column of 1s in X.

Data Types: single | double | logical

### y — Response variablevector

Response variable, specified as an n-by-1 vector, where n is the number of observations. Each entry in y is the response for the corresponding row of X.

Data Types: single | double

### modelfun — Functional form of the modelfunction handle | string of the form 'y ~ f(b1,b2,...,bj,x1,x2,...,xk)'

Functional form of the model, specified as either of the following.

• Function handle @modelfun or @(b,x)modelfun, where

• b is a coefficient vector with the same number of elements as beta0.

• x is a matrix with the same number of columns as X or the number of predictor variable columns of tbl.

modelfun(b,x) returns a column vector that contains the same number of rows as x. Each row of the vector is the result of evaluating modelfun on the corresponding row of x. In other words, modelfun is a vectorized function, one that operates on all data rows and returns all evaluations in one function call. modelfun should return real numbers to obtain meaningful coefficients.

• String of the form 'y ~ f(b1,b2,...,bj,x1,x2,...,xk)', where f represents a scalar function of the scalar coefficient variables b1,...,bj and the scalar data variables x1,...,xk.

### beta0 — Coefficientsnumeric vector

Coefficients for the nonlinear model, specified as a numeric vector. NonLinearModel starts its search for optimal coefficients from beta0.

Data Types: single | double

## Properties

CoefficientCovariance

Covariance matrix of coefficient estimates.

CoefficientNames

Cell array of strings containing a label for each coefficient.

Coefficients

Coefficient values stored as a table. Coefficients has one row for each coefficient and these columns:

• Estimate — Estimated coefficient value

• SE — Standard error of the estimate

• tStatt statistic for a test that the coefficient is zero

• pValuep-value for the t statistic

To obtain any of these columns as a vector, index into the property using dot notation. For example, in mdl the estimated coefficient vector is

`beta = mdl.Coefficients.Estimate`

Use coefTest to perform other tests on the coefficients.

Diagnostics

Table with diagnostics helpful in finding outliers and influential observations. The table contains the following fields.

FieldMeaningUtility
LeverageDiagonal elements of HatMatrixLeverage indicates to what extent the predicted value for an observation is determined by the observed value for that observation. A value close to 1 indicates that the prediction is largely determined by that observation, with little contribution from the other observations. A value close to 0 indicates the fit is largely determined by the other observations. For a model with P coefficients and N observations, the average value of Leverage is P/N. An observation with Leverage larger than 2*P/N can be regarded as having high leverage.
CooksDistanceCook's measure of scaled change in fitted valuesCooksDistance is a measure of scaled change in fitted values. An observation with CooksDistance larger than three times the mean Cook's distance can be an outlier.
HatMatrixProjection matrix to compute fitted from observed responsesHatMatrix is an N-by-N matrix such that Fitted = HatMatrix*Y, where Y is the response vector and Fitted is the vector of fitted response values.

DFE

Degrees of freedom for error (residuals), equal to the number of observations minus the number of estimated coefficients.

Fitted

Vector of predicted values based on the training data. fitnlm attempts to make Fitted as close as possible to the response data.

Formula

Object that represents the mathematical form of the model.

Iterative

Structure with information about the fitting process. Fields:

• InitialCoefs — Initial coefficient values (the beta0 vector)

• IterOpts — Options included in the Options name-value pair argument for fitnlm.

LogLikelihood

Log likelihood of the model distribution at the response values, with mean fitted from the model, and other parameters estimated as part of the model fit.

ModelCriterion

AIC and other information criteria for comparing models. A structure with fields:

• AIC — Akaike information criterion

• AICc — Akaike information criterion corrected for sample size

• BIC — Bayesian information criterion

• CAIC — Consistent Akaike information criterion

To obtain any of these values as a scalar, index into the property using dot notation. For example, in a model mdl, the AIC value aic is:

`aic = mdl.ModelCriterion.AIC`

MSE

Mean squared error, a scalar that is an estimate of the variance of the error term in the model.

NumCoefficients

Number of coefficients in the fitted model, a scalar. NumCoefficients is the same as NumEstimatedCoefficients for NonLinearModel objects. NumEstimatedCoefficients is equal to the degrees of freedom for regression.

NumEstimatedCoefficients

Number of estimated coefficients in the fitted model, a scalar. NumEstimatedCoefficients is the same as NumCoefficients for NonLinearModel objects. NumEstimatedCoefficients is equal to the degrees of freedom for regression.

NumPredictors

Number of variables fitnlm used as predictors for fitting.

NumVariables

Number of variables in the data. NumVariables is the number of variables in the original table or dataset, or the total number of columns in the predictor matrix and response vector when the fit is based on those arrays. It includes variables, if any, that are not used as predictors or as the response.

ObservationInfo

Table with the same number of rows as the input data (tbl or X).

FieldDescription
WeightsObservation weights. Default is all 1.
ExcludedLogical value, 1 indicates an observation that you excluded from the fit with the Exclude name-value pair.
MissingLogical value, 1 indicates a missing value in the input. Missing values are not used in the fit.
SubsetLogical value, 1 indicates the observation is not excluded or missing, so is used in the fit.

ObservationNames

Cell array of strings containing the names of the observations used in the fit.

• If the fit is based on a table or dataset containing observation names, ObservationNames uses those names.

• Otherwise, ObservationNames is an empty cell array

PredictorNames

Cell array of strings, the names of the predictors used in fitting the model.

Residuals

Table of residuals, with one row for each observation and these variables.

FieldDescription
RawObserved minus fitted values.
PearsonRaw residuals divided by RMSE.
StandardizedRaw residuals divided by their estimated standard deviation.
StudentizedResidual divided by an independent estimate of the residual standard deviation. The residual for observation i is divided by an estimate of the error standard deviation based on all observations except for observation i.

To obtain any of these columns as a vector, index into the property using dot notation. For example, in a model mdl, the ordinary raw residual vector r is:

`r = mdl.Residuals.Raw`

Rows not used in the fit because of missing values (in ObservationInfo.Missing) contain NaN values.

Rows not used in the fit because of excluded values (in ObservationInfo.Excluded) contain NaN values, with the following exceptions:

• raw contains the difference between the observed and predicted values.

• standardized is the residual, standardized in the usual way.

• studentized matches the standardized values because this residual is not used in the estimate of the residual standard deviation.

ResponseName

String giving naming the response variable.

RMSE

Root mean squared error, a scalar that is an estimate of the standard deviation of the error term in the model.

Robust

Structure that is empty unless fitnlm constructed the model using robust regression.

FieldDescription
WgtFunRobust weighting function, such as 'bisquare' (see robustfit)
TuneValue specified for tuning parameter (can be [])
WeightsVector of weights used in final iteration of robust fit

Rsquared

Proportion of total sum of squares explained by the model. The ordinary R-squared value relates to the SSR and SST properties:

Rsquared = SSR/SST = 1 - SSE/SST.

For a linear or nonlinear model, Rsquared is a structure with two fields:

• Ordinary — Ordinary (unadjusted) R-squared

For a generalized linear model, Rsquared is a structure with five fields:

• Ordinary — Ordinary (unadjusted) R-squared

• LLR — Log-likelihood ratio

• Deviance — Deviance

To obtain any of these values as a scalar, index into the property using dot notation. For example, the adjusted R-squared value in mdl is

`r2 = mdl.Rsquared.Adjusted`

SSE

Sum of squared errors (residuals).

The Pythagorean theorem implies

SST = SSE + SSR.

SSR

Regression sum of squares, the sum of squared deviations of the fitted values from their mean.

The Pythagorean theorem implies

SST = SSE + SSR.

SST

Total sum of squares, the sum of squared deviations of y from mean(y).

The Pythagorean theorem implies

SST = SSE + SSR.

VariableInfo

Table containing metadata about Variables. There is one row for each term in the model, and the following columns.

FieldDescription
ClassString giving variable class, such as 'double'
RangeCell array giving variable range:
• Continuous variable — Two-element vector [min,max], the minimum and maximum values

• Categorical variable — Cell array of distinct variable values

InModelLogical vector, where true indicates the variable is in the model
IsCategoricalLogical vector, where true indicates a categorical variable

VariableNames

Cell array of strings containing names of the variables in the fit.

• If the fit is based on a table or dataset, this property provides the names of the variables in that table or dataset.

• If the fit is based on a predictor matrix and response vector, VariableNames is the values in the VarNames name-value pair of the fitting method.

• Otherwise the variables have the default fitting names.

Variables

Table containing the data, both observations and responses, that the fitting function used to construct the fit. If the fit is based on a table or dataset array, Variables contains all of the data from that table or dataset array. Otherwise, Variables is a table created from the input data matrix X and response vector y.

## Methods

 coefCI Confidence intervals of coefficient estimates of nonlinear regression model coefTest Linear hypothesis test on nonlinear regression model coefficients disp Display nonlinear regression model feval Evaluate nonlinear regression model prediction fit Fit nonlinear regression model plotDiagnostics Plot diagnostics of nonlinear regression model plotResiduals Plot residuals of nonlinear regression model plotSlice Plot of slices through fitted nonlinear regression surface predict Predict response of nonlinear regression model random Simulate responses for nonlinear regression model

## Definitions

### Hat Matrix

The hat matrix H is defined in terms of the data matrix X and the Jacobian matrix J:

${J}_{i,j}={\frac{\partial f}{\partial {\beta }_{j}}|}_{{x}_{i},\beta }$

Here f is the nonlinear model function, and β is the vector of model coefficients.

The Hat Matrix H is

H = J(JTJ)–1JT.

The diagonal elements Hii satisfy

$\begin{array}{l}0\le {h}_{ii}\le 1\\ \sum _{i=1}^{n}{h}_{ii}=p,\end{array}$

where n is the number of observations (rows of X), and p is the number of coefficients in the regression model.

### Leverage

The leverage of observation i is the value of the ith diagonal term, hii, of the hat matrix H. Because the sum of the leverage values is p (the number of coefficients in the regression model), an observation i can be considered to be an outlier if its leverage substantially exceeds p/n, where n is the number of observations.

### Cook's Distance

The Cook's distance Di of observation i is

${D}_{i}=\frac{\sum _{j=1}^{n}{\left({\stackrel{^}{y}}_{j}-{\stackrel{^}{y}}_{j\left(i\right)}\right)}^{2}}{p\text{\hspace{0.17em}}MSE},$

where

• ${\stackrel{^}{y}}_{j}$ is the jth fitted response value.

• ${\stackrel{^}{y}}_{j\left(i\right)}$ is the jth fitted response value, where the fit does not include observation i.

• MSE is the mean squared error.

• p is the number of coefficients in the regression model.

Cook's distance is algebraically equivalent to the following expression:

${D}_{i}=\frac{{r}_{i}^{2}}{p\text{\hspace{0.17em}}MSE}\left(\frac{{h}_{ii}}{{\left(1-{h}_{ii}\right)}^{2}}\right),$

where ei is the ith residual.

## Copy Semantics

Value. To learn how value classes affect copy operations, see Copying Objects in the MATLAB® documentation.

## Examples

expand all

### Nonlinear Model

Create a nonlinear model for auto mileage based on the carbig data. Predict the mileage of an average car.

Load the data and create a nonlinear model.

```load carbig
X = [Horsepower,Weight];
y = MPG;
modelfun = @(b,x)b(1) + b(2)*x(:,1).^b(3) + ...
b(4)*x(:,2).^b(5);
beta0 = [-50 500 -1 500 -1];
mdl = fitnlm(X,y,modelfun,beta0)```
```mdl =

Nonlinear regression model:
y ~ b1 + b2*x1^b3 + b4*x2^b5

Estimated Coefficients:
Estimate      SE        tStat       pValue
________    _______    ________    ________

b1     -49.383     119.97    -0.41164     0.68083
b2      376.43     567.05     0.66384     0.50719
b3    -0.78193    0.47168     -1.6578    0.098177
b4      422.37     776.02     0.54428     0.58656
b5    -0.24127    0.48325    -0.49926     0.61788

Number of observations: 392, Error degrees of freedom: 387
Root Mean Squared Error: 3.96
F-statistic vs. constant model: 283, p-value = 1.79e-113```

Find the predicted mileage of an average auto. The data contain some observations with NaN, so compute the mean using nanmean.

`Xnew = nanmean(X)`
```Xnew =
1.0e+03 *
0.1051    2.9794```
`MPGnew = predict(mdl,Xnew)`
```MPGnew =

21.8073```