Algorithm Search⌘K

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 mm times to get mm completed data sets. Second, run the analysis you would run on complete data on each of them. Third, combine the mm estimates and their variances with Rubin's rules: the point estimate is the mean Qˉ\bar Q, and the variance T=W+(1+1/m)BT = W + (1 + 1/m)B 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, Qˉ\bar Q is consistent and the interval Qˉ±tνT\bar Q \pm t_\nu\sqrt T 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 QQ of a scalar and a variance UU, with (Q−θ)/U(Q - \theta)/\sqrt U close to normal, as for means, regression coefficients and log odds ratios. Rubin's rules use only QQ and UU.
  • The imputation model includes every variable in the analysis, the outcome too, and any variable that predicts missingness.

The template

  1. MULTIPLE-IMPUTATION(Y_obs, m)
  2. 1for j ← 1 to m do
  3. 2fit IMPUTATION-MODEL on the rows with y observed ▷ hole: normal regression of y on x
  4. 3draw σ*² from its posterior ▷ proper: a draw, not the estimate
  5. 4draw β* from its posterior given σ*²
  6. 5each missing y_i ← x_i'β* + σ* z_i, z_i ~ N(0, 1) ▷ observed values stay as they are
  7. 6(Q_j, U_j) ← ANALYSIS(completed data set j) ▷ hole: the complete-data method
  8. 7Q̄ ← (1/m) Σ_j Q_j; W ← (1/m) Σ_j U_j; B ← (1/(m-1)) Σ_j (Q_j - Q̄)²
  9. 8T ← W + (1 + 1/m) B
  10. 9return 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 p(β,log⁡σ)∝1p(\beta, \log\sigma) \propto 1, fitted on nobsn_{\text{obs}} rows with pp predictors, line L3 draws σ∗2=RSS/χnobs−p2\sigma_*^2 = \text{RSS}/\chi^2_{n_{\text{obs}} - p} and line L4 draws β∗∼N(β^,σ∗2(XobsTXobs)−1)\beta_* \sim N(\hat\beta, \sigma_*^2(X_{\text{obs}}^{\mathsf T}X_{\text{obs}})^{-1}). The imputed value then has the exact posterior predictive distribution, a t law centered at xiTβ^x_i^{\mathsf T}\hat\beta.

Why the draws must include the parameters. If line L5 used β^\hat\beta and σ^\hat\sigma in place of the draws, the imputations would show the noise around the fitted line but not the uncertainty of the line itself. BB would then be too small, and so would TT. Rubin calls imputations that include this uncertainty proper.

Where TT comes from. Think of θ\theta 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,

E[θ∣Yobs]=E[E[θ∣Yobs,Ymis]],Var⁡[θ∣Yobs]=E[Var⁡[θ∣Yobs,Ymis]]+Var⁡[E[θ∣Yobs,Ymis]].\mathbb{E}[\theta \mid Y_{\text{obs}}] = \mathbb{E}\big[\mathbb{E}[\theta \mid Y_{\text{obs}}, Y_{\text{mis}}]\big], \qquad \operatorname{Var}[\theta \mid Y_{\text{obs}}] = \mathbb{E}\big[\operatorname{Var}[\theta \mid Y_{\text{obs}}, Y_{\text{mis}}]\big] + \operatorname{Var}\big[\mathbb{E}[\theta \mid Y_{\text{obs}}, Y_{\text{mis}}]\big].

With QjQ_j and UjU_j as the completed-data posterior mean and variance, Qˉ\bar Q and WW estimate the first terms and BB estimates the last one. The factor 1+1/m1 + 1/m accounts for estimating E[θ∣Yobs]\mathbb{E}[\theta \mid Y_{\text{obs}}] by a mean of only mm draws: Var⁡Qˉ=B∞/m\operatorname{Var}\bar Q = B_\infty/m. These two identities are proved. The t reference law in line L9 is an approximation that Rubin (1987) derived for finite mm and large complete-data samples; its accuracy is measured, not proved.

