AI Wiki中文/EN

Generalized linear models: connect means to distributions

广义线性模型

Unify response distributions and link functions, then fit an original Poisson model with exposure offsets and explicit numerical diagnostics.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Counts, probabilities and measurements need different models

A fictional scanner records events during observation periods of different lengths. In setting 0 it records 2 events in one hour and 4 in two hours; in setting 1 it records 3 in one hour and 9 in three hours. Comparing the raw counts would mix two effects: operating setting and time spent observing.

A rate model separates them. The two fitted rates should be 2 and 3 events per hour. A two-hour prediction is then an expected count of 4 or 6. These are means of distributions, not promises that the next observations will equal those numbers.

Generalized linear models (GLMs) provide a way to connect a distribution for the response, a linear predictor and a function relating that predictor to the response mean. Linear regression and logistic regression are familiar members. This chapter uses a count model to show what their common structure adds, rather than deriving those two methods again. Stanford CS229, chapter 3.

Separate the distribution, mean and linear predictor

For the scalar-response version considered here, assume observations are conditionally independent given their inputs and parameters. A regular exponential-dispersion family can be written as:

p(y∣θ,ϕ)=exp⁡ ⁣(yθ−A(θ)ϕ+c(y,ϕ)),μ=A′(θ),Var⁡(Y)=ϕA′′(θ).p(y\mid\theta,\phi)=\exp\!\left(\frac{y\theta-A(\theta)}{\phi}+c(y,\phi)\right),\qquad\mu=A'(\theta),\qquad\operatorname{Var}(Y)=\phi A''(\theta).

Here θ is the natural parameter, A is the log normalizer, and φ is a positive dispersion parameter, common across observations in this formulation. The base term c makes the distribution integrate or sum to one. The mean and variance identities follow by differentiating that normalization under the usual regularity conditions. “Exponential family” does not mean that every response has an exponential distribution.

The GLM adds a linear predictor η and an invertible link g on the chosen mean domain:

ηi=vi⊤β+oi=g(μi),μi=g−1(ηi).\eta_i=v_i^\top\beta+o_i=g(\mu_i),\qquad\mu_i=g^{-1}(\eta_i).

The feature vector v includes an intercept column; o is an optional known offset with coefficient fixed at one. The link maps a mean to a linear predictor. The inverse link maps the predictor back to the mean. A canonical link chooses g(μ)=θ(μ), so η equals the natural parameter. Other valid links are possible; they must keep the resulting means inside the distribution’s domain. statsmodels 0.14.4, technical definition and family/link interface.

Conditional responseMean and conditional varianceCanonical linkInverse link
Gaussian measurementμ; variance σ²μη
Bernoulli outcome, 0 or 1μ; variance μ(1−μ)log(μ/(1−μ))sigmoid(η)
Poisson count, 0,1,2,…μ; variance μlog μexp η

Gaussian φ is σ²; Bernoulli and Poisson have φ=1. The Poisson mean is positive even though an observed count can be zero. A Bernoulli mean is a probability; a Poisson mean can exceed one. These conditional distribution choices say more than “fit a curve.” In particular, they impose different relationships between mean and variance.

Stanford’s chapter develops the canonical-link construction and uses η for the natural parameter. Here θ denotes that parameter, while η denotes the linear predictor, so the broader link choice remains visible. GLM is also distinct from the phrase “general linear model,” which commonly refers to Gaussian linear-model machinery, and from “generalized least squares,” which changes an error-covariance treatment.

An observation period is a known offset

For a positive exposure e and one numeric feature x, the count model is μ=e exp(β₀+β₁x). Thus o=log e. Doubling exposure doubles the expected count at the same x. The coefficient on log exposure is specified as one; it is not another fitted slope. This is the convention documented by the official GLM interface. Exposure and offset parameters.

Under independent Poisson responses, the average negative log-likelihood is:

ηi=β0+β1xi+log⁡ei,μi=eηi,J(β)=1n∑i(μi−yiηi+log⁡(yi!)).\eta_i=\beta_0+\beta_1x_i+\log e_i,\quad\mu_i=e^{\eta_i},\qquad J(\beta)=\frac1n\sum_i\left(\mu_i-y_i\eta_i+\log(y_i!)\right).

