Algorithm Search⌘K

Techniqueadvanced

Generalized estimating equations

Also called GEE, Liang-Zeger estimating equations.

Liang and Zeger's method for correlated responses: solve GLM-type score equations with a working correlation, and use the sandwich for valid standard errors.

Generalized estimating equations fit a regression model for the mean of correlated responses, such as repeated measures on the same person or pupils in the same school. The data come in GG independent clusters, and the model specifies only the marginal mean Eyij=μij=g−1(xij⊤b)E y_{ij} = \mu_{ij} = g^{-1}(x_{ij}^\top b) and a variance function, as in quasi-likelihood. The correlation inside a cluster is replaced by a working guess R(α)R(\alpha). Liang and Zeger (1986) showed that the estimate is consistent even when the guess is wrong, as long as the mean model is right, and that the sandwich covariance B−1MB−1B^{-1}MB^{-1} gives valid standard errors as the number of clusters grows. A good guess only makes the estimate more precise. With the independence guess the estimate is the ordinary generalized linear model fit, and the sandwich is the cluster-robust covariance.

In plain words

When the same patient is measured many times, the measurements are related, so they carry less information than the same number of measurements from different patients. Ordinary regression ignores this and reports too much certainty. This method fits the usual kind of regression line for the average response, but it also takes a guess at how measurements in the same group are related. The guess decides how much weight each measurement gets. If the guess is good, the estimate is more precise. If it is bad, the estimate is still right on average for many groups. The uncertainty is then measured from how much the groups really differ from each other, not from the guess, so it stays honest either way.

When it applies

  • Clustered data. Clusters i=1,…,Gi = 1, \dots, G are independent, with mim_i responses yi=(yi1,…,yimi)y_i = (y_{i1}, \dots, y_{im_i}) and an mi×pm_i \times p matrix XiX_i of covariates. Responses inside a cluster may be correlated in any way.
  • A marginal mean model. E[yij∣Xi]=μij=g−1(xij⊤b)E[y_{ij} \mid X_i] = \mu_{ij} = g^{-1}(x_{ij}^\top b), with a link gg and Var⁡yij=ϕV(μij)\operatorname{Var}y_{ij} = \phi V(\mu_{ij}) for a variance function VV. The coefficients describe the population average, not a single cluster.
  • The estimating equations. With Di=∂μi/∂bD_i = \partial\mu_i/\partial b (mi×pm_i \times p), Si=diag⁡(V(μij))S_i = \operatorname{diag}(\sqrt{V(\mu_{ij})}) and the working covariance Vi=ϕSiR(α)SiV_i = \phi S_iR(\alpha)S_i,
U(b)=∑i=1GDi⊤Vi−1(yi−μi)=0.U(b) = \sum_{i=1}^GD_i^\top V_i^{-1}(y_i - \mu_i) = 0.
  • Why a wrong guess does not bias it. For any fixed α\alpha, DiD_i and ViV_i depend on XiX_i and bb only, so E[Di⊤Vi−1(yi−μi)∣Xi]=Di⊤Vi−1E[yi−μi∣Xi]=0E[D_i^\top V_i^{-1}(y_i - \mu_i) \mid X_i] = D_i^\top V_i^{-1}E[y_i - \mu_i \mid X_i] = 0 at the true bb. This is exact, and it is the reason for consistency. It needs the mean of yijy_{ij} given all of XiX_i, not only given xijx_{ij}, to follow the model; Pepe and Anderson (1994) showed that this can fail with time-varying covariates.
  • Many clusters. The asymptotic theory lets G→∞G \to \infty with bounded mim_i. The working correlation must have a parameter α\alpha that can be estimated at rate G\sqrt G; any moment estimate below qualifies.

The template

  1. GEE((X_1, y_1), ..., (X_G, y_G))
  2. 1choose LINK g, VARIANCE-FUNCTION V, WORKING-CORRELATION R(α) ▷ holes
  3. 2b ← START ▷ hole: 0, or the independence fit
  4. 3repeat
  5. 4(φ̂, α̂) ← MOMENTS of the Pearson residuals rᵢⱼ = (yᵢⱼ - μᵢⱼ) / √V(μᵢⱼ)
  6. 5for each cluster i: μᵢ, Dᵢ = ∂μᵢ/∂b, Vᵢ = Sᵢ R(α̂) Sᵢ
  7. 6b ← b + (Σᵢ DᵢᵀVᵢ⁻¹Dᵢ)⁻¹ Σᵢ DᵢᵀVᵢ⁻¹(yᵢ - μᵢ) ▷ a Fisher scoring step
  8. 7until the step is small
  9. 8return b, B⁻¹MB⁻¹ with B = Σᵢ DᵢᵀVᵢ⁻¹Dᵢ, M = Σᵢ DᵢᵀVᵢ⁻¹(yᵢ - μᵢ)(yᵢ - μᵢ)ᵀVᵢ⁻¹Dᵢ

