**Class: **GeneralizedLinearModel

(Not Recommended) Create generalized linear regression model

`GeneralizedLinearModel.fit`

is not recommended. Use `fitglm`

instead.

`mdl = GeneralizedLinearModel.fit(tbl)`

mdl = GeneralizedLinearModel.fit(X,y)

mdl = GeneralizedLinearModel.fit(...,modelspec)

mdl = GeneralizedLinearModel.fit(...,Name,Value)

mdl =
GeneralizedLinearModel.fit(...,modelspec,Name,Value)

creates a generalized linear model of a table or dataset array `mdl`

= GeneralizedLinearModel.fit(`tbl`

)`tbl`

.

creates a generalized linear model of the responses `mdl`

= GeneralizedLinearModel.fit(`X`

,`y`

)`y`

to a data matrix
`X`

.

creates a generalized linear model as specified by `mdl`

= GeneralizedLinearModel.fit(...,`modelspec`

)`modelspec`

.

or
`mdl`

= GeneralizedLinearModel.fit(...,`Name,Value`

)

creates a generalized linear model with additional options specified by one or more
`mdl`

=
GeneralizedLinearModel.fit(...,`modelspec`

,`Name,Value`

)`Name,Value`

pair arguments.

`tbl`

— Input datatable | dataset array

Input data including predictor and response variables, specified as a table or dataset array.
The predictor variables and response variable can be numeric, logical, categorical,
character, or string. The response variable can have a data type other than numeric only
if `'Distribution'`

is `'binomial'`

.

By default,

`GeneralizedLinearModel.fit`

takes the last variable as the response variable and the others as the predictor variables.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.To define a model specification, set the

`modelspec`

argument using a formula or terms matrix. The formula or terms matrix specifies which columns to use as the predictor or response variables.

The variable names in a table do not have to be valid MATLAB^{®} identifiers. However, if the names are not valid, you cannot use a formula
when you fit or adjust a model; for example:

You cannot specify

`modelspec`

using a formula.You cannot use a formula to specify the terms to add or remove when you use the

`addTerms`

function or the`removeTerms`

function, respectively.You cannot use a formula to specify the lower and upper bounds of the model when you use the

`step`

or`stepwiseglm`

function with the name-value pair arguments`'Lower'`

and`'Upper'`

, respectively.

You can verify the variable names in `tbl`

by using the `isvarname`

function. The following code returns logical `1`

(`true`

) for each variable that has a valid variable name.

cellfun(@isvarname,tbl.Properties.VariableNames)

`tbl`

are not valid, then convert them by using the `matlab.lang.makeValidName`

function.tbl.Properties.VariableNames = matlab.lang.makeValidName(tbl.Properties.VariableNames);

`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`

`y`

— Response variablevector | matrix

Response variable, specified as a vector or matrix.

If

`'Distribution'`

is not`'binomial'`

, then`y`

must be 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`

. The data type must be single or double.If

`'Distribution'`

is`'binomial'`

, then`y`

can be an*n*-by-1 vector or*n*-by-2 matrix with counts in column 1 and`BinomialSize`

in column 2.

**Data Types: **`single`

| `double`

| `logical`

| `categorical`

`modelspec`

— Model specification`'linear'`

(default) | character vector or string scalar naming the model | ```
'Y ~
terms'
```

Model specification, specified as one of the following:

Character vector or string scalar specifying the type of model.

Value Model Type `'constant'`

Model contains only a constant (intercept) term. `'linear'`

Model contains an intercept and linear term for each predictor. `'interactions'`

Model contains an intercept, linear term for each predictor, and all products of pairs of distinct predictors (no squared terms). `'purequadratic'`

Model contains an intercept term and linear and squared terms for each predictor. `'quadratic'`

Model contains an intercept term, linear and squared terms for each predictor, and all products of pairs of distinct predictors. `'poly`

'`ijk`

Model is a polynomial with all terms up to degree in the first predictor, degree`i`

in the second predictor, and so on. Specify the maximum degree for each predictor by using numerals 0 though 9. The model contains interaction terms, but the degree of each interaction term does not exceed the maximum value of the specified degrees. For example,`j`

`'poly13'`