The factorial term does not affect fitted coefficients, but retaining it makes J the stated full log-likelihood loss. This is not least squares on log counts: log zero is undefined, and that transformation would change the observation model. There is no regularization in this implementation, for either coefficient.

With vᵢ=(1,xᵢ)ᵀ, differentiating gives:

∇J=1n∑i(μi−yi)vi,H=∇2J=1n∑iμivivi⊤,βtrial=β−αH−1∇J.\nabla J=\frac1n\sum_i(\mu_i-y_i)v_i,\qquad H=\nabla^2J=\frac1n\sum_i\mu_i v_i v_i^\top,\qquad\beta_{\mathrm{trial}}=\beta-\alpha H^{-1}\nabla J.

At finite coefficients, all means are positive. Two distinct feature values give a positive-definite Hessian in exact arithmetic. The loss is convex, but a finite minimizer still need not exist: a setting containing only zero counts can drive its fitted rate toward zero through an unbounded coefficient. A small numerical gradient does not prove existence of a finite maximum-likelihood estimate.

A small Newton fit with an inspectable stopping reason

For the Poisson log link, a Newton update also has an iteratively reweighted least-squares interpretation. At the current fit, define a working response z and weight w:

zi=ηi+yi−μiμi,wi=μi,βIRLS=arg min⁡b∑iwi(zi−oi−vi⊤b)2.z_i=\eta_i+\frac{y_i-\mu_i}{\mu_i},\qquad w_i=\mu_i,\qquad\beta_{\mathrm{IRLS}}=\operatorname*{arg\,min}_{b}\sum_iw_i\left(z_i-o_i-v_i^\top b\right)^2.

The known offset must be subtracted from the working response before fitting the coefficient vector. These weights change with the current means; this is not one fixed weighted least-squares problem. The program computes the equivalent two-by-two Newton system, then tries step sizes 1, 1/2, …, 1/2¹⁹ until its Armijo loss-decrease check passes.

The complete Python 3.10+ program accepts list/tuple rows (feature, count, exposure). Features and exposures are finite int/float values; counts are nonnegative integers; Booleans are rejected. Exposures must be strictly positive. The interface requires at least two distinct floating-point feature values and rejects an all-zero response, which has no finite intercept MLE. It stores an intercept separately and does not standardize features.

stop records gradient when the maximum absolute component of the average-loss gradient meets the tolerance, steps when the update limit is reached, curvature when the small system fails its numerical screen, or line-search when no trial passes. These are solver diagnostics, not statistical validation. Zero update allowance still evaluates the initial model and can report gradient if it already satisfies the criterion. steps in the returned record counts accepted updates.

# Python 3.10+; Poisson log-link, one feature, intercept and known exposure.
from math import exp, fsum, isfinite, lgamma, log


def sequence(value):
    if type(value) not in (list, tuple):
        raise ValueError('expected a list or tuple')
    return value


def number(value):
    if type(value) not in (int, float):
        raise ValueError('expected a finite number, not a Boolean')
    try:
        value = float(value)
    except OverflowError as error:
        raise ValueError('number outside floating-point range') from error
    if not isfinite(value):
        raise ValueError('number must be finite')
    return value


def mean(eta):
    try:
        mu = exp(eta)
    except OverflowError as error:
        raise ValueError('mean overflow') from error
    if not isfinite(mu) or mu <= 0:
        raise ValueError('mean outside positive floating-point range')
    return mu


def prepare(rows):
    data = []
    for row in sequence(rows):
        if len(sequence(row)) != 3:
            raise ValueError('row: (feature, count, positive exposure)')
        x, y, exposure = row
        x, exposure = number(x), number(exposure)
        if type(y) is not int or y < 0 or exposure <= 0:
            raise ValueError('counts are nonnegative integers; exposures are positive')
        y = number(y)
        data.append((x, y, log(exposure), lgamma(y + 1)))
    if not data or len({x for x, _, _, _ in data}) < 2:
        raise ValueError('need at least two distinct feature values')
    if not any(y > 0 for _, y, _, _ in data):
        raise ValueError('all-zero counts have no finite intercept MLE')
    return tuple(data)