Degrees of freedom. With r=(1+1/m)B/Wr = (1 + 1/m)B/W, the relative increase in variance, and λ=(1+1/m)B/T\lambda = (1 + 1/m)B/T, Rubin's degrees of freedom are

νm=(m−1)(1+1r)2=m−1λ2.\nu_m = (m - 1)\left(1 + \frac1r\right)^2 = \frac{m - 1}{\lambda^2}.

When BB is small, νm\nu_m is very large, even if the complete-data analysis has only a few degrees of freedom νcom\nu_{\text{com}}. Barnard and Rubin (1999) use

ν=(1νm+1ν^obs)−1,ν^obs=νcom+1νcom+3 νcom(1−λ),\nu = \left(\frac1{\nu_m} + \frac1{\hat\nu_{\text{obs}}}\right)^{-1}, \qquad \hat\nu_{\text{obs}} = \frac{\nu_{\text{com}} + 1}{\nu_{\text{com}} + 3}\,\nu_{\text{com}}(1 - \lambda),

which never exceeds νm\nu_m or νcom\nu_{\text{com}} and tends to νm\nu_m as νcom→∞\nu_{\text{com}} \to \infty. When B=0B = 0, νm=∞\nu_m = \infty and the normal quantile is used.

Classic examples

Rubin's rules by hand. Take m=3m = 3 estimates Q=(1,2,3)Q = (1, 2, 3), each with U=1/2U = 1/2. Then Qˉ=2\bar Q = 2, W=1/2W = 1/2, B=1B = 1, T=1/2+(4/3)(1)=11/6T = 1/2 + (4/3)(1) = 11/6, r=8/3r = 8/3, λ=8/11\lambda = 8/11 and νm=2(11/8)2=121/32≈3.78\nu_m = 2(11/8)^2 = 121/32 \approx 3.78. The 95% interval is 2±2.84111/6=(−1.85,5.85)2 \pm 2.841\sqrt{11/6} = (-1.85, 5.85). Most of the variance here comes from the disagreement of the imputations.

A mean with MAR outcome. Take x=1,…,12x = 1, \ldots, 12 and y=2.1,3.0,3.8,?,6.2,6.9,?,9.1,?,11.8,?,14.2y = 2.1, 3.0, 3.8, ?, 6.2, 6.9, ?, 9.1, ?, 11.8, ?, 14.2, where yy is missing at x=4,7,9,11x = 4, 7, 9, 11. The analysis is the mean of yy with U=S2/nU = S^2/n (divisor n−1n - 1 in S2S^2). The complete-case mean is 7.1387.138; it is too low because the missing values lie mostly at large xx. Normal regression imputation with m=5m = 5 (seed 1) gave the means 7.6447.644, 7.8547.854, 7.9187.918, 7.8957.895 and 7.8667.866, so Qˉ=7.835\bar Q = 7.835, W=1.318W = 1.318, B=0.0121B = 0.0121 and T=1.332T = 1.332. Rubin's νm\nu_m is about 33800, but the complete-data analysis has νcom=11\nu_{\text{com}} = 11, and the Barnard-Rubin value is 9.329.32. The 95% interval is (5.24,10.43)(5.24, 10.43).

Coverage under MAR, measured. With x∼N(0,1)x \sim N(0, 1), y=1+2x+ey = 1 + 2x + e, e∼N(0,1)e \sim N(0, 1), n=200n = 200, and yy missing with probability 1/(1+e0.5−1.5x)1/(1 + e^{0.5 - 1.5x}) (about 41% missing), the target is Ey=1\mathbb{E}y = 1. Over 1000 data sets, nominal 95%:

Method coverage mean bias mean width
complete cases 0.005 −0.876-0.876 0.718
single regression imputation 0.905 0.001 0.592
multiple imputation, m=2m = 2 0.949 0.000 0.822
multiple imputation, m=5m = 5 0.952 0.001 0.714
multiple imputation, m=20m = 20 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 mm 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 QQ with covariance UU, Qˉ\bar Q and TT have the same form with BB a matrix. Tests of several coefficients use an F reference law with a pooled rr, because BB is poorly estimated for small mm.
  • 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 β^\hat\beta, σ^\hat\sigma 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, TT can be too large.
  • Too few imputations. Rubin's efficiency of Qˉ\bar Q with mm imputations relative to m=∞m = \infty is (1+γ/m)−1(1 + \gamma/m)^{-1}, with γ\gamma the fraction of missing information: 0.943 for γ=0.3\gamma = 0.3, m=5m = 5. This is about the point estimate. Standard errors, p values and their reproducibility need more, often mm 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.

multiple_imputation.pyI0RawGitHub
# 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

  1. Show that when all mm imputations are equal, T=WT = W and the method reduces to the analysis of one completed data set. Answer. Equal data sets give equal QjQ_j, so B=0B = 0 and T=W+0=WT = W + 0 = W, the common UjU_j.
  2. Given Q=(4.1,4.4,3.9,4.3,4.3)Q = (4.1, 4.4, 3.9, 4.3, 4.3) and Uj=0.04U_j = 0.04 for all jj, compute Qˉ\bar Q, BB, TT and νm\nu_m. Answer. Qˉ=4.2\bar Q = 4.2; the deviations are −0.1,0.2,−0.3,0.1,0.1-0.1, 0.2, -0.3, 0.1, 0.1, so B=0.16/4=0.04B = 0.16/4 = 0.04. Then T=0.04+1.2⋅0.04=0.088T = 0.04 + 1.2 \cdot 0.04 = 0.088, r=1.2r = 1.2, and νm=4(1+1/1.2)2=4(11/6)2=13.44\nu_m = 4(1 + 1/1.2)^2 = 4(11/6)^2 = 13.44.
  3. Prove that the Barnard-Rubin ν\nu is at most min⁡(νm,νcom)\min(\nu_m, \nu_{\text{com}}). Answer. ν−1=νm−1+ν^obs−1\nu^{-1} = \nu_m^{-1} + \hat\nu_{\text{obs}}^{-1} is larger than each term, so ν<νm\nu < \nu_m and ν<ν^obs\nu < \hat\nu_{\text{obs}}. And ν^obs≤νcom\hat\nu_{\text{obs}} \le \nu_{\text{com}} since (νcom+1)/(νcom+3)<1(\nu_{\text{com}} + 1)/(\nu_{\text{com}} + 3) < 1 and 1−λ≤11 - \lambda \le 1.
  4. Explain why imputing the conditional mean xiTβ^x_i^{\mathsf T}\hat\beta for a missing outcome gives an unbiased estimate of Ey\mathbb{E}y under MAR on xx but a wrong estimate of Var⁡y\operatorname{Var}y. Answer. The regression line is correct under MAR on xx, so the mean of the predictions estimates E[E(y∣x)]=Ey\mathbb{E}[\mathbb{E}(y \mid x)] = \mathbb{E}y. But each imputed value has no residual, so the completed data have variance that misses σ2\sigma^2 for the imputed fraction, and Var⁡y\operatorname{Var}y is too small.
  5. With γ=0.5\gamma = 0.5, how many imputations make the efficiency at least 0.99? Answer. (1+0.5/m)−1≥0.99(1 + 0.5/m)^{-1} \ge 0.99 means 0.5/m≤1/990.5/m \le 1/99, so m≥49.5m \ge 49.5, and m=50m = 50.

References

  1. 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)
  2. 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)
  3. Roderick J. A. Little and Donald B. Rubin, Statistical Analysis with Missing Data, third edition, Wiley, 2019, Chapter 10 (Bayes and multiple imputation)
  4. 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.

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