The holes are the mean and variance model and the working correlation (line L1) and the start (line L2). Common working correlations are independence (R=IR = I), exchangeable (Rjk=αR_{jk} = \alpha for j≠kj \ne k) and first-order autoregressive (Rjk=α∣j−k∣R_{jk} = \alpha^{|j-k|}). The implementation estimates ϕ\phi by ∑rij2/(N−p)\sum r_{ij}^2/(N - p), with N=∑miN = \sum m_i, and α\alpha by the mean of rijrikr_{ij}r_{ik} over the pairs of the structure divided by ϕ^\hat\phi; it keeps α\alpha inside the range where RR is positive definite. Since ϕ\phi cancels from line L6, the update needs ViV_i only up to the factor ϕ\phi, and ϕ\phi enters only the model-based covariance ϕ^(∑iDi⊤(SiRSi)−1Di)−1\hat\phi(\sum_iD_i^\top(S_iRS_i)^{-1}D_i)^{-1}, which is valid only if RR is right. One step costs Θ(∑i(mi3+mi2p+mip2)+p3)\Theta(\sum_i(m_i^3 + m_i^2p + m_ip^2) + p^3).

What is proved and what is cited. The page and the tests show four exact facts. With R=IR = I, Di⊤Vi−1(yi−μi)=∑jxijdμijdηyij−μijϕV(μij)D_i^\top V_i^{-1}(y_i - \mu_i) = \sum_jx_{ij}\frac{d\mu_{ij}}{d\eta}\frac{y_{ij} - \mu_{ij}}{\phi V(\mu_{ij})}, which is the generalized linear model score, so the fit is the GLM fit. For the identity link with V=1V = 1 and a fixed α\alpha, the equations are ∑iXi⊤R−1(yi−Xib)=0\sum_iX_i^\top R^{-1}(y_i - X_ib) = 0, the normal equations of generalized least squares with a block diagonal covariance, and line L6 reaches them in one step. With R=IR = I and the identity link, B−1MB−1=(X⊤X)−1(∑iXi⊤eiei⊤Xi)(X⊤X)−1B^{-1}MB^{-1} = (X^\top X)^{-1}\big(\sum_iX_i^\top e_ie_i^\top X_i\big)(X^\top X)^{-1}, the CR0 cluster-robust covariance. And the estimating function has mean zero for every working correlation, shown above. The following are cited from Liang and Zeger (1986): if the mean model is right and α^\hat\alpha and ϕ^\hat\phi are G\sqrt G-consistent, then b^\hat b is consistent and G(b^−b)\sqrt G(\hat b - b) is asymptotically normal with a covariance consistently estimated by GG times line L8, whatever RR is; and if RR is right, the estimate is efficient among estimates of this form. These are results for G→∞G \to \infty, and the coverage at a given GG is only measured.

Classic examples

The independence fit is the GLM fit. The page example of the cluster-robust standard errors has x=1,…,6x = 1, \dots, 6, y=(2,3,2,4,7,8)y = (2, 3, 2, 4, 7, 8) and the clusters {1,2}\{1, 2\}, {3,4}\{3, 4\}, {5,6}\{5, 6\}, with an intercept. With the identity link and V=1V = 1:

working correlation b^\hat b slope SE, sandwich slope SE, model-based
independence (−1/15,44/35)(-1/15, 44/35) 0.2171 0.2848
exchangeable, α=1/2\alpha = 1/2 fixed (−13/123,52/41)(-13/123, 52/41) 0.1953
exchangeable, α^=0.587\hat\alpha = 0.587 (−0.1189,1.2721)(-0.1189, 1.2721) 0.1903 0.3218

The independence row is least squares, ϕ^=149/105\hat\phi = 149/105 is the residual mean square, and the sandwich SE 0.2171 is the CR0 value on the cluster-robust page; the tests check these in exact arithmetic. The fixed-α\alpha row equals generalized least squares with the block diagonal covariance, also exactly. With only 3 clusters none of these standard errors can be trusted, which is the point of the next example.

Random intercept data, measured. Take G=30G = 30 clusters of 4, yij=1+0.5xi+0.5wij+ai+εijy_{ij} = 1 + 0.5x_i + 0.5w_{ij} + a_i + \varepsilon_{ij} with aia_i and εij\varepsilon_{ij} independent N(0,1)N(0, 1), so that the true correlation is exchangeable with α=0.5\alpha = 0.5, a cluster-level covariate xix_i and a covariate wijw_{ij} that varies inside clusters. Over 1000 data sets, the coverage of 95% Wald intervals was:

interval slope of xix_i slope of wijw_{ij}
independence, model-based 0.777 0.943
independence, sandwich 0.921 0.928
exchangeable, sandwich 0.921 0.916
exchangeable, model-based 0.929 0.949

The standard deviation of the estimate of the ww slope was 0.1317 with the independence correlation and 0.1055 with the exchangeable one, a variance ratio of 0.64. So the right working correlation pays for covariates that vary inside clusters, and the ordinary model-based errors are far too small for covariates that are constant inside clusters. The sandwich covers a little below 0.95 with 30 clusters; the Monte Carlo standard error of each coverage is about 0.007. This is the same model as a linear mixed model with a random intercept, whose marginal covariance is exchangeable.

