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 independent clusters, and the model specifies only the marginal mean and a variance function, as in quasi-likelihood. The correlation inside a cluster is replaced by a working guess . 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 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 are independent, with responses and an matrix of covariates. Responses inside a cluster may be correlated in any way.
- A marginal mean model. , with a link and for a variance function . The coefficients describe the population average, not a single cluster.
- The estimating equations. With (), and the working covariance ,
- Why a wrong guess does not bias it. For any fixed , and depend on and only, so at the true . This is exact, and it is the reason for consistency. It needs the mean of given all of , not only given , to follow the model; Pepe and Anderson (1994) showed that this can fail with time-varying covariates.
- Many clusters. The asymptotic theory lets with bounded . The working correlation must have a parameter that can be estimated at rate ; any moment estimate below qualifies.
The template
GEE((X_1, y_1), ..., (X_G, y_G))- 1
choose LINK g, VARIANCE-FUNCTION V, WORKING-CORRELATION R(α) ▷ holes - 2
b ← START ▷ hole: 0, or the independence fit - 3
repeat - 4
(φ̂, α̂) ← MOMENTS of the Pearson residuals rᵢⱼ = (yᵢⱼ - μᵢⱼ) / √V(μᵢⱼ) - 5
for each cluster i: μᵢ, Dᵢ = ∂μᵢ/∂b, Vᵢ = Sᵢ R(α̂) Sᵢ - 6
b ← b + (Σᵢ DᵢᵀVᵢ⁻¹Dᵢ)⁻¹ Σᵢ DᵢᵀVᵢ⁻¹(yᵢ - μᵢ) ▷ a Fisher scoring step - 7
until the step is small - 8
return 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 (), exchangeable ( for ) and first-order autoregressive (). The implementation estimates by , with , and by the mean of over the pairs of the structure divided by ; it keeps inside the range where is positive definite. Since cancels from line L6, the update needs only up to the factor , and enters only the model-based covariance , which is valid only if is right. One step costs .
What is proved and what is cited. The page and the tests show four exact facts. With , , which is the generalized linear model score, so the fit is the GLM fit. For the identity link with and a fixed , the equations are , the normal equations of generalized least squares with a block diagonal covariance, and line L6 reaches them in one step. With and the identity link, , 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 and are -consistent, then is consistent and is asymptotically normal with a covariance consistently estimated by times line L8, whatever is; and if is right, the estimate is efficient among estimates of this form. These are results for , and the coverage at a given is only measured.
Classic examples
The independence fit is the GLM fit. The page example of the cluster-robust standard errors has , and the clusters , , , with an intercept. With the identity link and :
| working correlation | slope SE, sandwich | slope SE, model-based | |
|---|---|---|---|
| independence | 0.2171 | 0.2848 | |
| exchangeable, fixed | 0.1953 | ||
| exchangeable, | 0.1903 | 0.3218 |
The independence row is least squares, 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- 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 clusters of 4, with and independent , so that the true correlation is exchangeable with , a cluster-level covariate and a covariate that varies inside clusters. Over 1000 data sets, the coverage of 95% Wald intervals was:
| interval | slope of | slope of |
|---|---|---|
| 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 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 clusters of 4 Poisson counts whose means share a gamma-distributed cluster factor with mean 1 and shape 2, the marginal mean is still . The log link with and an exchangeable working correlation converged in all 500 data sets, with a mean 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 , 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 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 in by , where is the cluster block of a leverage matrix, which removes most of the downward bias of the sandwich with few clusters. Using quantiles with or degrees of freedom also helps, as for cluster-robust standard errors.
- Weighted equations for missing data. Inverse probability weights inside 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 . 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 is at most , so with the sandwich is singular.
- Time-varying covariates. A non-diagonal working correlation uses values from other times in the same cluster. If , 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 , 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 can fall outside the range where is positive definite, for example below for an exchangeable ; 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.
# 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
- Show that with the independence working correlation the equations are the score equations of the generalized linear model, for any . Answer. With , is diagonal and , so . Summed over this is the GLM score divided by , and does not change its root.
- For the identity link, and a fixed , show that the solution is . Answer. and , so , which is linear in . Setting it to 0 gives the formula, which is generalized least squares with the block diagonal covariance .
- For an exchangeable of size , show that , and say for which it exists. Answer. Multiply: , and with the bracket is 0. has the eigenvalues and , so it is positive definite for .
- Show that in line L8 has rank at most at the solution. Answer. with , a sum of rank-one matrices. At the solution , so the span a space of dimension at most .
- In the random intercept example, why does the independence model-based interval undercover for but not for ? Answer. The model-based variance treats the responses as independent. For a covariate that is constant within clusters, the information is about that of the 30 cluster means, each with variance instead of per response, so the true variance is about 2.5 times the model-based one when . A covariate that varies inside clusters is compared within clusters, where the shared cancels, so the independence variance is not too small for it.
References
- 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)
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag F7TMV3 Edit this page History Report an error Markdown