Deviance goodness-of-fit test Created 2026-10-06 Updated 2026-10-14
For a suitably regular generalized linear model, a residual deviance can be compared approximately with a chi-squared distribution on degrees of freedom to assess fit relative to the saturated model. Sparse or very small expected cell counts can invalidate this reference distribution. A large p-value means no detected lack of fit, not proof of correctness; dependence, wrong mean structure or overdispersion still require diagnostics.
For known size , the negative binomial distribution is an exponential family with natural parameter and cumulant . A generalized linear model can use a logarithmic link function for its mean, even though that link is not canonical. Jointly estimating the size changes the family and variance function, requiring additional updates beyond a single fixed-family GLM fit; this is what MASS::glm.nb does.
Generalized linear mixed model Created 2026-09-24 Updated 2026-10-14
A generalized linear mixed model adds latent random effects to the linear predictor of a generalized linear model.
An offset is a known term in a generalized linear model's linear predictor, with coefficient fixed to one. With a log link and exposure , choosing gives a mean count . Its role differs from that of a fitted explanatory-variable coefficient.
Identity link Created 2026-10-14 Updated 2026-10-20
The identity link function equates the response mean with the linear predictor. In a generalized linear model it gives . It is the canonical link function for the normal distribution. For response families whose means must remain positive or between zero and one, using the identity link requires corresponding restrictions on the linear predictor.
The prose names a second year that differs from the table label. The calculations use the four supplied counts, interpreting the first and second rows as the two displayed periods; no numerical conclusion depends on resolving that label discrepancy.
The first generalized linear model treats the four counts as independent Poisson random variables, with a log link and both row and column regression factors. The row-by-column interaction makes the log-linear model saturated. With , write
Its four maximum-likelihood fitted values equal the observed counts. Thus , , , and
The interaction is the log odds ratio measuring association of row and column. Under independent Poisson sampling, the delta-method variances are for the intercept, for the row contrast, for the column contrast, and for the interaction. Their square roots reproduce the printed standard errors. Although the software labels the standardized ratios as t values, these are asymptotic normal Wald statistics, with known Poisson dispersion one, not exact finite-df Student tests.
The statistical saturated model has zero residual deviance and zero residual degrees of freedom; this is a perfect interpolation, not evidence of predictive adequacy. The null deviance compares the four observed counts with an intercept-only model, whose four fitted means are . Fisher scoring is the numerical score/information iteration used to fit the model; the iteration count is a convergence report, not a test statistic.
Dropping the interaction gives the independence log-linear model for a two-way contingency table, . Its Poisson regression margin-matching score equations match the row and column totals, so
Here and denote the observed row and column totals. In particular the fitted row multiplier is , the column multiplier is , and the intercept is . These produce the second coefficient table. Their standard errors follow from the inverse Fisher information matrix; for the row and column contrasts their squared values are and , while the intercept variance is .
The Poisson deviance relative to the saturated fit is
The linear terms cancel because fitted and observed totals agree. The additive model has three coefficients, leaving one degree of freedom. Wilks theorem calibrates this likelihood-ratio test approximately by , giving . The interaction Wald test instead gives ; the two are only asymptotically equivalent.
Fisher's exact test conditions on both margins under independence. If is the upper-left count, then
Its usual two-sided p-value sums the probabilities of all tables no more probable than the observed . That sum is , reproducing the output without an asymptotic approximation. It tests the same absence of row-column association, but conditioning and discreteness explain the numerical difference from the likelihood-ratio test.
In ordinary language, the male proportion among the cases is in the first row and in the second. The estimated case-sex odds ratio is , but its approximate 95-percent confidence interval is wide, . These small samples do not give convincing evidence that the sex composition of cases changed between the two periods. Failure to reject is not evidence that the compositions are exactly equal. Nor do these counts establish a male-to-female disease-incidence ratio or an incidence trend: population denominators and comparable ascertainment would be needed for those interpretations.
Differentiate the normalization of the exponential family density with respect to , assuming the regularity that permits differentiation under its integral. The density derivative is . Consequently
Differentiating the expectation once more gives , so
The log-likelihood derivative with respect to is . For the generalized linear model with linear predictor , the chain rule gives
Using independence to add the log-likelihood contributions proves the score function
Here includes the dispersion parameter . Defining instead a unit-dispersion variance function would require retaining an explicit in the denominator.
Each scan() command reads a numeric vector from the entered data: the first creates the nine counts, and the second their nine predictor values. The last command fits a generalized linear model with the Poisson distribution and its default log link, including an intercept, then prints a summary. Thus the model is independent counts with means satisfying
The coefficients are maximum-likelihood estimates, and the reported standard errors come from the inverse fitted Fisher information matrix. Increasing the predictor by one multiplies the fitted mean by , about a increase. The intercept corresponds to a mean at predictor zero, outside the observed range. Approximate coefficient-to-standard-error ratios are and ; the slope is strongly different from zero under the assumed model. A Wald confidence interval for the slope is about , or for the multiplicative change.
The deviance is twice the log-likelihood advantage of the saturated model over the fitted model. For these counts it is
with the logarithmic term interpreted as zero when a count is zero. The saturated model has nine freely fitted means; the fitted model has two independent regression coefficients, so the residual degrees of freedom are .
Under an adequate Poisson model and the usual large-sample approximation, is compared with . The reported is rather large relative to seven, but below the upper critical value about ; its approximate upper-tail probability is . Thus there is some indication of lack of fit or overdispersion, but not a rejection at the level on this diagnostic. The deviance-to-d.f. ratio is about ; it does not by itself prove an overdispersed model, and the chi-square approximation is imperfect for small counts.
There is one inconsistency in the supplied numerical output. Independently solving the Poisson score equations for the displayed nine counts gives , and deviance , agreeing with the printed estimates and deviance. But gives standard errors approximately and . In particular the printed slope standard error is not the standard Poisson-model value for these data. The interpretations above describe the supplied numbers; the directly recomputed slope ratio is and its normal-approximation interval is about . The conclusion of a strong increasing trend is unchanged.
The Poisson distribution mass function is
It is an exponential dispersion family of order one with
Indeed, and . A generalized linear model specifies independent random variables from a response exponential family, together with a linear predictor and a link function relating it to the response mean. The Poisson canonical link is .
For the insurance counts, let class and merit be the reference levels in a regression factor. The fitted Poisson regression assumes
The insured exposure is known; its logarithm is an offset, not a coefficient to estimate. The model has eight free mean parameters and fixes the dispersion parameter at one. It assumes additive class and merit effects on the log-rate scale, hence multiplicative effects on the rate scale without a class-by-merit interaction.
Apart from constants independent of the parameters, the log-likelihood is
Differentiating gives the Poisson regression margin-matching score equations
Thus the fitted totals equal the observed totals in each class and merit category, including the reference categories by subtraction. In design matrix notation these equations are . Fisher scoring solves them iteratively; the reported three iterations describe the numerical fit, not an additional statistical result.
The regression intercept gives the baseline fitted claim rate per insured car year. The merit rate ratios, relative to merit at the same class, are
The class rate ratios, relative to class at the same merit, are
Each predicted cell rate is the baseline rate times its class and merit multipliers. The output's coefficient-to-standard error ratios are asymptotic normal Wald test statistics under the fitted Poisson regression, despite the software label “t value”; there is no estimated Gaussian residual scale in this model. All nonreference effects have very large absolute ratios.
The null Poisson deviance is on nineteen statistical degrees of freedom; adding the seven factor coefficients reduces it by . But the final Poisson deviance is still on twelve statistical degrees of freedom, and the deviance residuals include values near and . These are far beyond what a well-fitting unit-dispersion model would normally produce. The additive Poisson model fits substantially better than a common rate, but remains grossly inadequate. A class-by-merit interaction, overdispersion, or statistical dependence between claims could contribute; the summary alone does not distinguish these explanations. Its very small nominal standard errors and formal Wald tests rely on the rejected model, so improved mean structure and error assumptions are needed before treating them as reliable uncertainty assessments.
The fitted grouped-binomial logistic regression generalized linear model treats seasonal hits as independent variables, with and
Thus the response supplied to glm is a proportion, and weights=AB supplies its binomial denominator; it is not a regression with equally precise seasonal averages. I(Age^2) forms the numerical square rather than using a formula operator. The estimates maximize up to a constant, where , .
The observed negative Hessian is , . Expanding the score around the true parameter and applying a central-limit approximation gives . The reported standard errors are square roots of the diagonal entries of this inverse; the binomial dispersion is fixed at one. Each z value divides the coefficient estimate by its standard error, and the reported two-sided Wald test uses a standard normal approximation under the corresponding zero-coefficient hypothesis.
The last line reports the deviance against the saturated model,
with . There are 22 seasonal observations and three fitted parameters, so 19 degrees of freedom. Under the quadratic-logit model, independent binomial sampling and sufficiently large expected counts, . The value 23.345 gives an upper-tail probability about 0.22, no evidence of lack of fit at conventional levels. This approximation and the independence assumption should not be confused with an exact test of a player's ability.
The final commands recover the coefficients, apply the inverse logit , plot the observed averages against age, and join the fitted probabilities at the observed ages. The fitted curve is smooth, rises towards its peak at , then falls. Its maximum is about 0.373; the early and late observed points include markedly lower averages. The plot uses equally sized points even though their binomial precisions differ.
Figure 1.
Observed seasonal batting averages and the fitted quadratic logistic curve
. Details.
In a generalized linear model, the linear predictor is , a linear combination of the covariates with unknown coefficients. The link function relates this predictor to the mean: . The canonical link function chooses the natural parameter of the exponential family, namely . Differentiating the normalization of the density shows that , so the canonical link function is on the admissible parameter interval.
For a Bernoulli distribution, the probability mass function can be written as
Thus and . The canonical link is the logit:
One useful starting point is reverse correlation, implemented as a spike-triggered average. Present a long stimulus record and retain the stimulus history before each observed spike. After subtracting the stimulus mean, estimate
where is the number of spikes and is the history window. This identifies a candidate temporal receptive field. For white Gaussian stimulation and a one-filter encoding model, the average is proportional to the relevant filter, provided the response nonlinearity does not make that average vanish. For example an even response to the projection can have zero average despite strong stimulus dependence. Colored inputs require accounting for stimulus covariance, and more than one relevant stimulus direction may require a richer fitted model.
Use the candidate filter in an LNP model:
Estimate the static nonlinearity by binning filter projections and dividing spike counts by exposure time in each bin. Equivalently, Bayes' rule gives under this model. Refine the filter and nonlinearity by maximizing the conditional Poisson log-likelihood
with suitable regularization. Simulate an Inhomogeneous Poisson process at the fitted rate using integrated-intensity inversion from the previous solution. This gives a statistical encoding model, not a claim to reconstruct the neuron's ion channels.
Use cross-validation: estimate parameters on one set of trials and test them on independent held-out trials. Under repeated identical stimuli, compare the observed and simulated trial-averaged firing rates, spike-count distributions, interspike-interval distributions and autocorrelations. Compare held-out likelihoods and predictive errors with simpler baseline models and with the variability between real repeats. Exact spike-by-spike agreement is not expected from two independent realizations of a stochastic model. Large rate agreement accompanied by incorrect short-interval or correlation statistics reveals missing dynamics. Adding a spike-history term, for example in a point-process generalized linear model, can account for refractoriness or bursting when the basic Poisson cascade fails.
A good model predicts held-out response distributions, not just its training spike train. Such a model summarizes what stimulus features affect the neuron, permits controlled simulated changes of those features, and tests whether the proposed computation is sufficient. Its failures can suggest further experiments or additional stimulus and history variables.
Write . Ignoring only terms independent of , the Poisson log-likelihood is . The multinomial model is defined on the constraint , since its probabilities must sum to one. On this constraint its full log-likelihood satisfies
where both likelihoods include the same terms. Thus they differ by a constant on the admissible multinomial parameter set.
If the Poisson maximum-likelihood estimator has , it is feasible for the multinomial problem, and no feasible parameter can have a larger likelihood than it. Consequently it is also a multinomial maximum. With the usual uniqueness and identifiability assumption,
Without uniqueness, the precise conclusion is that is a multinomial maximizer; arbitrary independently chosen maximizers need not be identical. This qualification is necessary for a general unspecified parametrization.
In a log-linear generalized linear model with an unrestricted intercept, differentiation with respect to that intercept gives . Thus the fitted total automatically equals . One can fit independent Poisson cell counts using the usual GLM machinery and recover the multinomial fitted probabilities as . The result is constrained Poisson and multinomial likelihood equivalence, not an assertion that the sampling experiments themselves are identical.
A Poisson distribution has probability mass , where . It is an exponential family with , mean and variance . The responses are independent, their linear predictors are , and the log link relates these predictors to their means. These are precisely the components of a generalized linear model; the log link is its canonical link function and the dispersion is one.
The log-likelihood and score function are
Thus a finite maximum-likelihood estimator satisfies
The Hessian is ; with a full-rank design matrix it is negative definite at finite parameter values, so a finite solution is the unique maximum. A finite maximum need not exist for every possible response/design combination; the displayed equations describe it when it does exist. If the first component of every is one, the first score equation gives .
The saturated model fits each mean as , with the limiting mean zero allowed for a zero count. Subtracting the fitted log-likelihood from the saturated log-likelihood gives the Poisson deviance
where . With an intercept, the sum of the second terms is zero, but retaining them is necessary without that score equation.
Take low pH as a reference level. For group , the model with interaction has
where is biomass. The additive model sets every to zero. The interaction model estimates six parameters and the additive model four. In the additive model the log-mean curves are parallel straight lines, while the mean curves are positive exponentials with fixed ratios . In the interaction model the log-mean slopes differ, and the mean ratio is . The following sketches illustrate common versus factor-specific slopes in Poisson regression; their coefficients are illustrative, not estimates from the data.
Figure 1.
Illustrative Poisson mean curves with common and pH-specific biomass slopes
. Details.
The additive model is nested in the interaction model with two restrictions. The likelihood-ratio test therefore uses
whose p-value is . There is strong evidence that the biomass slope on the log-mean scale depends on pH. The interaction-model residual deviance is close to its residual degrees of freedom, giving no obvious indication of overdispersion from this comparison alone. The supplied deviances contain no slope estimates: they do not establish which pH group has more species, whether each slope is positive or negative, or whether any actual curves cross. Those conclusions require the fitted coefficients and their uncertainty.
An exponential dispersion family of order one has density or mass function, relative to a fixed dominating measure, of the form
where is a scalar natural parameter, is the dispersion parameter, and the support does not depend on . For regular families, is twice differentiable on an open natural-parameter domain and . Known observation weights replace by . “Order one” refers to the scalar canonical statistic , rather than an arbitrary vector of canonical statistics.
Differentiate the normalization , or its discrete counterpart, assuming differentiation under the integral is valid. The first derivative gives . The second derivative gives
Consequently,
The variance function expresses the second derivative in terms of the mean:
A generalized linear model specifies independent responses from an exponential dispersion family, a linear predictor , and a differentiable monotone link function relating it to the response mean by . The family, variance function, covariate design, link function and dispersion specification together define the model. The canonical link function identifies the linear predictor with the natural parameter:
One advantage is that the likelihood equations become particularly simple. With known weights and common dispersion , the score function and negative Hessian matrix for are
The latter does not explicitly depend on the responses, so it equals the expected Fisher information matrix at the same parameter. With full-rank design and positive variances the likelihood is strictly concave in , simplifying optimization. These statements concern the coefficient block at a fixed dispersion value.
Three explicit examples, taking unit weights, are as follows.
For a normal distribution with mean and variance ,
Thus , , , and . Its canonical link function is , the identity link.
For a Poisson distribution with mean and support ,
Here , , , and . Therefore , , and the Poisson canonical link is .
For a Bernoulli distribution with success probability ,
Taking , , , and gives the required form. Its mean and variance function are and . Its canonical link function is , the logit link. The fixed dispersion values in the Poisson and Bernoulli cases are part of those models; an arbitrary continuous dispersion is not being asserted for them.
To test , first fit the unrestricted model and then the restricted model with that component fixed at zero, estimating all nuisance parameters, including dispersion when applicable, in each fit. If and denote their full fitted parameter vectors, the likelihood-ratio test uses
For identifiable regular models, an interior null parameter and a fixed-dimensional full-rank design with increasing information, the Wilks theorem gives under . A level- test rejects for greater than the -quantile of the chi-squared distribution with one degree of freedom.
Alternatively the Wald test uses , with the variance obtained from the appropriate inverse full Fisher information matrix; it has the same limiting null law. The score test fits only the restricted model. If collects its nuisance parameters, its efficient information is , and the statistic is , again asymptotically . Accounting for the nuisance block is necessary rather than using the unadjusted diagonal information.
A generalized linear model has independent responses whose distributions belong to an exponential family:
Here the expected value and variance are and . A specified one-to-one link function connects the mean to the linear predictor: . The canonical link function is .
In binomial regression, independently, with known trial counts and probabilities related to the predictor. The logistic regression and probit regression specifications are respectively
Here is the standard normal distribution function. The binomial log-density contains , so its natural parameter is the log-odds: the logistic link is canonical. If the response mean is written as , the canonical link is .
Index independent experimental vials by , write for the observed total eaten and for the number of other-species eggs eaten. The grouped-binomial logistic regression uses
Here and identify day and adult species, and the free effects are . There is no day-species interaction. The weights in the binomial generalized linear model are the denominators , so fitting the proportions gives this binomial likelihood, not 23 Bernoulli observations. The dispersion is fixed at one. This is a model for the composition of eggs eaten conditional on the total, rather than a model for the total appetite.
There are 23 independent vial responses. The intercept-only fit has 22 residual statistical degrees of freedom and deviance 33.631. Adding two day indicators removes two statistical degrees of freedom and reduces the residual deviance by . Adding the two species indicators then reduces it by . Thus the six replacements, in their printed order, are .
The residual deviance statistical degrees of freedom are , , and . These sequential analysis-of-deviance rows compare nested generalized linear models in the displayed order. In an unbalanced design, the first day row does not test day after controlling for species.
For the Poisson regression, the log-likelihood is
Since , the score function and its derivative are
Consequently a finite maximum-likelihood estimator satisfies
These nonlinear equations are normally solved by iteratively reweighted least squares. If has full column rank, the Hessian is negative definite and any finite solution is the unique maximizer. Full rank does not by itself rule out a boundary solution at infinite coefficients for every conceivable data set. The Poisson generalized linear model has dispersion one, so there is no separate scale parameter in this likelihood.
A generalized linear model specifies independent responses in an exponential dispersion family, their means , and a link function connecting those means to a linear predictor. In the common notation,
where are known positive weights, is the common dispersion parameter, and is the variance function. The systematic part is
Here is a row of the known design matrix and contains the unknown regression coefficients. The link function is invertible on the permitted mean domain; the canonical link function takes the mean to the natural parameter. This separates distributional, predictor, and link assumptions: it does not require the response itself to be normally distributed or the mean itself to be linear in the covariates.