Overdispersed counts. With G=40G = 40 clusters of 4 Poisson counts whose means share a gamma-distributed cluster factor with mean 1 and shape 2, the marginal mean is still exp⁡(xij⊤b)\exp(x_{ij}^\top b). The log link with V(μ)=μV(\mu) = \mu and an exchangeable working correlation converged in all 500 data sets, with a mean α^\hat\alpha of 0.484. The coverage for the cluster-level slope was 0.770 for the independence model-based interval and 0.928 for both sandwich intervals; for the within-cluster slope it was 0.948, 0.918 and 0.924.

Binary responses. With the logit link and V(μ)=μ(1−μ)V(\mu) = \mu(1 - \mu), the coefficients are population-averaged log odds ratios, as in logistic regression. They differ from the cluster-specific coefficients of a random-effects logistic model, which are larger in absolute value; neither is wrong, they answer different questions.

Missing responses. If some yijy_{ij} are missing, the unweighted equations stay unbiased only when the responses are missing completely at random. Under missing at random, weighting each term by the inverse of the probability of being observed, as in inverse probability weighting, restores consistency (Robins, Rotnitzky and Zhao, 1995); see the missing data mechanism page for the definitions.

Variations

  • Choice of working correlation. Use independence, exchangeable, AR(1) for equally spaced times, or an unstructured matrix when clusters are small and many. Pan (2001) proposed QIC, a quasi-likelihood analogue of AIC, to compare working correlations, and QICu to compare mean models.
  • Small-sample corrections. Mancl and DeRouen (2001) replace yi−μiy_i - \mu_i in MM by (I−Hii)−1(yi−μi)(I - H_{ii})^{-1}(y_i - \mu_i), where HiiH_{ii} is the cluster block of a leverage matrix, which removes most of the downward bias of the sandwich with few clusters. Using tt quantiles with G−pG - p or G−1G - 1 degrees of freedom also helps, as for cluster-robust standard errors.
  • Weighted equations for missing data. Inverse probability weights inside UU handle responses missing at random (Robins, Rotnitzky and Zhao, 1995).
  • Estimating functions in general. The equations are an M-estimator summed over clusters, and the sandwich is the general M-estimator covariance, which also covers heteroscedasticity-consistent standard errors and exactly identified generalized method of moments. Line L6 is Fisher scoring for the quasi-score.

Pitfalls

  • Few clusters. The theory is for G→∞G \to \infty. With 30 clusters the sandwich intervals covered about 92% instead of 95% in the table above, and with fewer than about 20 clusters a correction is needed. The rank of MM is at most G−1G - 1, so with p≥Gp \ge G the sandwich is singular.
  • Time-varying covariates. A non-diagonal working correlation uses xx values from other times in the same cluster. If E[yij∣Xi]≠E[yij∣xij]E[y_{ij} \mid X_i] \ne E[y_{ij} \mid x_{ij}], for example when past responses affect future covariates, the estimate is biased; Pepe and Anderson (1994) recommend the independence working correlation in that case.
  • Missing data. The unweighted equations need responses missing completely at random. Dropout that depends on observed earlier responses biases them.
  • No likelihood. There is no likelihood ratio test and no AIC. Use Wald tests with the sandwich covariance, or score tests based on UU, and QIC for model choice.
  • Marginal versus conditional effects. With a nonlinear link, the coefficients are averages over the population of clusters. They are not the effect for a given cluster, and they are smaller in absolute value than those of a mixed model for the logit link.
  • An impossible working correlation. The moment estimate of α\alpha can fall outside the range where R(α)R(\alpha) is positive definite, for example below −1/(m−1)-1/(m - 1) for an exchangeable RR; the implementation clips it.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

generalized_estimating_equations.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-estimating-equations/. The authors are listed in prov/F7TMV3.jsonl.
"""Generalized estimating equations for clustered responses.

The mean model is mu_ij = g^{-1}(x_ij^T b) and Var y_ij = phi V(mu_ij). Within cluster i the working
covariance is V_i = phi S_i R(alpha) S_i with S_i = diag(sqrt V(mu_ij)). The estimate solves
    sum_i D_i^T V_i^{-1} (y_i - mu_i) = 0,   D_i = d mu_i / d b,
by Fisher scoring, and its covariance is the sandwich B^{-1} M B^{-1} with B = sum D_i^T V_i^{-1} D_i
and M = sum D_i^T V_i^{-1} (y_i - mu_i)(y_i - mu_i)^T V_i^{-1} D_i.

The Gaussian family uses only +, -, * and /, so with Fraction inputs and a fixed alpha the results
are exact.
"""

import math
from typing import NamedTuple

CORRELATIONS = ("independence", "exchangeable", "ar1")


def _expit(t):
    if t >= 0:
        return 1.0 / (1.0 + math.exp(-t))
    z = math.exp(t)
    return z / (1.0 + z)