def statistics(data, beta):
    # Internal helper for validated, prepared rows and two finite coefficients.
    n = len(data)
    terms = []
    for x, y, offset, log_factorial in data:
        eta = beta[0] + beta[1] * x + offset
        mu = mean(eta)
        terms.append((mu - y * eta + log_factorial,
                      mu - y, (mu - y) * x, mu, mu * x, mu * x * x))
    values = tuple(fsum(row[j] for row in terms) / n for j in range(6))
    if not all(isfinite(v) for v in values):
        raise ValueError('objective or derivative outside floating-point range')
    return values  # average loss, g0, g1, H00, H01, H11


def fit(rows, max_steps=40, tolerance=1e-9):
    data = prepare(rows)
    if type(max_steps) is not int or max_steps < 0:
        raise ValueError('max_steps must be a nonnegative integer')
    tolerance = number(tolerance)
    if tolerance <= 0:
        raise ValueError('tolerance must be positive')
    # Initial constant rate; log exposures remain fixed, with coefficient one.
    beta = (log(fsum(y for _, y, _, _ in data))
            - log(fsum(exp(o) for _, _, o, _ in data)), 0.0)
    current = statistics(data, beta)
    losses = [current[0]]
    stop = 'steps'
    for _ in range(max_steps):
        loss, g0, g1, a, b, c = current
        if max(abs(g0), abs(g1)) <= tolerance:
            stop = 'gradient'
            break
        determinant = a * c - b * b
        if not isfinite(determinant) or determinant <= 1e-12 * a * c:
            stop = 'curvature'
            break
        direction = ((c * g0 - b * g1) / determinant,
                     (a * g1 - b * g0) / determinant)
        decrease = g0 * direction[0] + g1 * direction[1]
        if not isfinite(decrease) or decrease <= 0:
            stop = 'curvature'
            break
        for j in range(20):
            step = 0.5 ** j
            trial = tuple(v - step * d for v, d in zip(beta, direction))
            try:
                candidate = statistics(data, trial)
            except (ValueError, OverflowError):
                continue
            if candidate[0] <= loss - 1e-4 * step * decrease:
                beta, current = trial, candidate
                losses.append(current[0])
                break
        else:
            stop = 'line-search'
            break
    gradient = max(abs(current[1]), abs(current[2]))
    if gradient <= tolerance:
        stop = 'gradient'
    return dict(beta=beta, loss=current[0], gradient=gradient,
                steps=len(losses)-1, stop=stop, losses=tuple(losses))


def predict(model, rows):
    # model is an unmodified fit result; no parameter update occurs here.
    result = []
    for row in sequence(rows):
        if len(sequence(row)) != 2:
            raise ValueError('prediction row: (feature, positive exposure)')
        x, exposure = map(number, row)
        if exposure <= 0:
            raise ValueError('exposure must be positive')
        result.append(mean(model['beta'][0] + model['beta'][1]*x + log(exposure)))
    return tuple(result)


if __name__ == '__main__':
    data = ((0, 2, 1), (0, 4, 2), (1, 3, 1), (1, 9, 3))
    model = fit(data)
    print('stop / accepted steps:', model['stop'], model['steps'])
    print('intercept / slope:', tuple(round(b, 6) for b in model['beta']))
    print('unit-exposure rates:', tuple(round(v, 6) for v in predict(model, ((0,1),(1,1)))))
    print('two-unit counts:', tuple(round(v, 6) for v in predict(model, ((0,2),(1,2)))))
    print('loss / maximum gradient:', round(model['loss'], 6), round(model['gradient'], 10))
    print('zero-step stop:', fit(data, max_steps=0)['stop'])

Actual output:

stop / accepted steps: gradient 4
intercept / slope: (0.693147, 0.405465)
unit-exposure rates: (2.0, 3.0)
two-unit counts: (4.0, 6.0)
loss / maximum gradient: 1.615615 0.0
zero-step stop: steps

Because x is binary in this example, the model has one independently selectable positive rate per setting. Maximizing each setting’s likelihood gives total count divided by total exposure: 6/3=2 and 12/4=3. Therefore β₀=log 2 and β₁=log(3/2), agreeing with the numeric fit. At equal exposure, exp β₁ is a rate ratio, not a probability or a causal effect.

The data were constructed for that check. Positive log-likelihood loss is compatible with fitted means equaling observed counts; a distribution can assign a non-unit probability to its own mean. Neither the fit nor its small gradient confirms that real scanner events are independent Poisson draws.

