Generalized linear models
Build generalized linear models using exponential families, links, IRLS, deviance and overdispersion remedies.
After this lesson you can
- Choose a family and link suited to response support, variance and effect scale.
- Derive canonical likelihood equations and the IRLS Fisher scoring update.
- Interpret deviance, rates, offsets and model coefficients.
- Detect overdispersion and compare quasi-likelihood, negative binomial and sandwich methods.
Before you start
Motivation: responses that are not normal
The Gaussian linear model of the previous lesson assumes three things at once: the mean of is linear in predictors, variance is constant, and errors are normal. Many practical responses violate all three:
- Counts. The number of vulnerabilities an analyzer finds in a repository is a nonnegative integer, often zero, whose dispersion grows with its mean: a repository averaging 50 findings fluctuates far more than one averaging 2. A least-squares line predicts negative counts for small repositories and treats a 0 as equally reliable as a 50.
- Proportions and binary events. Whether a user clicks, a build fails, or what fraction of a build’s tests fail. The mean is a probability confined to , and variance depends on it: maximal at and zero at endpoints.
- Positive skewed quantities. Build times, latencies, spending per customer. They are positive, have long right tails and standard deviation often proportional to the mean: 10% variation on a 30 s build is 3 s; on a 20-minute build, two minutes.
A tempting way out is to transform the response and continue with least squares: regress or . This sometimes works but fails in essential ways. The log of a zero count does not exist; and even when it does, , so the transformed model describes a mean different from the one of interest, and one transform cannot simultaneously linearize the mean and stabilize variance.
Generalized linear models (GLMs, Nelder and Wedderburn, 1972) separate these roles. A link function makes the mean linear on a suitable scale; a distribution family governs variance and shape. Fitting uses maximum likelihood, and prior lessons’ theory (Fisher information, asymptotic normality, Wald, likelihood ratio, sandwich) applies directly. The result is one toolkit for linear, logistic, Poisson and gamma regression with one fitting algorithm.
The three ingredients
The exponential dispersion family
In lesson 7 you saw the exponential family in canonical form . GLMs use the scalar case with , adding a scale parameter. Resolve a notational conflict now: in a GLM, is reserved for the linear predictor, so the natural parameter is called (as in McCullagh and Nelder) and log-partition .
Mean and variance follow from without integration. One observation’s log-likelihood is , with score and second derivative . The two score identities from lesson 6, and , give
Since , is strictly increasing and invertible: . Variance is then a function of the mean,
the variance function. It is the family’s fingerprint: choosing a family is chiefly choosing how variance grows with mean.
| Family | Support | ||||
|---|---|---|---|---|---|
| Normal | |||||
| Binomial: success proportion in trials () | |||||
| Poisson | |||||
| Gamma with mean and shape | |||||
| Inverse Gaussian |
Check one row. Gamma with mean and shape has density , whose logarithm is . With read with , so , and . Variance : standard deviation proportional to mean, constant coefficient of variation . Exactly how build times behave.
Linear predictor and link
The Gaussian linear model is the normal case with identity . Notice what the link does not do: transform data. It transforms the mean, a deterministic number, so one never calculates . Variance is not modeled separately: the mean determines it through .
The link’s obvious job is mapping (where lives) to allowed means. Logit and probit map to ; logarithm to . Identity maps nowhere particular, a problem for a count family.
Three things the figure shows:
- Family decides band shape. Normal has constant width; Poisson grows as ; gamma as ; binomial narrows near 0 and 1. Ordinary least squares cannot reproduce these shapes.
- Link decides whether the mean is possible. With Poisson and identity link, becomes negative for small , and the model requests a negative mean, disallowed by the family: no data can be simulated there and log-likelihood is undefined. MLE sometimes exists with that link, but fitting must avoid the boundary and the model cannot extrapolate.
- Link decides the scale of additive effects. With log link, adding to the predictor multiplies the mean by : effects are multiplicative, often natural for counts and times.
The canonical link
One link is privileged among all: the one making the linear predictor equal the natural parameter.
From the column: identity for normal, logit for binomial, log for Poisson and for gamma (often used as with the sign of changed). Canonical does not mean the best model for your data; it means algebra simplifies in a precise way.
With canonical link, sample log-likelihood is
with . Data enter only through , so with known that vector of numbers is a sufficient statistic by the factorization theorem. It is the sufficient statistic of a -parameter exponential family with natural parameter .
The proof is direct (differentiate twice above) and you will do it step by step in the exercises. Its consequences are used constantly:
- Moments match. With an intercept, the first equation says : Poisson regression’s total fitted counts exactly match observed, and in logistic regression fitted probabilities sum to the number of ones. This also holds within each level of a categorical predictor.
- No spurious local optima. Any algorithm finding a zero-score point has found the global maximum.
- Observed and expected Hessians coincide, because they do not depend on . This will make two different algorithms coincide.
Existence is not guaranteed. If in logistic regression a hyperplane separates ones from zeros (complete separation), likelihood strictly increases as goes to infinity normal to that hyperplane and approaches its supremum, 1 (log-likelihood 0), without reaching it, so the MLE does not exist; Poisson has the same issue if all counts at a factor level are zero (that level’s estimated rate is 0, i.e. ). You will see this in the IRLS figure.
With a noncanonical link, score carries an extra factor (calculated next), the Hessian depends on and concavity is no longer guaranteed. That does not make such links worse: probit, log-binomial, gamma with log link or Poisson with identity link are legitimate when effect scale calls for them.
IRLS: fitting as repeated weighted least squares
Except for normal with identity, likelihood equations are nonlinear in and must be solved iteratively. Lesson 5’s numerical MLE used Newton; here Fisher scoring (Newton with Hessian replaced by negative expected information) has an especially elegant GLM form: each step is weighted linear regression.
The derivation fits in six lines: calculate score, then the Fisher information matrix, then rearrange the scoring step. Write and define diagonal matrices
The second claim is the last consequence of the previous theorem: with canonical link, observed Hessian does not depend on and therefore equals its expectation, . Newton and scoring produce exactly the same iterates. You will reconstruct this in a guided exercise.
In logistic regression, , so and . Points with near 0 or 1, already confidently classified, receive little weight; points near the boundary dominate each regression.
What you should have seen:
- From , the first step is ordinary least squares. All means are , weights , and . The first boundary comes from linear regression of on , already pointing the right way.
- Quadratic convergence. With overlapping classes, IRLS brings score below in 4 steps, and the number of correct digits doubles in each final step: Newton’s hallmark. Gradient descent needs hundreds of iterations with the largest tolerable step and thousands with small steps; increase it further and convergence becomes oscillation. It converges linearly, at a rate dependent on Hessian condition number; here predictors are correlated () and uncentered, typical of real data. IRLS is immune: weighted regression exactly solves any linear reparameterization of .
- Separation. With separable data deviance approaches 0, coefficients grow without bound, and all point weights vanish because all are eventually classified with probability near 1. IRLS does not “fail”: it correctly pursues an unattained supremum. Beware stopping criteria: score and deviance also approach 0, so software watching only one declares convergence. In practice the symptom is huge coefficients with even larger standard errors and, at best, a warning of separation or fitted probabilities equal to 0 or 1.
Two implementation details. No initial is needed: initial means making finite suffice, such as for Poisson or for binomial (used by statsmodels). With noncanonical links a step can worsen likelihood or leave the domain (negative Poisson mean with identity); hence R’s glm halves the step while deviance is nonfinite or means leave the domain, and glm2 also halves while deviance rises.
Deviance
In the linear model, residual sum of squares measures lack of fit and differences compare nested models. Its GLM generalization is deviance, comparing your model with the best imaginable fit: one parameter per observation.
The integral formula follows in one line: , so is the integral of from to . Since the integrand has the sign of , with equality only if . Unit deviances of the four main families are:
| Family | |
|---|---|
| Normal | |
| Binomial (proportion) | |
| Poisson | |
| Gamma |
with convention . For normal, is residual sum of squares and . For Poisson with intercept, sums to zero by moment matching, leaving the familiar .
Compare nested models. If have parameters and fit the same data with the same family, saturated terms cancel:
This is the likelihood-ratio test statistic; by Wilks’s theorem, under it is approximately . In Poisson and binomial and deviance difference is directly compared to . If is unknown (normal, gamma, or quasi-likelihood), estimate it with the larger model and use
which in the normal case is exactly the nested-model F test. is the generalized Pearson statistic. A sequence of these comparisons, adding terms one at a time, is an analysis of deviance, analogous to ANOVA.
Goodness of fit, with care. Comparing with to judge fit is tempting. The approximation only holds in the small-dispersion regime: large Poisson counts or binomials with large , so each is approximately normal. When grows with fixed it fails because the saturated model gains one parameter per observation and Wilks does not apply. The extreme is binary data (): for logistic regression, likelihood equations give , a function of fitted values that does not depend on beyond what the fit already contains. It says nothing about goodness of fit.
Inference and residuals
Everything you know about MLE applies. By MLE asymptotic normality,
with the final IRLS weight: the covariance matrix comes free from the algorithm. Three inference tools:
- Wald. The Wald test and interval appear in every coefficient table.
- Likelihood ratio. The previous section’s deviance difference. For one coefficient, compare the model with and without it.
- Profile intervals. The profile-likelihood interval inverts the likelihood ratio: , where minimizes deviance over other coefficients. It is invariant under monotone transformations (the interval for rate ratio is the exponential of that for , without new approximations) and respects likelihood skewness.
All three agree asymptotically and are barely distinguishable for large samples and moderate effects (in the laboratory below, versus likelihood ratio ). They diverge for small samples, low counts or extreme probabilities, where Wald is least reliable. Logistic regression also has the Hauck–Donner effect (1977): for very large effects, standard error grows faster than the coefficient and Wald statistic decreases as it moves away from null, potentially failing to reject nearly separated data. Likelihood ratio and profile avoid this problem.
Residuals. Raw GLM residuals are not comparable because each observation has its own variance. Two standardized versions are:
Pearson and deviance residuals, with and . To compare with standard normal divide by , where is the hat-matrix diagonal of the last weighted regression, . Deviance residuals tend to be closer to normal for skewed families (low-mean Poisson, gamma), because the square root of deviance corrects some skewness.
For discrete responses and small means no residual is normal: in binary logistic regression, residuals versus form two curved bands, one for each , and reveal nothing by eye. Alternatives are grouping (compare observed and fitted proportions in bins) or Dunn–Smyth randomized quantile residuals (1996), exactly standard normal under the correct model evaluated at true parameters (approximately so with estimates).
Interpreting coefficients: odds, rates and exposure
A GLM coefficient is additive on the link scale. What that means on the mean scale depends on the link.
Log link (Poisson, gamma, negative binomial). If increases one unit holding others fixed,
Effects are multiplicative and is a rate ratio, or for times, a mean ratio. A coefficient for a binary variable means the group with has mean times larger: 35% more, not 30%. For small coefficients, and “ %” is approximately right; for it is misleading ().
Logit link. Now is the change in log odds, , and is an odds ratio. Its probability effect is not constant:
maximal in absolute value at and negligible near 0 or 1. Bound (the “divide by four” rule) gives the largest possible probability change per unit of . For rare events, small , odds approximate and odds ratio approximates risk ratio; otherwise they can differ greatly. Probit coefficients are read on a latent-normal scale and are approximately logit coefficients divided by 1.6.
Rates and exposure: the offset
Counts often depend on how much was observed. A service monitored 2000 hours accumulates more incidents than one monitored 200 even if both are equally fragile. Model the rate per exposure unit, with and known exposure (hours, users, lines of code, person-years). With log link,
Term enters the linear predictor with fixed coefficient 1: an offset. Rate models with exposure offsets use the same IRLS, subtracting the offset from working response () and adding it back when recalculating . Coefficients are log rate ratios.
Forgetting the offset is not harmless. If exposure correlates with a predictor, that predictor absorbs exposure differences. In the laboratory below, critical services are monitored about 2.5 times as many hours; without offset, estimated rate ratio for “critical” is when truth is : more exposure is confused with more risk. Including as a covariate with free coefficient is valid if proportionality is uncertain; including without log is not.
Overdispersion
Poisson and binomial have no free dispersion parameter: and the mean fixes variance. Real data rarely obey this.
The usual cause is unobserved heterogeneity. If each repository has its own rate, , and rates vary around the model mean with and , total variance gives
If is gamma, marginal is exactly negative binomial. In binomial data, positive correlation within each group of trials (tests in one build failing together) gives group success-count variance instead of : model with when groups share .
What fails and what does not. Estimating equations involve only the mean; if the mean model is correct their expectation is zero even under another variance, and remains consistent: an M-estimator with unbiased equations. Uncertainty fails: actual covariance is approximately times model covariance, standard errors are too small by , statistics too large and intervals too narrow. With , a nominal 95% interval covers about 74%. This is a classic source of false discoveries.
Detection. Ratio (or if counts are not small) should be near 1; values 2 or 3 clearly indicate overdispersion. Before blaming variance, rule out a wrong mean model (missing predictor, nonlinearity, unsuitable link), which also inflates the ratio.
The figure summarizes diagnosis: with everything works and ; increasing widens the histogram while keeping it centered at , Poisson’s promised normal stays narrow and its coverage falls far below 95%, while the other three remain near it. Three standard remedies follow.
1. Quasi-likelihood. Wedderburn (1974) observed that IRLS uses only mean and variance function, never the complete distribution. If we specify only
the quasi-score satisfies both score properties needed for asymptotic theory: zero expectation and . It derives from quasi-likelihood , behaving like log-likelihood without corresponding to a distribution. In practice quasi-Poisson gives Poisson’s same , estimates , multiplies standard errors by and compares models using the deviance section’s test. Use when variance is proportional to mean.
2. Negative binomial. Models and estimates by maximum likelihood. With fixed it is a GLM (own variance function), fitted with IRLS alternating with estimation of . Its log-link weights give high-mean observations relatively less weight than Poisson, so differs somewhat. Use when variance grows quadratically with mean (plot versus ). Testing by likelihood ratio has a nuance: null is on the parameter boundary, and null distribution is a 50% mixture of mass at 0 and , so p-value is half the value.
3. Sandwich errors. The sandwich variance from lesson 8,
assumes nothing about variance: only correct mean specification and independent observations (or independent groups in its clustered version). It is a safety net when no variance model is trustworthy. Its price: no improvement in (still Poisson, inefficient if actual variance differs), noisier variance estimate and downward bias in small samples: with the figure shows some undercoverage, motivating HC1–HC3 corrections.
Excess zeros. A common case: more zeros than the model permits because a subpopulation never produces events (archived repositories, services without traffic). Detect by comparing observed zeros with expected for Poisson. Negative binomial often explains them already, since a highly dispersed gamma mean places much mass near zero; otherwise use zero-inflated models (mixture of structural zero and count) or hurdle models (a binary model for “zero or not” and a truncated model for positives).
Implementation from scratch
Generic IRLS needs, for each link, , and , and for each family, , unit deviance and initial means. Everything else is the previous section’s iteration.
import numpy as np
from scipy import special, stats
class Enlace:
def __init__(self, nombre, g, ginv, dmu):
self.nombre, self.g, self.ginv, self.dmu = nombre, g, ginv, dmu # dmu(eta) = dmu/deta
identidad = Enlace("identidad", lambda m: m, lambda e: e, lambda e: np.ones_like(e))
logit = Enlace("logit", special.logit, special.expit, lambda e: special.expit(e) * special.expit(-e))
probit = Enlace("probit", special.ndtri, special.ndtr, lambda e: np.exp(-e**2 / 2) / np.sqrt(2 * np.pi))
log = Enlace("log", np.log, np.exp, np.exp)
inversa = Enlace("inversa", lambda m: 1 / m, lambda e: 1 / e, lambda e: -1 / e**2)
def ylogy(y, mu):
"""y log(y / mu), con 0 log 0 = 0."""
return special.xlogy(y, y) - special.xlogy(y, mu)
class Familia:
def __init__(self, nombre, V, d, mu0, canonico, phi_fija):
self.nombre, self.V, self.d, self.mu0 = nombre, V, d, mu0
self.canonico, self.phi_fija = canonico, phi_fija
binomial = Familia("binomial", lambda m: m * (1 - m),
lambda y, m: 2 * (ylogy(y, m) + ylogy(1 - y, 1 - m)),
lambda y: (y + 0.5) / 2, logit, True)
poisson = Familia("Poisson", lambda m: m,
lambda y, m: 2 * (ylogy(y, m) - (y - m)),
lambda y: (y + y.mean()) / 2, log, True)
gamma = Familia("gamma", lambda m: m**2,
lambda y, m: 2 * (-np.log(y / m) + (y - m) / m),
lambda y: (y + y.mean()) / 2, inversa, False)
def ajustar_glm(X, y, familia, enlace=None, pesos=None, offset=None, tol=1e-10, max_iter=50):
"""IRLS: scoring de Fisher escrito como mínimos cuadrados ponderados."""
enlace = enlace or familia.canonico
n, p = X.shape
w0 = np.ones(n) if pesos is None else np.asarray(pesos, float) # pesos a priori (m_i en la binomial)
off = np.zeros(n) if offset is None else np.asarray(offset, float)
mu = familia.mu0(y)
eta = enlace.g(mu)
dev = np.inf
for it in range(1, max_iter + 1):
dmu = enlace.dmu(eta)
z = eta - off + (y - mu) / dmu # respuesta de trabajo (sin el offset)
W = w0 * dmu**2 / familia.V(mu) # pesos de trabajo
XtW = X.T * W
beta = np.linalg.solve(XtW @ X, XtW @ z) # ecuaciones normales ponderadas
eta = X @ beta + off
mu = enlace.ginv(eta)
dev_nueva = np.sum(w0 * familia.d(y, mu))
hecho = abs(dev_nueva - dev) < tol * (abs(dev_nueva) + 0.1)
dev = dev_nueva
if hecho:
break
dmu = enlace.dmu(eta)
W = w0 * dmu**2 / familia.V(mu)
pearson = np.sum(w0 * (y - mu)**2 / familia.V(mu))
phi = 1.0 if familia.phi_fija else pearson / (n - p)
cov = phi * np.linalg.inv((X.T * W) @ X)
return dict(beta=beta, se=np.sqrt(np.diag(cov)), mu=mu, desviacion=dev,
pearson=pearson, phi=phi, iter=it, gl=n - p)
# vulnerabilidades por repositorio (datos sintéticos)
rng = np.random.default_rng(20)
n = 500
kloc = np.exp(rng.normal(3.0, 1.0, n)) # miles de líneas de código
deps = rng.poisson(40, n) # dependencias directas
ci = rng.binomial(1, 0.6, n) # análisis estático en la integración continua
X = np.column_stack([np.ones(n), np.log(kloc), deps / 10, ci])
nombres = ["intercepto", "log kLOC", "deps/10", "CI"]
y = rng.poisson(np.exp(X @ np.array([-2.0, 0.6, 0.15, -0.5])))
propio = ajustar_glm(X, y, poisson)
import statsmodels.api as sm
ref = sm.GLM(y, X, family=sm.families.Poisson()).fit()
print(f"{'':12s}{'propio':>10s}{'statsmodels':>13s}{'EE propio':>11s}{'EE sm':>9s}")
for j, nm in enumerate(nombres):
print(f"{nm:12s}{propio['beta'][j]:10.5f}{ref.params[j]:13.5f}{propio['se'][j]:11.5f}{ref.bse[j]:9.5f}")
print(f"desviación: {propio['desviacion']:.4f} (sm {ref.deviance:.4f}) con {propio['gl']} gl; iteraciones IRLS: {propio['iter']}")
print("máx |Δβ| frente a statsmodels:", np.max(np.abs(propio['beta'] - ref.params)))
# Wald y razón de verosimilitudes para el coeficiente de CI
sin_ci = ajustar_glm(X[:, :3], y, poisson)
rv = sin_ci['desviacion'] - propio['desviacion']
zw = propio['beta'][3] / propio['se'][3]
print(f"\nCI: Wald z² = {zw**2:.2f} (p = {stats.chi2.sf(zw**2, 1):.2e}); "
f"RV = D0 - D1 = {rv:.2f} (p = {stats.chi2.sf(rv, 1):.2e})")
b, s = propio['beta'][3], propio['se'][3]
print(f"razón de tasas de CI: {np.exp(b):.3f}, IC 95 % de Wald [{np.exp(b - 1.96 * s):.3f}, {np.exp(b + 1.96 * s):.3f}]")The custom fit agrees with statsmodels to rounding error in five iterations, and standard errors follow from with no extra work. Deviance 506 on 496 degrees of freedom does not indicate overdispersion: data were generated from Poisson. Continuous integration’s effect is rate ratio : repositories with static analysis in CI have 38.5% fewer vulnerabilities at the same size and dependency count. The interval is constructed on the scale and exponentiated afterward, hence asymmetric around .
Now noncanonical links and gamma. The fraction of failed tests per build is modeled with binomial and weights (number of tests run); build times with gamma. Finally, distance from MLE at each iteration shows quadratic convergence.
import warnings
# 1) proporción de tests fallidos por build: binomial con m_i ensayos, logit (canónico) y probit
rng = np.random.default_rng(3)
nb = 300
cambios = rng.gamma(2.0, 150, nb) # líneas cambiadas en el commit
nocturno = rng.binomial(1, 0.3, nb)
m = rng.integers(50, 400, nb) # tests ejecutados en cada build
Xb = np.column_stack([np.ones(nb), np.log(cambios), nocturno])
fallos = rng.binomial(m, special.ndtr(Xb @ np.array([-3.2, 0.25, 0.3])))
yb = fallos / m
for enl, link_sm in [(logit, sm.families.links.Logit()), (probit, sm.families.links.Probit())]:
f = ajustar_glm(Xb, yb, binomial, enl, pesos=m)
r = sm.GLM(np.column_stack([fallos, m - fallos]), Xb, family=sm.families.Binomial(link=link_sm)).fit()
print(f"binomial-{enl.nombre:7s} β = {np.round(f['beta'], 4)} D = {f['desviacion']:.3f} "
f"(sm {r.deviance:.3f}) |Δβ| = {np.max(np.abs(f['beta'] - r.params)):.1e} iter = {f['iter']}")
# 2) tiempos de compilación (forma 4, φ = 0.25): gamma con enlace log y con el canónico
nc = 250
modulos = rng.integers(1, 60, nc)
cache = rng.binomial(1, 0.5, nc)
Xc = np.column_stack([np.ones(nc), np.log(modulos), cache])
tiempos = rng.gamma(4.0, np.exp(Xc @ np.array([1.0, 0.8, -0.6])) / 4.0)
for enl, link_sm in [(log, sm.families.links.Log()), (inversa, sm.families.links.InversePower())]:
f = ajustar_glm(Xc, tiempos, gamma, enl)
with warnings.catch_warnings():
warnings.simplefilter("ignore") # statsmodels avisa: 1/mu no garantiza medias positivas
r = sm.GLM(tiempos, Xc, family=sm.families.Gamma(link=link_sm)).fit(scale="X2")
print(f"gamma-{enl.nombre:8s} β = {np.round(f['beta'], 4)} φ̂ = {f['phi']:.4f} (sm {r.scale:.4f}) "
f"EE = {np.round(f['se'], 4)} (sm {np.round(r.bse, 4)})")
# 3) convergencia cuadrática: distancia al EMV en cada iteración (logística de los builds)
beta_hat = ajustar_glm(Xb, yb, binomial, logit, pesos=m, tol=0)["beta"]
mu = binomial.mu0(yb)
eta = logit.g(mu)
for it in range(1, 7):
dmu = logit.dmu(eta)
W = m * dmu**2 / binomial.V(mu)
z = eta + (yb - mu) / dmu
beta = np.linalg.solve((Xb.T * W) @ Xb, (Xb.T * W) @ z)
eta = Xb @ beta
mu = logit.ginv(eta)
print(f"iteración {it}: ‖β - β̂‖ = {np.linalg.norm(beta - beta_hat):.2e}")Three observations. Build data were generated with probit, yet logit has lower deviance (326.8 versus 332.1): with 300 builds the links are nearly indistinguishable and such a difference cannot select one. Logit coefficients are 2 to 2.2 times probit, not 1.6: the 1.6 rule holds for intermediate probabilities, while failure rates here are a few percent, where the logistic tail is heavier than normal and the ratio of link slopes (normal density at divided by ) rises from 1.6 at to 2.2 at . For gamma, log link (true) estimates , nearly the used to simulate data; canonical link, misspecified for these data, leaves more variability unexplained and its rises to . The final trace shows textbook quadratic convergence: , , ; each error is of order the previous error squared.
With libraries: incident rates with exposure
In statsmodels, a GLM is sm.GLM(y, X, family=...) or, with formulas, smf.glm("y ~ a + b", datos, family=...). Important options:
| Item | statsmodels |
|---|---|
| Family and link | sm.families.Poisson(), Binomial(link=sm.families.links.Probit()), Gamma(link=sm.families.links.Log()) |
| Binomial with trials | two-column response [éxitos, fracasos], or proportion with var_weights=m |
| Exposure | offset=np.log(t) (or exposure=t, which takes the log) |
| Quasi-likelihood | .fit(scale="X2"): |
| Sandwich errors | .fit(cov_type="HC0") (or "HC1", or "cluster" with groups) |
| Negative binomial with estimated | smf.negativebinomial(...) (discrete model, joint MLE) |
| Deviance, Pearson, residuals | res.deviance, res.pearson_chi2, res.resid_deviance, res.resid_pearson |
The laboratory simulates security incidents in 300 services with two risk factors (criticality and internet exposure), monitoring hours depending on criticality, and unobserved heterogeneity with .
import pandas as pd
import statsmodels.formula.api as smf
rng = np.random.default_rng(7)
n = 300
critico = rng.binomial(1, 0.35, n)
internet = rng.binomial(1, 0.5, n)
horas = np.round(rng.uniform(200, 2000, n) * (1 + 1.5 * critico)) # los críticos se vigilan más horas
tasa = np.exp(0.2 + 0.4 * critico + 0.7 * internet) # incidentes por 1000 horas
alpha = 0.6 # heterogeneidad no observada
y = rng.poisson(horas / 1000 * tasa * rng.gamma(1 / alpha, alpha, n))
df = pd.DataFrame(dict(incidentes=y, critico=critico, internet=internet, horas=horas))
expo = np.log(df.horas / 1000)
form = "incidentes ~ critico + internet"
pois = smf.glm(form, df, family=sm.families.Poisson(), offset=expo).fit()
sin_off = smf.glm(form, df, family=sm.families.Poisson()).fit()
print("razones de tasas (verdad: crítico 1.49, internet 2.01)")
print(" con offset:", np.round(np.exp(pois.params[1:]).values, 3))
print(" sin offset:", np.round(np.exp(sin_off.params[1:]).values, 3))
print(f"\nPearson/gl = {pois.pearson_chi2 / pois.df_resid:.2f} D/gl = {pois.deviance / pois.df_resid:.2f}")
quasi = smf.glm(form, df, family=sm.families.Poisson(), offset=expo).fit(scale="X2")
sand = smf.glm(form, df, family=sm.families.Poisson(), offset=expo).fit(cov_type="HC0")
nbm = smf.negativebinomial(form, df, offset=expo).fit(disp=0)
print(f"α̂ de la binomial negativa (EMV): {nbm.params['alpha']:.3f} (verdad {alpha})")
print(f"\n{'':18s}{'β internet':>11s}{'EE':>8s}{'IC 95 % de la razón de tasas':>32s}")
for nombre, r in [("Poisson", pois), ("cuasi-Poisson", quasi), ("sándwich (HC0)", sand), ("binomial negativa", nbm)]:
b, s = r.params["internet"], r.bse["internet"]
print(f"{nombre:18s}{b:11.4f}{s:8.4f} [{np.exp(b - 1.96 * s):.3f}, {np.exp(b + 1.96 * s):.3f}]")
# ceros observados frente a esperados
mu_p = pois.fittedvalues
mu_nb = nbm.predict(df, offset=expo)
a = nbm.params["alpha"]
print(f"\nceros: observados {np.sum(y == 0)}, esperados Poisson {np.sum(np.exp(-mu_p)):.1f}, "
f"binomial negativa {np.sum((1 + a * mu_nb) ** (-1 / a)):.1f}")
# razón de verosimilitudes para α = 0 (en la frontera: mitad de una χ²₁)
rv = 2 * (nbm.llf - pois.llf)
print(f"RV de α = 0: {rv:.1f}, p = {0.5 * stats.chi2.sf(rv, 1):.1e}")The output tells the entire overdispersion section with data:
- Offset matters. With it, rate ratios ( and ) are near truth; without, the “critical” ratio jumps to because it absorbs extra monitoring hours.
- Clear overdispersion. , and negative binomial estimates , near the true . The test of is overwhelming.
- Poisson standard errors are half what they should be. For “internet,” versus (quasi), (sandwich) and (negative binomial). Poisson’s rate-ratio interval, , is misleadingly narrow. All three remedies agree in order of magnitude; negative binomial also changes the point estimate ( versus ) because it weights differently.
- Zeros reveal the problem. Poisson expects 51 incident-free services and there are 80; negative binomial expects 80.4. No zero-inflated model is needed: heterogeneity explains them.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. What is the gradient of with respect to ?
Step 1 of 4. What is Fisher information ?
desviacion(y, mu, familia, m=None) to return total deviance , and residuos_desviacion(y, mu, familia, m=None) to return vector . familia is 'poisson' or 'binomial'; for binomial, y is success proportion and m the number of trials (if None, ). Ignore m for Poisson. Use convention : with or no nan should appear.import numpy as np
def desviacion(y, mu, familia, m=None):
"""Desviación total para 'poisson' o 'binomial' (y = proporción, m = ensayos)."""
y = np.asarray(y, dtype=float)
mu = np.asarray(mu, dtype=float)
# tu código: desviación unidad d(y, mu) de cada familia, ponderada por m
return 0.0
def residuos_desviacion(y, mu, familia, m=None):
"""sign(y - mu) * sqrt(m * d(y, mu))."""
y = np.asarray(y, dtype=float)
return np.zeros_like(y)Summary
- Ingredients. Response from an exponential dispersion family (, ), linear predictor and link . Normal, binomial, Poisson and gamma have , , and .
- Canonical link. : sufficient statistic is , likelihood equations are and log-likelihood is concave. MLE may not exist (separation).
- IRLS. Fisher scoring rewritten as weighted least squares of with weights ; with canonical link it is Newton and converges quadratically. Asymptotic covariance is .
- Deviance. ; differences between nested models are likelihood ratios (, or with estimated ). Absolute value measures fit only with small dispersion, never binary data.
- Interpretation. With log link, is a rate ratio; with logit, an odds ratio, and probability effect is bounded by . Rates with exposure use as offset.
- Overdispersion. Coefficients remain consistent, but Poisson or binomial standard errors are too small by . Detect with and correct using quasi-likelihood, negative binomial or sandwich errors.