# family -> (inverse link, d mu / d eta, variance function)
FAMILIES = {
    "gaussian": (lambda e: e, lambda e, m: 1, lambda m: 1),
    "poisson": (lambda e: math.exp(e), lambda e, m: m, lambda m: m),
    "binomial": (_expit, lambda e, m: m * (1 - m), lambda m: m * (1 - m)),
}


class GEEResult(NamedTuple):
    b: list            # coefficients
    cov: list          # sandwich covariance B^-1 M B^-1
    naive: list        # model-based covariance B^-1, valid only if the working covariance is right
    se: list           # square roots of the diagonal of cov
    phi: object        # dispersion estimate
    alpha: object      # working correlation parameter (0 for independence)
    iterations: int
    converged: bool


def solve_many(a: list, rhs: list) -> list:
    """Solve a X = rhs for X (rhs given as a list of rows, k x c). Gaussian elimination with
    partial pivoting; works with float and Fraction entries."""
    k = len(a)
    c = len(rhs[0]) if rhs else 0
    m = [list(a[i]) + list(rhs[i]) for i in range(k)]
    for col in range(k):
        piv = max(range(col, k), key=lambda r: abs(m[r][col]))
        if m[piv][col] == 0:
            raise ValueError("singular matrix")
        m[col], m[piv] = m[piv], m[col]
        for r in range(k):
            if r != col and m[r][col] != 0:
                f = m[r][col] / m[col][col]
                m[r] = [u - f * v for u, v in zip(m[r], m[col])]
    return [[m[i][k + j] / m[i][i] for j in range(c)] for i in range(k)]


def working_correlation(m: int, kind: str, alpha) -> list:
    """The m x m working correlation matrix R(alpha)."""
    one = alpha * 0 + 1
    if kind == "independence":
        return [[one if i == j else 0 * one for j in range(m)] for i in range(m)]
    if kind == "exchangeable":
        return [[one if i == j else alpha for j in range(m)] for i in range(m)]
    return [[alpha ** abs(i - j) for j in range(m)] for i in range(m)]


def _sqrt(v):
    return 1 if v == 1 else math.sqrt(v)


def _cluster_terms(cluster, b, fam, kind, alpha):
    """For one cluster, with V_i = S_i R S_i taken at phi = 1 (phi cancels from the update).
    Returns (resid, s, d, vinv_d, vinv_r): y_i - mu_i, the diagonal of S_i, D_i, V_i^-1 D_i and
    V_i^-1 (y_i - mu_i)."""
    inv_link, dmu, var = fam
    x, y = cluster
    eta = [sum(c * v for c, v in zip(b, row)) for row in x]
    mu = [inv_link(e) for e in eta]
    s = [_sqrt(var(m)) for m in mu]
    d = [[dmu(e, m) * v for v in row] for row, e, m in zip(x, eta, mu)]
    resid = [yi - m for yi, m in zip(y, mu)]
    r = working_correlation(len(y), kind, alpha)
    v = [[s[i] * r[i][j] * s[j] for j in range(len(y))] for i in range(len(y))]
    sol = solve_many(v, [dr + [e] for dr, e in zip(d, resid)])
    p = len(b)
    return resid, s, d, [row[:p] for row in sol], [row[p] for row in sol]


def _moments(clusters, b, fam, kind, n_obs, p):
    """Dispersion and correlation from Pearson residuals r_ij = (y_ij - mu_ij) / sqrt V(mu_ij)."""
    inv_link, _, var = fam
    ss = 0
    pair_sum = 0
    pairs = 0
    for x, y in clusters:
        mu = [inv_link(sum(c * v for c, v in zip(b, row))) for row in x]
        r = [(yi - m) / _sqrt(var(m)) for yi, m in zip(y, mu)]
        ss += sum(t * t for t in r)
        if kind == "exchangeable":
            for j in range(len(r)):
                for k in range(j + 1, len(r)):
                    pair_sum += r[j] * r[k]
            pairs += len(r) * (len(r) - 1) // 2
        elif kind == "ar1":
            pair_sum += sum(r[j] * r[j + 1] for j in range(len(r) - 1))
            pairs += len(r) - 1
    phi = ss / (n_obs - p)
    if kind == "independence" or pairs == 0 or phi == 0:
        return phi, 0
    alpha = pair_sum / (pairs * phi)
    m_max = max(len(y) for _, y in clusters)
    lo = -1.0 / (m_max - 1) + 1e-3 if kind == "exchangeable" else -0.99
    return phi, min(0.99, max(lo, float(alpha)))