has an intercept and*x*_{1},*x*_{2},*x*_{2}^{2},*x*_{2}^{3},*x*_{1}**x*_{2}, and*x*_{1}**x*_{2}^{2}terms, where*x*_{1}and*x*_{2}are the first and second predictors, respectively.*t*-by-(*p*+1) matrix, namely terms matrix, specifying terms to include in model, where*t*is the number of terms and*p*is the number of predictor variables, and plus one is for the response variable.Character vector or string scalar representing a formula in the form

where the`'`

,~`Y`

'`terms`

`terms`

are in Wilkinson Notation.

**Example: **`'quadratic'`

Specify optional
comma-separated pairs of `Name,Value`

arguments. `Name`

is
the argument name and `Value`

is the corresponding value.
`Name`

must appear inside quotes. You can specify several name and value
pair arguments in any order as
`Name1,Value1,...,NameN,ValueN`

.

`'BinomialSize'`

— Number of trials for binomial distribution1 (default) | numeric scalar | numeric vector | character vector | string scalar

Number of trials for binomial distribution, that is the sample size, specified as the
comma-separated pair consisting of `'BinomialSize'`

and the
variable name in `tbl`

, a numeric scalar, or a numeric
vector of the same length as the response. This is the parameter
`n`

for the fitted binomial distribution.
`BinomialSize`

applies only when the
`Distribution`

parameter is
`'binomial'`

.

If `BinomialSize`

is a scalar value, that means
all observations have the same number of trials.

As an alternative to `BinomialSize`

, you can specify the response as a
two-column matrix with counts in column 1 and `BinomialSize`

in column
2.

**Data Types: **`single`

| `double`

| `char`

| `string`

`'CategoricalVars'`

— Categorical variable liststring array | cell array of character vectors | logical or numeric index vector

Categorical variable list, specified as the comma-separated pair consisting of
`'CategoricalVars'`

and either a string array or cell array of
character vectors containing categorical variable names in the table or dataset array
`tbl`

, or a logical or numeric index vector indicating which
columns are categorical.

If data is in a table or dataset array

`tbl`

, then, by default,`GeneralizedLinearModel.fit`

treats all categorical values, logical values, character arrays, string arrays, and cell arrays of character vectors as categorical variables.If data is in matrix

`X`

, then the default value of`'CategoricalVars'`

is an empty matrix`[]`

. That is, no variable is categorical unless you specify it as categorical.

For example, you can specify the observations 2 and 3 out of 6 as categorical using either of the following examples.

**Example: **`'CategoricalVars',[2,3]`

**Example: **`'CategoricalVars',logical([0 1 1 0 0 0])`

**Data Types: **`single`

| `double`

| `logical`

| `string`

| `cell`

`'DispersionFlag'`

— Indicator to compute dispersion parameter`false`

for `'binomial'`

and `'poisson'`

distributions (default) | `true`

Indicator to compute dispersion parameter for `'binomial'`

and `'poisson'`

distributions,
specified as the comma-separated pair consisting of `'DispersionFlag'`

and
one of the following.

`true` | Estimate a dispersion parameter when computing standard errors |

`false` | Default. Use the theoretical value when computing standard errors |

The fitting function always estimates the dispersion for other distributions.

**Example: **`'DispersionFlag',true`

`'Distribution'`

— Distribution of the response variable`'normal'`

(default) | `'binomial'`

| `'poisson'`

| `'gamma'`

| `'inverse gaussian'`

Distribution of the response variable, specified as the comma-separated
pair consisting of `'Distribution'`

and one of the
following.

`'normal'` | Normal distribution |

`'binomial'` | Binomial distribution |

`'poisson'` | Poisson distribution |

`'gamma'` | Gamma distribution |

`'inverse gaussian'` | Inverse Gaussian distribution |

**Example: **`'Distribution','gamma'`

`'Exclude'`

— Observations to excludelogical or numeric index vector

Observations to exclude from the fit, specified as the comma-separated
pair consisting of `'Exclude'`

and a logical or numeric
index vector indicating which observations to exclude from the fit.

For example, you can exclude observations 2 and 3 out of 6 using either of the following examples.

**Example: **`'Exclude',[2,3]`

