Techniquecore
Multiple imputation
Also called Rubin's rules.
Fill in missing values several times from a predictive model, analyse each completed data set, and pool the results with Rubin's rules so the variance reflects the missingness.
Multiple imputation handles missing data in three steps. First, replace each missing value by a random draw from its predictive distribution given the observed data, and do this times to get completed data sets. Second, run the analysis you would run on complete data on each of them. Third, combine the estimates and their variances with Rubin's rules: the point estimate is the mean , and the variance adds the spread between the imputations to the mean variance within them. When the values are missing at random and the imputation model is correct and proper, is consistent and the interval has close to nominal coverage. A single imputation gives the same kind of point estimate but treats guesses as data, so its standard errors are too small.
In plain words
Some values in your table are empty. You could guess each one from the rest of the data, but then you would treat the guesses as if you had measured them, and you would claim more certainty than you have.
Instead, make several guesses for each empty value, each a little different, in the way a real value could differ. This gives several complete tables. Analyse each table in the usual way. The answers will not agree exactly. Their average is your answer. How much they disagree tells you how much the empty values cost you, and you add that to the usual uncertainty.
This works when the reason a value is missing depends only on things you can see in the data, and when the guessing model fits the data well.
When it applies
- The missingness is ignorable: missing at random given the variables in the imputation model, with distinct parameters. Under missing not at random, the imputation model must include a model for the mechanism, or the results are only a sensitivity analysis.
- There is a predictive model for the missing values given the observed ones, such as a normal linear regression, a logistic regression, or chained equations for many incomplete variables.
- The analysis of complete data gives an estimate of a scalar and a variance , with close to normal, as for means, regression coefficients and log odds ratios. Rubin's rules use only and .
- The imputation model includes every variable in the analysis, the outcome too, and any variable that predicts missingness.
The template
MULTIPLE-IMPUTATION(Y_obs, m)- 1
for j ← 1 to m do - 2
fit IMPUTATION-MODEL on the rows with y observed ▷ hole: normal regression of y on x - 3
draw σ*² from its posterior ▷ proper: a draw, not the estimate - 4
draw β* from its posterior given σ*² - 5
each missing y_i ← x_i'β* + σ* z_i, z_i ~ N(0, 1) ▷ observed values stay as they are - 6
(Q_j, U_j) ← ANALYSIS(completed data set j) ▷ hole: the complete-data method - 7
Q̄ ← (1/m) Σ_j Q_j; W ← (1/m) Σ_j U_j; B ← (1/(m-1)) Σ_j (Q_j - Q̄)² - 8
T ← W + (1 + 1/m) B - 9
return Q̄ ± t_ν √T ▷ hole: Rubin or Barnard-Rubin ν
The holes are the imputation model (lines L2 to L5), the analysis (line L6) and the degrees of freedom (line L9). For normal linear regression with the prior , fitted on rows with predictors, line L3 draws and line L4 draws . The imputed value then has the exact posterior predictive distribution, a t law centered at .
Why the draws must include the parameters. If line L5 used and in place of the draws, the imputations would show the noise around the fitted line but not the uncertainty of the line itself. would then be too small, and so would . Rubin calls imputations that include this uncertainty proper.
Where comes from. Think of in a Bayesian way. Its posterior given the observed data is the mixture, over the missing values, of its posterior given the completed data. By the laws of total expectation and total variance,
With and as the completed-data posterior mean and variance, and estimate the first terms and estimates the last one. The factor accounts for estimating by a mean of only draws: . These two identities are proved. The t reference law in line L9 is an approximation that Rubin (1987) derived for finite and large complete-data samples; its accuracy is measured, not proved.
Degrees of freedom. With , the relative increase in variance, and , Rubin's degrees of freedom are
When is small, is very large, even if the complete-data analysis has only a few degrees of freedom . Barnard and Rubin (1999) use
which never exceeds or and tends to as . When , and the normal quantile is used.
Classic examples
Rubin's rules by hand. Take estimates , each with . Then , , , , , and . The 95% interval is . Most of the variance here comes from the disagreement of the imputations.
A mean with MAR outcome. Take and , where is missing at . The analysis is the mean of with (divisor in ). The complete-case mean is ; it is too low because the missing values lie mostly at large . Normal regression imputation with (seed 1) gave the means , , , and , so , , and . Rubin's is about 33800, but the complete-data analysis has , and the Barnard-Rubin value is . The 95% interval is .
Coverage under MAR, measured. With , , , , and missing with probability (about 41% missing), the target is . Over 1000 data sets, nominal 95%:
| Method | coverage | mean bias | mean width |
|---|---|---|---|
| complete cases | 0.005 | 0.718 | |
| single regression imputation | 0.905 | 0.001 | 0.592 |
| multiple imputation, | 0.949 | 0.000 | 0.822 |
| multiple imputation, | 0.952 | 0.001 | 0.714 |
| multiple imputation, | 0.957 | 0.001 | 0.695 |
Single imputation removes the bias but its interval is too narrow. Multiple imputation keeps the bias away and restores the coverage; a larger makes the interval shorter.
Regression with incomplete covariates. For a regression with several incomplete covariates, imputation by chained equations fills in all of them, and Rubin's rules pool each coefficient. The outcome must be in the imputation model of each covariate, or the coefficients are biased toward zero.
Variations
- Several parameters at once. For a vector with covariance , and have the same form with a matrix. Tests of several coefficients use an F reference law with a pooled , because is poorly estimated for small .
- Joint models. Draw all missing values together from one multivariate model, such as a multivariate normal fitted by data augmentation, which is a Gibbs sampler on parameters and missing values.
- Predictive mean matching. Replace the draw of line L5 by the observed value of a donor whose predicted mean is close. The imputations are always values that occur in the data.
- Other analysis-side methods. Expectation-maximization gives the maximum likelihood estimate under MAR without imputation, and inverse probability weighting reweights the complete cases. Both need the variance to be computed in another way, such as by the bootstrap.
Pitfalls
- Imputing without the outcome. If the outcome is left out of the model for an incomplete covariate, the imputed covariate is unrelated to the outcome, and its coefficient is biased toward zero.
- Improper imputation. Drawing from the fitted model at , gives intervals that are too narrow, the more so when many values are missing.
- Uncongenial models. If the imputation model assumes less than the analysis, such as no interaction where the analysis has one, the pooled estimate is biased for that term. If it assumes more and is right, can be too large.
- Too few imputations. Rubin's efficiency of with imputations relative to is , with the fraction of missing information: 0.943 for , . This is about the point estimate. Standard errors, p values and their reproducibility need more, often at least the percentage of incomplete cases.
- Pooling the wrong quantity. Apply Rubin's rules to quantities that are close to normal: pool log odds ratios, not odds ratios, and Fisher-transformed correlations, not correlations. Do not average p values or test statistics.
- MNAR data. No imputation model fitted to the observed data can find a dependence of missingness on the missing values themselves. Vary the imputation model, for example by shifting the imputed values, and report how much the answer moves.
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/multiple-imputation/. The authors are listed in prov/W9KZM4.jsonl.
import math
import random
from collections.abc import Callable, Sequence
from fractions import Fraction
from typing import NamedTuple
from stdist import norm_ppf, t_ppf
class Pooled(NamedTuple):
qbar: object # mean of the m estimates
w: object # mean within-imputation variance
b: object # between-imputation variance, divisor m - 1
t: object # total variance W + (1 + 1/m) B
r: object # relative increase in variance (1 + 1/m) B / W
lam: object # (1 + 1/m) B / T, the fraction of variance due to missing data
df: float # degrees of freedom (Rubin 1987, or Barnard and Rubin 1999)
def rubin_pool(estimates: Sequence, variances: Sequence, df_com: float | None = None) -> Pooled:
"""Combine m >= 2 completed-data estimates of a scalar with Rubin's rules.
variances are the completed-data variance estimates U_j. With df_com
(the complete-data degrees of freedom) the Barnard-Rubin small-sample
df is returned, otherwise Rubin's (m - 1)(1 + 1/r)^2. df is inf when B = 0.
Exact for Fraction inputs except the df. Cost O(m).
"""
m = len(estimates)
if m < 2 or len(variances) != m:
raise ValueError("need m >= 2 estimates and m variances")
qbar = sum(estimates) / m # @line L7
w = sum(variances) / m
b = sum((q - qbar) ** 2 for q in estimates) / (m - 1)
inc = (1 + Fraction(1, m)) * b if isinstance(b, Fraction) else (1.0 + 1.0 / m) * b
t = w + inc # @line L8
r = inc / w if w != 0 else math.inf
lam = inc / t if t != 0 else 0
if b == 0:
df_m = math.inf
else:
df_m = (m - 1) / float(lam) ** 2
if df_com is None:
df = df_m
else:
df_obs = (df_com + 1) / (df_com + 3) * df_com * (1 - float(lam))
df = 1.0 / (1.0 / df_m + 1.0 / df_obs)
return Pooled(qbar, w, b, t, r, lam, df)
def pooled_interval(p: Pooled, level: float = 0.95) -> tuple[float, float]:
"""Qbar -/+ t_df quantile * sqrt(T); the normal quantile when df is inf."""
a = 0.5 + level / 2
c = norm_ppf(a) if math.isinf(p.df) else t_ppf(a, p.df)
h = c * math.sqrt(float(p.t))
return float(p.qbar) - h, float(p.qbar) + h # @line L9
def _cholesky(a: list) -> list:
k = len(a)
low = [[0.0] * k for _ in range(k)]
for i in range(k):
for j in range(i + 1):
s = a[i][j] - sum(low[i][t] * low[j][t] for t in range(j))
low[i][j] = math.sqrt(s) if i == j else s / low[j][j]
return low
def _inverse(a: list) -> list:
k = len(a)
m = [list(map(float, row)) + [1.0 if i == j else 0.0 for j in range(k)] for i, row in enumerate(a)]
for c in range(k):
p = max(range(c, k), key=lambda r: abs(m[r][c]))
m[c], m[p] = m[p], m[c]
piv = m[c][c]
m[c] = [v / piv for v in m[c]]
for r in range(k):
if r != c and m[r][c] != 0:
f = m[r][c]
m[r] = [u - f * v for u, v in zip(m[r], m[c])]
return [row[k:] for row in m]
def regression_posterior(x: Sequence[Sequence[float]], y: Sequence[float]) -> tuple[list, float, list, int]:
"""OLS on complete rows: (beta-hat, residual sum of squares, (X'X)^-1, n - p)."""
p = len(x[0])
xtx = [[sum(r[i] * r[j] for r in x) for j in range(p)] for i in range(p)]
v = _inverse(xtx)
xty = [sum(r[i] * yi for r, yi in zip(x, y)) for i in range(p)]
beta = [sum(v[i][j] * xty[j] for j in range(p)) for i in range(p)]
rss = sum((yi - sum(b * c for b, c in zip(beta, r))) ** 2 for r, yi in zip(x, y))
return beta, rss, v, len(y) - p
def impute_normal_regression(
y: Sequence[float | None], x: Sequence[Sequence[float]], rng: random.Random
) -> list:
"""One proper draw of the missing y from Bayesian normal linear regression.
y holds None where missing; x is fully observed with a constant column.
Draws sigma*^2 = RSS / chi2(n_obs - p), beta* ~ N(beta-hat, sigma*^2 (X'X)^-1)
and y* = x' beta* + sigma* z. Observed y are returned unchanged.
Precondition: n_obs - p >= 1 and X_obs of full rank. Cost O(n p^2 + p^3).
"""
obs = [i for i, v in enumerate(y) if v is not None]
beta, rss, v, dfr = regression_posterior([x[i] for i in obs], [y[i] for i in obs]) # @line L2
sigma2 = rss / (2.0 * rng.gammavariate(dfr / 2.0, 1.0)) # @line L3
low = _cholesky(v)
z = [rng.gauss(0.0, 1.0) for _ in beta]
p = len(beta)
bstar = [beta[i] + math.sqrt(sigma2) * sum(low[i][j] * z[j] for j in range(p)) for i in range(p)] # @line L4
out = list(y)
for i, yi in enumerate(y):
if yi is None:
out[i] = sum(b * c for b, c in zip(bstar, x[i])) + math.sqrt(sigma2) * rng.gauss(0.0, 1.0) # @line L5
return out
def multiple_imputation(
y: Sequence[float | None],
x: Sequence[Sequence[float]],
analysis: Callable[[list, list], tuple[float, float]],
m: int = 20,
seed: int = 0,
df_com: float | None = None,
) -> tuple[Pooled, list]:
"""Impute y m times, run analysis(x, y_completed) -> (estimate, variance), pool.
Returns the pooled result and the m completed y vectors.
Cost: m times (imputation + analysis).
"""
rng = random.Random(seed)
qs, us, sets = [], [], []
for _ in range(m): # @line L1
yc = impute_normal_regression(y, x, rng)
q, u = analysis(x, yc) # @line L6
qs.append(q)
us.append(u)
sets.append(yc)
return rubin_pool(qs, us, df_com), sets
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.
The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""
import math
from statistics import NormalDist
_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000
def norm_cdf(x: float) -> float:
"""P(Z <= x) for a standard normal Z."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def norm_sf(x: float) -> float:
"""P(Z > x), computed with erfc, so it is accurate for large x."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def norm_ppf(p: float) -> float:
"""The lower p-quantile z_p of the standard normal, 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return _STD.inv_cdf(p)
def _gamma_tails(a: float, x: float) -> tuple[float, float]:
"""(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
if a <= 0.0 or x < 0.0:
raise ValueError("need a > 0 and x >= 0")
if x == 0.0:
return 0.0, 1.0
if math.isinf(x):
return 1.0, 0.0
front = math.exp(-x + a * math.log(x) - math.lgamma(a))
if x < a + 1.0:
# Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
ap, term = a, 1.0 / a
total = term
for _ in range(_MAXIT):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * _EPS:
break
p = front * total
return p, 1.0 - p
# Continued fraction for Q, modified Lentz.
b = x + 1.0 - a
c = 1.0 / _TINY
d = 1.0 / b
h = d
for i in range(1, _MAXIT):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < _TINY:
d = _TINY
c = b + an / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
q = front * h
return 1.0 - q, q
def gamma_p(a: float, x: float) -> float:
"""Regularized lower incomplete gamma P(a, x)."""
return _gamma_tails(a, x)[0]
def gamma_q(a: float, x: float) -> float:
"""Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
return _gamma_tails(a, x)[1]
def _beta_cf(a: float, b: float, x: float) -> float:
"""The continued fraction of I_x(a, b), modified Lentz."""
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
if abs(d) < _TINY:
d = _TINY
d = 1.0 / d
h = d
for m in range(1, _MAXIT):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
return h
def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
"""(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.
y is 1 - x; pass it when it is known more accurately than 1 - x.
"""
if a <= 0.0 or b <= 0.0:
raise ValueError("need a > 0 and b > 0")
if y is None:
y = 1.0 - x
if x <= 0.0:
return 0.0, 1.0
if y <= 0.0:
return 1.0, 0.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
+ a * math.log(x) + b * math.log(y)
)
if x < (a + 1.0) / (a + b + 2.0):
low = front * _beta_cf(a, b, x) / a
return low, 1.0 - low
# Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
up = front * _beta_cf(b, a, y) / b
return 1.0 - up, up
def beta_inc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b)."""
return _beta_tails(a, b, x)[0]
def chi2_cdf(x: float, k: float) -> float:
"""P(X <= x) for X chi-square with k > 0 degrees of freedom."""
return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)
def chi2_sf(x: float, k: float) -> float:
"""P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)
def t_sf(x: float, k: float) -> float:
"""P(T > x) for T Student t with k > 0 degrees of freedom."""
if math.isfinite(x):
s = k + x * x
half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0] # P(|T| > |x|) / 2
else:
half = 0.0
return half if x >= 0.0 else 1.0 - half
def t_cdf(x: float, k: float) -> float:
"""P(T <= x) for T Student t with k degrees of freedom."""
return t_sf(-x, k)
def f_cdf(x: float, k1: float, k2: float) -> float:
"""P(F <= x) for F with (k1, k2) degrees of freedom."""
if x <= 0.0:
return 0.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]
def f_sf(x: float, k1: float, k2: float) -> float:
"""P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
if x <= 0.0:
return 1.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]
def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
"""The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).
lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
"""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
if p <= 0.5:
g = lambda x: cdf(x) - p # increasing in x
else:
q = 1.0 - p
g = lambda x: q - sf(x) # increasing in x, and no cancellation in sf
while g(hi) < 0.0:
lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
for _ in range(400):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
if g(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def chi2_ppf(p: float, k: float) -> float:
"""The lower p-quantile chi^2_(k, p)."""
return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))
def t_ppf(p: float, k: float) -> float:
"""The lower p-quantile t_(k, p)."""
if p == 0.5:
return 0.0
if p < 0.5:
return -t_ppf(1.0 - p, k)
return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)
def f_ppf(p: float, k1: float, k2: float) -> float:
"""The lower p-quantile F_(k1, k2, p)."""
return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
test_multiple_imputation.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multiple-imputation/. The authors are listed in prov/W9KZM4.jsonl.
import math
import random
from fractions import Fraction
from multiple_imputation import (
impute_normal_regression,
multiple_imputation,
pooled_interval,
regression_posterior,
rubin_pool,
)
from stdist import norm_ppf, t_ppf
def mean_analysis(x, y):
n = len(y)
m = sum(y) / n
s2 = sum((v - m) ** 2 for v in y) / (n - 1) # divisor n - 1
return m, s2 / n
def test_rubin_rules_hand_example_exact():
p = rubin_pool([Fraction(1), Fraction(2), Fraction(3)], [Fraction(1, 2)] * 3)
assert p.qbar == 2 and p.w == Fraction(1, 2) and p.b == 1
assert p.t == Fraction(11, 6) and p.r == Fraction(8, 3) and p.lam == Fraction(8, 11)
assert abs(p.df - 121 / 32) < 1e-12 # (m - 1)(1 + 1/r)^2 = 2 (11/8)^2
def test_no_between_variance():
p = rubin_pool([1.5, 1.5, 1.5, 1.5], [0.2, 0.3, 0.1, 0.2])
assert p.b == 0 and abs(p.t - 0.2) < 1e-15 and math.isinf(p.df)
lo, hi = pooled_interval(p)
assert abs(hi - 1.5 - norm_ppf(0.975) * math.sqrt(0.2)) < 1e-12
def test_barnard_rubin_df_limits():
rng = random.Random(1)
for _ in range(200):
m = rng.randint(2, 30)
qs = [rng.gauss(0, 1) for _ in range(m)]
us = [rng.uniform(0.1, 2) for _ in range(m)]
rub = rubin_pool(qs, us)
for nu in (5, 30, 1000):
br = rubin_pool(qs, us, df_com=nu)
assert br.df <= rub.df + 1e-9 and br.df <= nu
big = rubin_pool(qs, us, df_com=1e12)
assert abs(big.df - rub.df) <= 1e-6 * rub.df
def test_interval_uses_t_quantile():
p = rubin_pool([1.0, 2.0, 4.0], [0.5, 0.5, 0.5])
lo, hi = pooled_interval(p, 0.9)
assert abs((hi - lo) / 2 - t_ppf(0.95, p.df) * math.sqrt(p.t)) < 1e-12
def test_observed_values_never_change():
rng = random.Random(2)
x = [[1.0, rng.gauss(0, 1)] for _ in range(30)]
y = [1 + 2 * r[1] + rng.gauss(0, 1) if i % 3 else None for i, r in enumerate(x)]
for _ in range(5):
yc = impute_normal_regression(y, x, rng)
assert all(a == b for a, b in zip(y, yc) if a is not None)
assert all(v is not None for v in yc)
def test_draws_match_posterior_predictive_moments():
# y* | data is t with mean x0' beta-hat and variance RSS/(n_obs - p - 2) (1 + x0' V x0).
xo = [[1.0, v] for v in (0, 1, 2, 3, 4, 5, 6, 8, 9, 11)]
yo = [1.2, 2.9, 5.3, 6.8, 9.4, 10.6, 13.5, 17.1, 18.7, 23.4]
x0 = [1.0, 7.0]
beta, rss, v, dfr = regression_posterior(xo, yo)
mean = beta[0] + 7 * beta[1]
quad = sum(x0[i] * v[i][j] * x0[j] for i in range(2) for j in range(2))
var = rss / (dfr - 2) * (1 + quad)
rng = random.Random(3)
r = 20000
draws = [impute_normal_regression(yo + [None], xo + [x0], rng)[-1] for _ in range(r)]
dm = sum(draws) / r
dv = sum((d - dm) ** 2 for d in draws) / (r - 1)
assert abs(dm - mean) < 4 * math.sqrt(var / r)
assert abs(dv / var - 1) < 0.06
def mar_sample(rng, n):
x, y = [], []
for _ in range(n):
u = rng.gauss(0, 1)
v = 1 + 2 * u + rng.gauss(0, 1)
p_miss = 1 / (1 + math.exp(-(-0.5 + 1.5 * u))) # depends on x only: MAR
x.append([1.0, u])
y.append(None if rng.random() < p_miss else v)
return x, y
def test_coverage_under_mar_measured():
# Measured, not proved. Target: E y = 1.
rng = random.Random(4)
reps, n = 200, 200
z = norm_ppf(0.975)
hit_mi = hit_cc = hit_si = 0
for rep in range(reps):
x, y = mar_sample(rng, n)
pooled, _ = multiple_imputation(y, x, mean_analysis, m=10, seed=rep)
lo, hi = pooled_interval(pooled)
hit_mi += lo <= 1 <= hi
obs = [v for v in y if v is not None]
m, u = mean_analysis(None, obs)
hit_cc += abs(m - 1) <= z * math.sqrt(u)
beta, _, _, _ = regression_posterior([x[i] for i, v in enumerate(y) if v is not None], obs)
filled = [v if v is not None else beta[0] + beta[1] * r[1] for v, r in zip(y, x)]
m, u = mean_analysis(None, filled)
hit_si += abs(m - 1) <= z * math.sqrt(u)
assert abs(hit_mi / reps - 0.95) < 0.05
assert hit_cc / reps < 0.5 # complete cases are biased under this MAR mechanism
assert hit_si / reps < hit_mi / reps # single imputation understates the variance
Exercises
- Show that when all imputations are equal, and the method reduces to the analysis of one completed data set. Answer. Equal data sets give equal , so and , the common .
- Given and for all , compute , , and . Answer. ; the deviations are , so . Then , , and .
- Prove that the Barnard-Rubin is at most . Answer. is larger than each term, so and . And since and .
- Explain why imputing the conditional mean for a missing outcome gives an unbiased estimate of under MAR on but a wrong estimate of . Answer. The regression line is correct under MAR on , so the mean of the predictions estimates . But each imputed value has no residual, so the completed data have variance that misses for the imputed fraction, and is too small.
- With , how many imputations make the efficiency at least 0.99? Answer. means , so , and .
References
- Donald B. Rubin, Multiple Imputation for Nonresponse in Surveys, Wiley, 1987, Chapter 3 (the Bayesian derivation of the combining rules and the t reference distribution) and Chapter 4 (randomization-based evaluation, proper imputation)
- John Barnard and Donald B. Rubin, Small-sample degrees of freedom with multiple imputation, Biometrika 86(4), 1999, pp. 948 to 955 (degrees of freedom that never exceed the complete-data degrees of freedom)
- Roderick J. A. Little and Donald B. Rubin, Statistical Analysis with Missing Data, third edition, Wiley, 2019, Chapter 10 (Bayes and multiple imputation)
- Stef van Buuren, Flexible Imputation of Missing Data, second edition, CRC Press, 2018, Chapter 2 (the pooling rules and the fraction of missing information) and Chapter 3 (Bayesian normal linear imputation)
Where this leads
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 W9KZM4 Edit this page History Report an error Markdown