def gee(clusters: list, family: str = "gaussian", corr: str = "exchangeable", alpha=None,
        b0: list | None = None, tol: float = 1e-10, max_iter: int = 100) -> GEEResult:
    """Fit generalized estimating equations.

    clusters: list of (x_i, y_i), x_i a list of m_i rows of length p, y_i a list of m_i responses,
    in time order within the cluster for corr="ar1". If alpha is given it is held fixed;
    otherwise it is re-estimated from Pearson residuals at each step.
    Cost per step: Theta(sum_i (m_i^3 + m_i^2 p + m_i p^2) + p^3).
    """
    if family not in FAMILIES or corr not in CORRELATIONS:  # @line L1
        raise ValueError("unknown family or working correlation")
    if not clusters:
        raise ValueError("need at least one cluster")
    p = len(clusters[0][0][0])
    n_obs = 0
    for x, y in clusters:
        if len(x) != len(y) or not y or any(len(row) != p for row in x):
            raise ValueError("each cluster needs rows of length p and one response per row")
        n_obs += len(y)
    if n_obs <= p:
        raise ValueError("need more observations than coefficients")
    fam = FAMILIES[family]
    b = list(b0) if b0 is not None else [0 * clusters[0][1][0] for _ in range(p)]  # @line L2
    fixed = alpha is not None
    a = alpha if fixed else 0
    phi = 1
    converged = False
    it = 0
    for it in range(1, max_iter + 1):  # @line L3
        if not fixed and corr != "independence":
            phi, a = _moments(clusters, b, fam, corr, n_obs, p)  # @line L4
        big_b = [[0] * p for _ in range(p)]
        u = [0] * p
        for cl in clusters:
            resid, _, d, vinv_d, vinv_r = _cluster_terms(cl, b, fam, corr, a)  # @line L5
            for j in range(p):
                u[j] += sum(d[t][j] * vinv_r[t] for t in range(len(resid)))
                for k in range(p):
                    big_b[j][k] += sum(d[t][j] * vinv_d[t][k] for t in range(len(resid)))
        step = [row[0] for row in solve_many(big_b, [[v] for v in u])]
        b = [bj + sj for bj, sj in zip(b, step)]  # @line L6
        if max(abs(s) for s in step) <= tol * (1 + max(abs(v) for v in b)):  # @line L7
            converged = True
            break
    phi_final, a_final = _moments(clusters, b, fam, corr, n_obs, p)
    if fixed:
        a_final = alpha
    big_b = [[0] * p for _ in range(p)]
    meat = [[0] * p for _ in range(p)]
    for cl in clusters:
        resid, _, d, vinv_d, vinv_r = _cluster_terms(cl, b, fam, corr, a_final)
        score = [sum(d[t][j] * vinv_r[t] for t in range(len(resid))) for j in range(p)]
        for j in range(p):
            for k in range(p):
                big_b[j][k] += sum(d[t][j] * vinv_d[t][k] for t in range(len(resid)))
                meat[j][k] += score[j] * score[k]
    eye = [[1 if i == j else 0 for j in range(p)] for i in range(p)]
    binv = solve_many(big_b, eye)
    left = [[sum(binv[i][t] * meat[t][j] for t in range(p)) for j in range(p)] for i in range(p)]
    cov = [[sum(left[i][t] * binv[t][j] for t in range(p)) for j in range(p)] for i in range(p)]  # @line L8
    naive = [[phi_final * v for v in row] for row in binv]
    se = [math.sqrt(float(cov[i][i])) for i in range(p)]
    return GEEResult(b, cov, naive, se, phi_final, a_final, it, converged)  # @line L8


def glm_independence_score(clusters: list, b: list, family: str) -> list:
    """The GLM score sum_ij x_ij (dmu/deta) (y_ij - mu_ij) / V(mu_ij) at b, for checks."""
    inv_link, dmu, var = FAMILIES[family]
    p = len(b)
    out = [0.0] * p
    for x, y in clusters:
        for row, yi in zip(x, y):
            e = sum(c * v for c, v in zip(b, row))
            m = inv_link(e)
            f = dmu(e, m) * (yi - m) / var(m)
            for j in range(p):
                out[j] += row[j] * f
    return out
test_generalized_estimating_equations.py 232 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-estimating-equations/. The authors are listed in prov/F7TMV3.jsonl.

import math
import random
from fractions import Fraction

import pytest

from generalized_estimating_equations import gee, glm_independence_score, working_correlation

F = Fraction
EX_X = [1, 2, 3, 4, 5, 6]
EX_Y = [2, 3, 2, 4, 7, 8]


def ex_clusters(conv=F):
    return [([[conv(1), conv(EX_X[i])] for i in (2 * g, 2 * g + 1)], [conv(EX_Y[i]) for i in (2 * g, 2 * g + 1)])
            for g in range(3)]


def mat_solve(a, b):
    """Plain Gauss-Jordan on Fractions, written separately from the module."""
    k = len(a)
    m = [[F(v) for v in row] + [F(b[i])] for i, row in enumerate(a)]
    for c in range(k):
        piv = next(r for r in range(c, k) if m[r][c] != 0)
        m[c], m[piv] = m[piv], m[c]
        for r in range(k):
            if r != c and m[r][c] != 0:
                f = m[r][c] / m[c][c]
                m[r] = [u - f * v for u, v in zip(m[r], m[c])]
    return [m[i][k] / m[i][i] for i in range(k)]