For n rows and t accepted updates, the fixed limit of 20 trial scales per attempted update gives O((t+1)n) arithmetic work and O(n+t) retained working data and loss history. A final failed attempt adds only the fixed trial limit. Prediction of m rows takes O(m+1) work and output storage, including empty input. These counts treat bounded floating-point arithmetic as unit cost. Extreme data can overflow or underflow; rejected trial means do not get silently clipped. A failed initial evaluation raises a numerical error instead of returning a fitted model.

The link cannot repair the wrong response distribution

A log link ensures positive means. It does not establish Poisson variance or independence. Counts with extra variation, bursts, omitted predictors or dependent observation windows may require a different model or uncertainty calculation. Comparing an unconditional sample variance with an unconditional mean is not by itself a test of the conditional Poisson assumption: varying fitted means can create extra marginal variation.

Exposure also encodes an assumption: expected counts scale proportionally with the known observation period at fixed x. If observation time is misrecorded, or the rate changes within it in a way the features do not capture, the offset formula may be wrong. Converting hours to minutes changes the fitted intercept by −log 60 while preserving counts when prediction exposures are converted too.

Use held-out predictive likelihood or a suitable deviance, inspect errors against fitted means and exposure, and examine whether the sampling unit matches intended use. The compact code supplies no standard errors, confidence intervals, dispersion estimate, variable selection or generic family/link engine. Its curvature threshold is a numerical safeguard, not a proof that a dataset is statistically inadmissible.

Check the units and the distribution

  1. A fitted mean is 3 events at exposure one. Is that a probability? What is the mean at exposure two, with the same feature value?

Answer: It is an expected count, which may exceed one. The model predicts 6 at twice the exposure. An individual realized count can differ from either mean.

  1. Can the same Poisson fit be obtained by taking log counts and fitting ordinary least squares? What happens to a zero count?

Answer: No. The likelihood and weighting change, and log zero is undefined. The Poisson objective accepts y=0 directly; that observation contributes μ because 0!=1 and the yη term vanishes.

  1. Why is log exposure not an ordinary fitted feature here? What changes when hours become minutes?

Answer: Its coefficient is fixed at one to express proportional exposure. Multiplying exposures by 60 requires subtracting log 60 from the intercept, with the feature slope unchanged; consistent prediction units preserve expected counts.

  1. One setting has only zero counts, while another has positive counts. Is a tiny gradient proof of a finite MLE? Does the same stopping reason validate the Poisson assumption?

Answer: No. In the two-setting model the zero-count rate approaches zero as its log rate tends to negative infinity. Finite coefficients can pass a gradient tolerance near that boundary without attaining the supremum. Distributional adequacy and independent test performance require separate evidence.

Read the general definition alongside the solver convention

The CS229 notes by Tengyu Ma and Andrew Ng, dated August 23, 2026, chapter 3, introduce the exponential-family representation and derive Gaussian and Bernoulli models through a canonical-link recipe. The present notation keeps the natural and linear parameters separate to avoid treating that recipe as the only possible GLM definition. The notes also use g for the response function; here g is the link, its inverse. Only the relevant chapter and version header were read.

The versioned statsmodels 0.14.4 documentation gives the exponential-dispersion formulation, conditional moments and family/link choices; its GLM interface specifies offset and log exposure with coefficient one. This chapter uses those definitions and an original solver. No statsmodels implementation, sample dataset or statistical-output table is copied or executed.

The tests compare the two-setting fit with analytic maximum-likelihood rates, check derivatives against a high-precision Poisson-probability calculation, and compare one update with independently constructed working-response regression. They also cover exposure-unit changes, zeros, numerical curvature rejection and stopping budgets. These are focused AI technical checks, not a claim of production solver coverage.

Make a prediction, then check

At a fixed feature value, a fitted rate is 3 events per hour. What does the exposure-offset model predict for two hours?

Choose one answer

Learning objectives

  • Separate the conditional distribution, natural parameter, linear predictor, link and inverse link.
  • Fit an original Poisson model with known exposure and connect Newton updates to working-response weighted regression.
  • Interpret rate ratios, units, numerical stopping and conditional variance without claiming a finite MLE or distributional validity from a small gradient.

Prerequisites & connections

Explore related knowledge →