**Example: **`'Exclude',logical([0 1 1 0 0 0])`

**Data Types: **`single`

| `double`

| `logical`

`'Intercept'`

— Indicator for constant term`true`

(default) | `false`

Indicator for the constant term (intercept) in the fit, specified as the comma-separated pair
consisting of `'Intercept'`

and either `true`

to
include or `false`

to remove the constant term from the model.

Use `'Intercept'`

only when specifying the model using a character vector or
string scalar, not a formula or matrix.

**Example: **`'Intercept',false`

`'Link'`

— Link functioncanonical link function (default) | scalar value | structure

Link function to use in place of the canonical link function,
specified as the comma-separated pair consisting of `'Link'`

and
one of the following.

Link Function Name | Link Function | Mean (Inverse) Function |
---|---|---|

`'identity'` | f(μ) = μ | μ = Xb |

`'log'` | f(μ) = log(μ) | μ = exp(Xb) |

`'logit'` | f(μ) = log(μ/(1–μ)) | μ = exp(Xb) / (1
+ exp(Xb)) |

`'probit'` | f(μ) = Φ^{–1}(μ) | μ = Φ(Xb) |

`'comploglog'` | f(μ) = log(–log(1
– μ)) | μ = 1 – exp(–exp(Xb)) |

`'reciprocal'` | f(μ) = 1/μ | μ = 1/(Xb) |

`p` (a number) | f(μ) = μ^{p} | μ = Xb^{1/p} |

`S.Link` — The link function`S.Inverse` — The inverse link function`S.Derivative` — The derivative of the link function
| f(μ) = `S.Link` (μ) | μ = `S.Inverse` (Xb) |

The link function defines the relationship *f*(*μ*)
= *X***b* between the mean response *μ* and
the linear combination of predictors *X***b*.

For more information on the canonical link functions, see Canonical Link Function.

**Example: **`'Link','probit'`

**Data Types: **`char`

| `string`

| `single`

| `double`

| `struct`

`'Offset'`

— Offset variable[ ] (default) | vector | character vector | string scalar

Offset variable in the fit, specified as the comma-separated
pair consisting of `'Offset'`

and a vector or name
of a variable with the same length as the response.

`GeneralizedLinearModel.fit`

uses `Offset`

as an additional predictor,
with a coefficient value fixed at 1.0. In other words, the formula for
fitting is

*f*(*μ*)```
~ Offset +
(terms involving real predictors)
```

with the `Offset`

predictor having coefficient `1`

.

For example, consider a Poisson regression model. Suppose the
number of counts is known for theoretical reasons to be proportional
to a predictor `A`

. By using the log link function
and by specifying `log(A)`

as an offset, you can
force the model to satisfy this theoretical constraint.

**Data Types: **`single`

| `double`

| `char`

| `string`

`'PredictorVars'`

— Predictor variablesstring array | cell array of character vectors | logical or numeric index vector

Predictor variables to use in the fit, specified as the comma-separated pair consisting of
`'PredictorVars'`

and either a string array or cell array of
character vectors of the variable names in the table or dataset array
`tbl`

, or a logical or numeric index vector indicating which
columns are predictor variables.

The string values or character vectors should be among the names in `tbl`

, or
the names you specify using the `'VarNames'`

name-value pair
argument.

The default is all variables in `X`

, or all
variables in `tbl`

except for `ResponseVar`

.

For example, you can specify the second and third variables as the predictor variables using either of the following examples.

**Example: **`'PredictorVars',[2,3]`

**Example: **`'PredictorVars',logical([0 1 1 0 0 0])`

**Data Types: **`single`

| `double`

| `logical`

| `string`

| `cell`

`'ResponseVar'`

— Response variablelast column in

`tbl`

(default) | character vector or string scalar containing variable name | logical or numeric index vectorResponse variable to use in the fit, specified as the comma-separated pair consisting of
`'ResponseVar'`

and either a character vector or string scalar
containing the variable name in the table or dataset array `tbl`

, or a
logical or numeric index vector indicating which column is the response variable. You
typically need to use `'ResponseVar'`

when fitting a table or dataset
array `tbl`

.

For example, you can specify the fourth variable, say `yield`

,
as the response out of six variables, in one of the following ways.

**Example: **`'ResponseVar','yield'`

**Example: **`'ResponseVar',[4]`

**Example: **`'ResponseVar',logical([0 0 0 1 0 0])`

**Data Types: **`single`

| `double`

| `logical`

| `char`

| `string`

`'VarNames'`

— Names of variables`{'x1','x2',...,'xn','y'}`

(default) | string array | cell array of character vectorsNames of variables, specified as the comma-separated pair consisting of
`'VarNames'`

and a string array or cell array of character vectors
including the names for the columns of `X`

first, and the name for the
response variable `y`

last.

`'VarNames'`

is not applicable to variables in a table or dataset
array, because those variables already have names.

The variable names do not have to be valid MATLAB identifiers. However, if the names are not valid, you cannot use a formula when you fit or adjust a model; for example:

You cannot use a formula to specify the terms to add or remove when you use the

`addTerms`

function or the`removeTerms`

function, respectively.You cannot use a formula to specify the lower and upper bounds of the model when you use the

`step`

or`stepwiseglm`

function with the name-value pair arguments`'Lower'`

and`'Upper'`

, respectively.

Before specifying `'VarNames',varNames`

, you can verify the variable
names in `varNames`

by using the `isvarname`

function. The following code returns logical
`1`

(`true`

) for each variable that has a valid
variable name.

cellfun(@isvarname,varNames)

`varNames`

are not valid, then convert them by
using the `matlab.lang.makeValidName`

function.varNames = matlab.lang.makeValidName(varNames);

**Example: **`'VarNames',{'Horsepower','Acceleration','Model_Year','MPG'}`

**Data Types: **`string`

| `cell`

`'Weights'`

— Observation weights`ones(n,1)`

(default) | Observation weights, specified as the comma-separated pair consisting
of `'Weights'`

and an *n*-by-1 vector
of nonnegative scalar values, where *n* is the number
of observations.

**Data Types: **`single`

| `double`

`mdl`

— Generalized linear model`GeneralizedLinearModel`

objectGeneralized linear model representing a least-squares fit of
the link of the response to the data, returned as a `GeneralizedLinearModel`

object.

For properties and methods of the generalized linear model object, `mdl`

,
see the `GeneralizedLinearModel`

class
page.

Fit a logistic regression model of probability of smoking as a function of age, weight, and sex, using a two-way interactions model.

Load the `hospital`

dataset array.

load hospital ds = hospital; % just to use the ds name

Specify the model using a formula that allows up to two-way interactions.

`modelspec = 'Smoker ~ Age*Weight*Sex - Age:Weight:Sex';`

Create the generalized linear model.

mdl = fitglm(ds,modelspec,'Distribution','binomial')

mdl = Generalized linear regression model: logit(Smoker) ~ 1 + Sex*Age + Sex*Weight + Age*Weight Distribution = Binomial Estimated Coefficients: Estimate SE tStat pValue ___________ _________ ________ _______ (Intercept) -6.0492 19.749 -0.3063 0.75938 Sex_Male -2.2859 12.424 -0.18399 0.85402 Age 0.11691 0.50977 0.22934 0.81861 Weight 0.031109 0.15208 0.20455 0.83792 Sex_Male:Age 0.020734 0.20681 0.10025 0.92014 Sex_Male:Weight 0.01216 0.053168 0.22871 0.8191 Age:Weight -0.00071959 0.0038964 -0.18468 0.85348 100 observations, 93 error degrees of freedom Dispersion: 1 Chi^2-statistic vs. constant model: 5.07, p-value = 0.535

The large $$p$$-value indicates the model might not differ statistically from a constant.

A terms matrix `T`

is a
*t*-by-(*p* + 1) matrix specifying terms in a model,
where *t* is the number of terms, *p* is the number of
predictor variables, and +1 accounts for the response variable. The value of
`T(i,j)`

is the exponent of variable `j`

in term
`i`

.

For example, suppose that an input includes three predictor variables `A`

,
`B`

, and `C`

and the response variable
`Y`

in the order `A`

, `B`

,
`C`

, and `Y`

. Each row of `T`

represents one term:

`[0 0 0 0]`

— Constant term or intercept`[0 1 0 0]`

—`B`

; equivalently,`A^0 * B^1 * C^0`

`[1 0 1 0]`

—`A*C`

`[2 0 0 0]`

—`A^2`

`[0 1 2 0]`

—`B*(C^2)`

The `0`

at the end of each term represents the response variable. In
general, a column vector of zeros in a terms matrix represents the position of the response
variable. If you have the predictor and response variables in a matrix and column vector,
then you must include `0`

for the response variable in the last column of
each row.

A formula for model specification is a character vector or string scalar of
the form `'`

.* Y* ~

`terms`

is the response name.`Y`

represents the predictor terms in a model using Wilkinson notation.`terms`

For example:

`'Y ~ A + B + C'`

specifies a three-variable linear model with intercept.`'Y ~ A + B + C – 1'`

specifies a three-variable linear model without intercept. Note that formulas include a constant (intercept) term by default. To exclude a constant term from the model, you must include`–1`

in the formula.

Wilkinson notation describes the terms present in a model. The notation relates to the terms present in a model, not to the multipliers (coefficients) of those terms.

Wilkinson notation uses these symbols:

`+`

means include the next variable.`–`

means do not include the next variable.`:`

defines an interaction, which is a product of terms.`*`

defines an interaction and all lower-order terms.`^`

raises the predictor to a power, exactly as in`*`

repeated, so`^`

includes lower-order terms as well.`()`

groups terms.

This table shows typical examples of Wilkinson notation.

Wilkinson Notation | Term in Standard Notation |
---|---|

`1` | Constant (intercept) term |

`A^k` , where `k` is a positive
integer | `A` ,
`A` , ...,
`A` |

`A + B` | `A` , `B` |

`A*B` | `A` , `B` ,
`A*B` |

`A:B` | `A*B` only |

`–B` | Do not include `B` |

`A*B + C` | `A` , `B` , `C` ,
`A*B` |

`A + B + C + A:B` | `A` , `B` , `C` ,
`A*B` |

`A*B*C – A:B:C` | `A` , `B` , `C` ,
`A*B` , `A*C` ,
`B*C` |

`A*(B + C)` | `A` , `B` , `C` ,
`A*B` , `A*C` |

Statistics and Machine
Learning Toolbox™ notation always includes a constant term unless you explicitly remove the term
using `–1`

.

For more details, see Wilkinson Notation.

The default link function for a generalized linear model is the *canonical link
function*.

**Canonical Link Functions for Generalized Linear Models**

Distribution | Link Function Name | Link Function | Mean (Inverse) Function |
---|---|---|---|

`'normal'` | `'identity'` | f(μ) = μ | μ = Xb |

`'binomial'` | `'logit'` | f(μ) = log(μ/(1–μ)) | μ = exp(Xb) / (1
+ exp(Xb)) |

`'poisson'` | `'log'` | f(μ) = log(μ) | μ = exp(Xb) |

`'gamma'` | `-1` | f(μ) = 1/μ | μ = 1/(Xb) |

`'inverse gaussian'` | `-2` | f(μ) = 1/μ^{2} | μ = (Xb)^{–1/2} |

The generalized linear model

`mdl`

is a standard linear model unless you specify otherwise with the`Distribution`

name-value pair.For other methods such as

`devianceTest`

, or properties of the`GeneralizedLinearModel`

object, see`GeneralizedLinearModel`

.

You can also construct a generalized linear model using `fitglm`

.

Use `stepwiseglm`

to select a model specification automatically. Use `step`

,
`addTerms`

, or `removeTerms`

to adjust a fitted model.

[1] Collett, D. *Modeling Binary Data*. New York:
Chapman & Hall, 2002.

[2] Dobson, A. J. *An Introduction to Generalized Linear
Models*. New York: Chapman & Hall, 1990.

[3] McCullagh, P., and J. A. Nelder. *Generalized Linear
Models*. New York: Chapman & Hall, 1990.

A modified version of this example exists on your system. Do you want to open this version instead?

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

Select web siteYou can also select a web site from the following list:

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

- América Latina (Español)
- Canada (English)
- United States (English)

- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)

- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)