def mat_inv(a):
    k = len(a)
    cols = [mat_solve(a, [1 if i == j else 0 for i in range(k)]) for j in range(k)]
    return [[cols[j][i] for j in range(k)] for i in range(k)]


def matmul(a, b):
    return [[sum(a[i][t] * b[t][j] for t in range(len(b))) for j in range(len(b[0]))] for i in range(len(a))]


def transpose(a):
    return [list(r) for r in zip(*a)]


def cr0_direct(clusters):
    """(X^T X)^-1 (sum_g X_g^T e_g e_g^T X_g) (X^T X)^-1 with OLS residuals, all in Fractions."""
    x = [row for xs, _ in clusters for row in xs]
    y = [v for _, ys in clusters for v in ys]
    xtx = matmul(transpose(x), x)
    b = mat_solve(xtx, [sum(r[j] * v for r, v in zip(x, y)) for j in range(len(x[0]))])
    meat = [[F(0)] * len(b) for _ in b]
    for xs, ys in clusters:
        e = [v - sum(c * t for c, t in zip(b, r)) for r, v in zip(xs, ys)]
        s = [sum(r[j] * ei for r, ei in zip(xs, e)) for j in range(len(b))]
        for i in range(len(b)):
            for j in range(len(b)):
                meat[i][j] += s[i] * s[j]
    inv = mat_inv(xtx)
    return b, matmul(matmul(inv, meat), inv)


def gls_direct(clusters, kind, alpha):
    """GLS with the block diagonal covariance built from R(alpha), solved on the full n x n matrix."""
    x = [row for xs, _ in clusters for row in xs]
    y = [v for _, ys in clusters for v in ys]
    n = len(y)
    sigma = [[F(0)] * n for _ in range(n)]
    off = 0
    for _, ys in clusters:
        m = len(ys)
        for i in range(m):
            for j in range(m):
                if kind == "exchangeable":
                    sigma[off + i][off + j] = F(1) if i == j else alpha
                else:
                    sigma[off + i][off + j] = alpha ** abs(i - j)
        off += m
    sinv = mat_inv(sigma)
    xt_si = matmul(transpose(x), sinv)
    return mat_solve(matmul(xt_si, x), [sum(r * v for r, v in zip(row, y)) for row in xt_si])


def test_page_example_exact():
    r = gee(ex_clusters(), "gaussian", "independence")
    assert r.b == [F(-1, 15), F(44, 35)]  # the least squares line
    assert r.phi == F(149, 105)  # residual sum of squares over n - p
    b, cov = cr0_direct(ex_clusters())
    assert r.cov == cov  # independence GEE sandwich = CR0 cluster-robust covariance
    assert r.se[1] == pytest.approx(0.2171, abs=1e-4)
    assert math.sqrt(r.naive[1][1]) == pytest.approx(0.2848, abs=1e-4)
    fixed = gee(ex_clusters(), "gaussian", "exchangeable", alpha=F(1, 2))
    assert fixed.b == [F(-13, 123), F(52, 41)]
    est = gee(ex_clusters(float), "gaussian", "exchangeable")
    assert est.converged
    assert est.alpha == pytest.approx(0.5871, abs=1e-4)
    assert est.b == pytest.approx([-0.1189, 1.2721], abs=1e-4)
    assert est.se[1] == pytest.approx(0.1903, abs=1e-4)


def test_gaussian_fixed_alpha_is_gls_exact():
    rng = random.Random(41)
    for kind, alpha in (("exchangeable", F(1, 3)), ("exchangeable", F(-1, 5)), ("ar1", F(2, 5)), ("ar1", F(-1, 2))):
        for _ in range(3):
            clusters = []
            for _ in range(rng.randint(3, 5)):
                m = rng.randint(1, 4)
                xs = [[F(1), F(rng.randint(-4, 4)), F(rng.randint(0, 3))] for _ in range(m)]
                ys = [F(rng.randint(-9, 9)) for _ in range(m)]
                clusters.append((xs, ys))
            try:
                expect = gls_direct(clusters, kind, alpha)
            except StopIteration:
                continue
            assert gee(clusters, "gaussian", kind, alpha=alpha).b == expect


def test_singleton_clusters_give_hc0_exact():
    rng = random.Random(42)
    rows = [([[F(1), F(rng.randint(-5, 5))]], [F(rng.randint(-9, 9))]) for _ in range(7)]
    r = gee(rows, "gaussian", "exchangeable", alpha=F(1, 3))  # alpha has no effect with m_i = 1
    b, cov = cr0_direct(rows)
    assert r.b == b and r.cov == cov