References

  1. CS229 Lecture Notes — chapter 3: Generalized linear models
    Tengyu Ma and Andrew Ng · 2026
  2. statsmodels 0.14.4 — Generalized Linear Models: technical definition and model interface
    statsmodels developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Eight tests passed. Four two-setting datasets recover analytic count/exposure MLE rates; one includes zeros with positive group totals. A separate 65-digit Decimal Poisson-PMF objective verifies the loss, two gradient coordinates and all three unique Hessian entries by finite differences. One Newton step agrees with independently constructed IRLS working-response regression.
  • Checked exposure-unit conversion, repeated input, immutability, empty prediction, four update budgets and zero-update initial optimality. Exercised actual quarter-step backtracking, curvature rejection and all 20 failed line-search scales. Zero-count groups may have unattained finite-parameter optima; gradient stopping is explicitly numerical. Eleven malformed datasets, four hyperparameters, three prediction inputs and three invalid mean arguments are rejected.
  • Original scanner example returns gradient stop after four accepted steps, coefficients (0.693147, 0.405465), rates 2 and 3, two-unit means 4 and 6, and full average negative log-likelihood 1.615615. Conditional Poisson variance, no penalty on either coefficient, known offset coefficient one, unscaled inputs and fixed 20-trial line search are stated. No real scanner performance, confidence interval or generic GLM solver claim.
  • Both locales have six stable anchors, five identical display formulas, identical complete code and six output lines, and four answers. Strict MDX/KaTeX and actual React HTML passed, with identical mathematical annotations and no emphasis residue. Reread for pinned Humanizer style and notation; used dispersion wording in Chinese to avoid implying a discrete-only response. Tests load code and stdout through article_text. AI author checks only; review remains written pending independent cross-review.
  • Independent reviewer reread both full explanations, derivations, program, costs, conditional/marginal variance distinction and four answers without outstanding defects. Reran all eight author tests; matched mathematics, code, stdout and six anchors.
  • Independent reference profiles out the intercept for x=0,1,2, derives a sufficient-statistic quadratic in r=exp(slope), and solves its positive root with 70-digit Decimal. Twelve datasets check 24 coefficients and 36 interpolation/extrapolation predictions, loss descent and accepted-step counts. It uses neither Newton, IRLS nor finite differences.
  • Verified one-feature implementation, scalar common-dispersion definition, fixed exposure coefficient one, and unpenalized coefficients; small gradients do not establish finite-MLE existence. Initial numerical errors, failed trial steps, fixed 20-scale limit and floating-point costs agree with the text. This is AI technical review.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.

Source locations checked:

  • CS229 Lecture Notes — chapter 3: Generalized linear models · Actually opened the official 278-page PDF through web. Header gives Tengyu Ma, Andrew Ng and 2026-08-23. Read printed pp. 30–34, extracted lines 1695–1912: exponential-family normalizer, Bernoulli and Gaussian derivations, the dispersion footnote, the canonical linear-natural-parameter recipe, OLS/logistic specialization and the response-versus-link naming footnote. Did not adopt a universal adequacy claim for Poisson visitor counts. No whole-document, visual-PDF or implementation audit claimed.
  • statsmodels 0.14.4 — Generalized Linear Models: technical definition and model interface · Actually opened official /v0.14.4/glm.html through web. Technical section lines 219–256 gives exponential-dispersion density, mean/variance, natural parameter and link; family/link list lines 299–316 permits alternatives. Also read /v0.14.4/generated/statsmodels.genmod.generalized_linear_model.GLM.html lines 138–156, 186–189 and 223–224: intercept handling, log exposure, and offset coefficients fixed at one. Read the versioned API’s family/link table lines 251–259. No source code or package execution; scalar Poisson program and damped Newton logic are original.
  • CS229 Lecture Notes — chapter 3: Generalized linear models · Root independently read the official main_notes.pdf via web, extracted lines 1759–1845, printed pp.31–33: dispersion footnote, Gaussian representation and canonical GLM construction. This supports the stated natural-parameter/linear-predictor notation difference. No whole-PDF or visual audit claimed; date header remains separately verified in author record.
  • statsmodels 0.14.4 — Generalized Linear Models: technical definition and model interface · Root independently read fixed 0.14.4 technical documentation lines 219–240: EDM density, conditional moments and family table; same-version GLM API lines 138–156: intercept handling, offsets and log exposure. No library program/data copied or executed.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.