def test_independence_equals_glm_fit():
    rng = random.Random(43)
    for family in ("poisson", "binomial"):
        clusters = []
        for _ in range(25):
            u = rng.gauss(0.0, 0.5)
            xs = [[1.0, rng.gauss(0.0, 1.0)] for _ in range(3)]
            ys = []
            for row in xs:
                eta = 0.3 + 0.6 * row[1] + u
                if family == "poisson":
                    lam, k, pr = math.exp(-math.exp(eta)), 0, 1.0
                    while True:
                        pr *= rng.random()
                        if pr <= lam:
                            break
                        k += 1
                    ys.append(float(k))
                else:
                    ys.append(1.0 if rng.random() < 1.0 / (1.0 + math.exp(-eta)) else 0.0)
            clusters.append((xs, ys))
        r = gee(clusters, family, "independence")
        assert r.converged
        # The GLM score is 0 at the GEE estimate, and the log-likelihood is strictly concave for a
        # canonical link, so this is the GLM maximum likelihood fit.
        assert max(abs(s) for s in glm_independence_score(clusters, r.b, family)) < 1e-8
        # Pooling the clusters into singletons changes the variance but not the estimate.
        singles = [([row], [v]) for xs, ys in clusters for row, v in zip(xs, ys)]
        assert gee(singles, family, "independence").b == pytest.approx(r.b, abs=1e-9)


def test_estimating_equation_and_invariance():
    rng = random.Random(44)
    clusters = []
    for _ in range(20):
        u = rng.gammavariate(2.0, 0.5)
        xs = [[1.0, rng.random(), t / 3.0] for t in range(4)]
        ys = []
        for row in xs:
            lam, k, pr = math.exp(-u * math.exp(0.5 + 0.4 * row[1] + 0.3 * row[2])), 0, 1.0
            while True:
                pr *= rng.random()
                if pr <= lam:
                    break
                k += 1
            ys.append(float(k))
        clusters.append((xs, ys))
    for kind in ("exchangeable", "ar1"):
        r = gee(clusters, "poisson", kind)
        assert r.converged
        fixed = gee(clusters, "poisson", kind, alpha=r.alpha, b0=r.b)
        assert fixed.b == pytest.approx(r.b, abs=1e-8)
        assert gee(list(reversed(clusters)), "poisson", kind).b == pytest.approx(r.b, abs=1e-8)
    r = working_correlation(3, "ar1", F(1, 2))
    assert r == [[1, F(1, 2), F(1, 4)], [F(1, 2), 1, F(1, 2)], [F(1, 4), F(1, 2), 1]]


def test_coverage_and_efficiency_measured():
    """Random intercept model, G = 30 clusters of 4, intra-cluster correlation 0.5. With r = 1000 the
    95% coverage for the cluster-level slope was: independence model-based 0.777, independence
    sandwich 0.921, exchangeable sandwich 0.921; the standard deviation of the within-cluster slope
    was 0.1317 (independence) and 0.1055 (exchangeable). Here r = 120 (4 SE of a coverage near 0.92
    is about 0.10)."""
    rng = random.Random(11)
    g_count, m, r = 30, 4, 120
    xs = [(g % 10) / 9.0 for g in range(g_count)]
    ws = [[rng.gauss(0, 1) for _ in range(m)] for _ in range(g_count)]
    z = 1.959963984540054
    naive = sand = 0
    w_ind, w_exc = [], []
    for _ in range(r):
        cl = []
        for g in range(g_count):
            a = rng.gauss(0, 1)
            cl.append(([[1.0, xs[g], ws[g][j]] for j in range(m)],
                       [1.0 + 0.5 * xs[g] + 0.5 * ws[g][j] + a + rng.gauss(0, 1) for j in range(m)]))
        ri = gee(cl, "gaussian", "independence")
        re = gee(cl, "gaussian", "exchangeable")
        naive += abs(ri.b[1] - 0.5) <= z * math.sqrt(ri.naive[1][1])
        sand += abs(re.b[1] - 0.5) <= z * re.se[1]
        w_ind.append(ri.b[2])
        w_exc.append(re.b[2])

    def sd(v):
        mu = sum(v) / len(v)
        return math.sqrt(sum((t - mu) ** 2 for t in v) / (len(v) - 1))

    assert sand / r >= 0.83
    assert naive / r <= 0.88
    assert sd(w_exc) < 0.92 * sd(w_ind)


def test_bad_inputs():
    with pytest.raises(ValueError):
        gee(ex_clusters(), "gamma", "independence")
    with pytest.raises(ValueError):
        gee(ex_clusters(), "gaussian", "unstructured")
    with pytest.raises(ValueError):
        gee([], "gaussian", "independence")
    with pytest.raises(ValueError):
        gee([([[1, 2]], [1, 2])], "gaussian", "independence")
    with pytest.raises(ValueError):
        gee([([[1, 2]], [1])], "gaussian", "independence")  # n = 1 <= p = 2

Exercises

  1. Show that with the independence working correlation the equations are the score equations of the generalized linear model, for any ϕ\phi. Answer. With R=IR = I, Vi=ϕSi2V_i = \phi S_i^2 is diagonal and Di=diag⁡(dμij/dη)XiD_i = \operatorname{diag}(d\mu_{ij}/d\eta)X_i, so Di⊤Vi−1(yi−μi)=∑jxij(dμij/dη)(yij−μij)/(ϕV(μij))D_i^\top V_i^{-1}(y_i - \mu_i) = \sum_jx_{ij}(d\mu_{ij}/d\eta)(y_{ij} - \mu_{ij})/(\phi V(\mu_{ij})). Summed over ii this is the GLM score divided by ϕ\phi, and ϕ\phi does not change its root.
  2. For the identity link, V=1V = 1 and a fixed α\alpha, show that the solution is b^=(∑iXi⊤Ri−1Xi)−1∑iXi⊤Ri−1yi\hat b = (\sum_iX_i^\top R_i^{-1}X_i)^{-1}\sum_iX_i^\top R_i^{-1}y_i. Answer. Di=XiD_i = X_i and Vi=ϕRiV_i = \phi R_i, so U(b)=ϕ−1∑iXi⊤Ri−1(yi−Xib)U(b) = \phi^{-1}\sum_iX_i^\top R_i^{-1}(y_i - X_ib), which is linear in bb. Setting it to 0 gives the formula, which is generalized least squares with the block diagonal covariance diag⁡(R1,…,RG)\operatorname{diag}(R_1, \dots, R_G).
  3. For an exchangeable R=(1−α)I+α11⊤R = (1 - \alpha)I + \alpha\mathbf 1\mathbf 1^\top of size mm, show that R−1=11−α(I−α1+(m−1)α11⊤)R^{-1} = \frac{1}{1 - \alpha}\big(I - \frac{\alpha}{1 + (m - 1)\alpha}\mathbf 1\mathbf 1^\top\big), and say for which α\alpha it exists. Answer. Multiply: (1−α)I⋅11−α(I−c11⊤)+α11⊤11−α(I−c11⊤)=I+11⊤(−c+α(1−mc)1−α)(1 - \alpha)I \cdot \frac{1}{1-\alpha}(I - c\mathbf 1\mathbf 1^\top) + \alpha\mathbf 1\mathbf 1^\top\frac{1}{1-\alpha}(I - c\mathbf 1\mathbf 1^\top) = I + \mathbf 1\mathbf 1^\top\big(-c + \frac{\alpha(1 - mc)}{1 - \alpha}\big), and with c=α/(1+(m−1)α)c = \alpha/(1 + (m - 1)\alpha) the bracket is 0. RR has the eigenvalues 1−α1 - \alpha and 1+(m−1)α1 + (m - 1)\alpha, so it is positive definite for −1/(m−1)<α<1-1/(m - 1) < \alpha < 1.
  4. Show that MM in line L8 has rank at most G−1G - 1 at the solution. Answer. M=∑iUiUi⊤M = \sum_iU_iU_i^\top with Ui=Di⊤Vi−1(yi−μi)U_i = D_i^\top V_i^{-1}(y_i - \mu_i), a sum of GG rank-one matrices. At the solution ∑iUi=0\sum_iU_i = 0, so the UiU_i span a space of dimension at most G−1G - 1.
  5. In the random intercept example, why does the independence model-based interval undercover for xix_i but not for wijw_{ij}? Answer. The model-based variance treats the 4G=1204G = 120 responses as independent. For a covariate that is constant within clusters, the information is about that of the 30 cluster means, each with variance (1+1/4)(1 + 1/4) instead of 2/42/4 per response, so the true variance is about 2.5 times the model-based one when α=0.5\alpha = 0.5. A covariate that varies inside clusters is compared within clusters, where the shared aia_i cancels, so the independence variance is not too small for it.

References

  1. Kung-Yee Liang and Scott L. Zeger, Longitudinal data analysis using generalized linear models, Biometrika 73(1), 1986, pp. 13 to 22, The whole paper (the estimating equations with a working correlation, the consistency of the estimate when only the mean model is right, and the robust covariance)
  2. Scott L. Zeger and Kung-Yee Liang, Longitudinal data analysis for discrete and continuous outcomes, Biometrics 42(1), 1986, pp. 121 to 130, The whole paper (the method for binary, count and continuous repeated measures, with the moment estimates of the correlation and examples)
  3. Margaret S. Pepe and Garnet L. Anderson, A cautionary note on inference for marginal regression models with longitudinal data and general correlated response data, Communications in Statistics, Simulation and Computation 23(4), 1994, pp. 939 to 951, The whole paper (with time-varying covariates a non-diagonal working correlation can bias the estimate unless the mean given all covariates of the cluster equals the mean given the current one)
  4. Lloyd A. Mancl and Timothy A. DeRouen, A covariance estimator for GEE with improved small-sample properties, Biometrics 57(1), 2001, pp. 126 to 134, The whole paper (the robust covariance is biased downward with few clusters, and a leverage-type correction)
  5. Wei Pan, Akaike's information criterion in generalized estimating equations, Biometrics 57(1), 2001, pp. 120 to 125, The whole paper (QIC for choosing the working correlation and QICu for choosing covariates)
  6. James M. Robins, Andrea Rotnitzky and Lue Ping Zhao, Analysis of semiparametric regression models for repeated outcomes in the presence of missing data, Journal of the American Statistical Association 90(429), 1995, pp. 106 to 121, The whole paper (inverse probability weighted estimating equations that stay consistent when responses are missing at random)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples