Algorithmadvanced
Multiple imputation by chained equations
Also called MICE, fully conditional specification.
Fills each incomplete column in turn with draws from a regression on the other columns, repeats the cycle, and returns m completed tables for Rubin's rules.
- Time
- O(m T q (n p^2 + p^3)) worst
- Space
- O(m n p) extra
- Where
- T = the number of sweeps; m = the number of imputations; n = the number of rows; p = the number of columns; q = the number of incomplete columns
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- S. van Buuren, H. C. Boshuizen, D. L. Knook, 1999
Multiple imputation by chained equations (MICE) makes the completed data sets that multiple imputation needs when more than one column of a table has missing values. It does not specify one joint model for all columns. It specifies one conditional model for each incomplete column, usually a regression on all the other columns, and it imputes the columns one at a time in a cycle. Each step draws the parameters of the regression from their posterior and then draws the missing values from the fitted model, so the imputations carry the uncertainty about the model as well as the noise. After some cycles the current table is stored, and the procedure starts again for the next of the tables. The results are then pooled with Rubin's rules. With only one incomplete column, the method is exact Bayesian regression imputation. With several, it is a heuristic that works well in practice but has no general guarantee.
In plain words
A table has holes in several columns. First, fill every hole with a random value taken from the same column, as a rough start. Then take the first column with holes. Fit a regression that predicts this column from all the others, using only the rows where this column was really seen. Throw away the rough values in this column and put in new values predicted by the fit, with some random noise and some random change to the fit itself. Do the same for the next column with holes, which can now use the better values of the first column. Go around all the columns several times, until the filled values stop drifting. Keep the table. Start again with new random numbers to make the next table. Analyse every table in the usual way and combine the answers.
The problem
The input is a table with rows and numeric columns, in which some entries are missing, a number of imputations and a number of sweeps . For a column , is the set of rows where is observed and the set where it is missing. The incomplete columns are those with . For each of them the user chooses a conditional model; here it is the normal linear regression of column on a constant and the other columns, with the prior .
The output is completed tables. Each one agrees with on every observed entry and has a real number in every missing entry. The tables are the input for an analysis that runs on each and is pooled by Rubin's rules.
The method assumes that the data are missing at random (see missing data mechanism): the chance that an entry is missing may depend on observed entries, but not on the missing value itself. It needs for every incomplete column and regressions of full rank.
The algorithm
MICE(Y, m, T)- 1
for l ← 1 to m do - 2
fill each missing entry with a random observed value of its column - 3
for t ← 1 to T do - 4
for each incomplete column j, from left to right do - 5
draw (β*, σ*) from the posterior of the regression of column j on the other columns, rows O_j - 6
for each row i in M_j do Y_ij ← x_iᵀβ* + σ* z_i ▷ x_i: the other columns of row i, z_i a fresh N(0, 1) draw - 7
store the completed table as imputation l - 8
return the m completed tables
Line L5 fits ordinary least squares to the rows of , with the response taken from the data and the predictors taken from the current table, which holds imputed values from earlier steps. Then it draws with and with and standard normal. Line L6 then draws each missing value from the fitted model. Lines L5 and L6 together are one draw from the posterior predictive distribution of the missing values of column , given the current values of all other columns. The sweep of lines L4 to L6 has the form of one scan of a Gibbs sampler, and the loop of line L3 runs it times so that the effect of the rough start of line L2 goes away.
The pmm variant (predictive mean matching) changes line L6. For each missing row it computes the prediction , finds the 5 observed rows of the column whose fitted values are closest to it, and copies the observed value of one of them at random.
Example
The table has rows and three columns , generated by , and with independent standard normal . The value is missing with probability and with probability , so the missingness depends only on the complete column , which is missing at random. In the data set used here (seed 1 of Python's random.Random), 77 values of and 45 values of are missing, 8 rows miss both, and 86 rows are complete. Rows with large often lose , and those rows have small , so the mean of the observed is , while the mean of all 200 values before deletion is .
The table shows the mean of the 77 imputed values after each sweep, for three independent runs of lines L2 to L6 (seed 3). The random start of line L2 gives a mean of in the first run, the mean of the observed values. One sweep moves it to about , and after that the three chains move around the same level without a trend.
| sweep | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| chain 1 | ||||||||
| chain 2 | ||||||||
| chain 3 |
With and , the five estimates of the mean of are , , , and . Rubin's rules give , , , the total variance and , so the 95% interval is . The interval from the observed alone is , which misses the true mean . For the coefficient of in the regression of on and , the pooled estimate is with interval ; here is larger than , the fraction of the variance due to the missing data is , and is only .
The next table is measured, not proved. It repeats the setup for 300 data sets (, ) and gives the mean error of the estimate and the coverage of the nominal 95% interval for the mean of and for the coefficient of . The complete-case mean uses all observed ; the complete-case regression uses the rows where and are both observed. The Monte Carlo standard error of a coverage near is about .
| method | mean of : bias | mean of : coverage | coefficient of : bias | coefficient of : coverage |
|---|---|---|---|---|
| MICE, normal draws | ||||
| MICE, predictive mean matching | ||||
| complete cases |
Three things show. Complete cases fail badly for the mean. They are fine for the regression coefficient, because the missingness depends only on , which is in the regression. Predictive mean matching is biased here: the missing lie mostly below the observed ones, and matching can only copy observed values.
Correctness
The proof below shows four facts. The observed entries are never changed, and every missing entry is filled after line L2, so the output has the stated form. The run stops after exactly regression draws. Line L5 draws exactly from the posterior of the normal linear model with the prior . If only one column is incomplete, every stored table is an exact and independent posterior predictive draw for any , because the predictors never change; MICE then reduces to the regression imputation on the multiple imputation page.
For two or more incomplete columns, the proof does not show convergence. The conditional models are chosen one by one, and in general no joint distribution has them as its full conditionals. Then the chain is not a Gibbs sampler for any joint model, and its limit, if it has one, can depend on the order of the columns. Liu, Gelman, Hill, Su and Kropko (2014) give conditions under which the limit is close to the right posterior predictive law in large samples when the models are compatible. The good coverage in the example is measured, for one data model.
Proof: MICE keeps the observed data, fills every cell, stops after m T q regressions, and with one incomplete column gives exact posterior predictive drawsfull
Line numbers refer to the main pseudocode. The table has rows and columns. For a column , is the set of rows where is observed and the set of rows where it is missing; the incomplete columns are the columns with . The regression of column has the design matrix with a constant column and the other columns, so it has coefficients. The preconditions are: for every incomplete column, , and the rows of in have full column rank at every visit of line L5. The random numbers are taken to be exact draws from their laws.
Lemma 1 (observed values never change). At every point of the run, the working table has equal to the observed value for every and every .
Proof. The working table starts as a copy of the data. Only two lines write to it. Line L2 writes the entries with , and line L6 writes the entries with for the current column . No line writes an entry with .
Lemma 2 (every cell is filled). After line L2, every entry of the working table is a real number, and this stays true until line L7. So each stored table is complete.
Proof. Line L2 gives each entry with a value from the observed values of column , which exist because . The other entries are observed. Line L6 replaces a number with the real number . No line writes a missing marker.
Lemma 3 (the draw of line L5 is the exact posterior of a normal linear model). Let and have full column rank with . Put and . Under the model with the prior density , the posterior is given by with , and then . The step of line L5 draws as twice a Gamma variate with shape and with and standard normal, so it draws from this posterior.
Proof. The identity holds because . The posterior density is therefore proportional to
For fixed , the last factor is the kernel of , and its integral over is a constant times . So the marginal density of is proportional to . The change of variable gives a density proportional to , which is . Twice a Gamma variate with shape and scale 1 is . The matrix is positive definite, so its Cholesky factor exists, and has mean and covariance .
Lemma 4 (one incomplete column gives exact draws for any T). Suppose only column is incomplete. Then every visit of lines L5 and L6 draws the missing values of column from the posterior predictive law of the model of Lemma 3, fitted to the rows with the other columns as predictors. This law does not depend on the initial fill of line L2 or on the sweep number. So each stored table is one exact posterior predictive draw for every , and the tables are independent given the data.
Proof. With , the predictors of column are the other columns, which are complete and never change (Lemma 1). The response values in line L5 are the observed values , . So the input of line L5 is the same at every visit, and by Lemma 3 the pair is a draw from the posterior. Line L6 then draws with fresh independent , which is a draw from the posterior predictive law of the missing responses: first the parameters from the posterior, then the data from the model. The values written in line L2 are overwritten in the first sweep and are never read as predictors, because column is not a predictor of itself. Each sweep and each imputation uses fresh random numbers, so the stored tables are independent draws.
Lemma 4 says that for one incomplete column MICE is the same procedure as normal linear regression imputation on the multiple imputation page, and the extra sweeps only cost time.
Lemma 5 (predictive mean matching imputes observed values). In the pmm variant, every value written for column is one of the observed values , .
Proof. The variant replaces line L6 by a choice among the donors, which are rows of , and writes the observed value of the chosen donor. Line L2 also writes observed values.
Theorem (termination, cost and output). The run stops after exactly executions of line L5. It returns complete tables, each equal to the data on all observed entries. If the table has one incomplete column, each returned table is an exact and independent draw of the missing values from the posterior predictive law of the normal linear regression model with the prior of Lemma 3.
Proof. The loops of lines L1, L3 and L4 have fixed ranges of , and elements, and their bodies have no other loops except the loops over the finite sets . So line L5 runs times and the run stops. Lemmas 1 and 2 give the form of the output, and Lemma 4 gives the law of the output when .
What is not proved. For two or more incomplete columns, the sweep of lines L3 to L6 defines a Markov chain on the missing values, and each conditional draw is exact given the current values of the other columns. But the regression models are specified one at a time, and in general there is no joint distribution whose full conditionals they are. Then the chain is not a Gibbs sampler for any joint model, its stationary law can depend on the visiting order, and nothing above shows that it converges or what it converges to. When the conditional models are compatible with one joint model, Liu, Gelman, Hill, Su and Kropko (2014) give conditions under which the stationary law of such an iterative imputation is close to the posterior predictive law of that joint model in large samples. This page does not prove that result. The measured coverage on the main page is evidence for one data model only.
Complexity
One visit of line L5 builds the design in , forms in , inverts it and takes the Cholesky factor in , and draws random variates. Line L6 costs per missing entry, at most per column. Lines L5 and L6 run times, so the time is . The line L2 fill costs per imputation. The working table and the design take space, and the stored tables take .
The pmm variant also has to find the nearest fitted values. The reference implementation sorts all distances for each missing entry, which costs per visit. Sorting the fitted values once and using binary search brings this to .
Properties
- Observed data are kept. Every completed table agrees with the data on the observed entries.
- Randomized. The output depends on the random numbers. A fixed seed makes it reproducible, and different seeds give different but equally valid sets of imputations.
- Proper for one incomplete column. The parameters are drawn from their posterior before each set of missing values, so the between-imputation variance includes the uncertainty about the regression. This is what makes Rubin's rules give valid intervals.
- Flexible by column. Each column can have its own model: linear regression for a continuous column, logistic regression for a binary one, matching for a skewed one. This is the main reason MICE is used instead of a joint model.
- No joint model in general. The method is defined by the conditional models alone, and they need not fit together.
- Embarrassingly parallel. The chains are independent and can run at the same time.
Variants and improvements
- Predictive mean matching. Copy the observed value of a donor with a close predicted mean. The imputations are always plausible values, such as integers or values in range, and the method is robust to some departures from normality. It cannot impute outside the range of the observed values.
- Other conditional models. Use logistic regression for binary columns, multinomial or ordinal models for categorical ones, and classification and regression trees or random forests when the relations are nonlinear. The parameters must still be drawn from an approximate posterior, often by a bootstrap of the rows.
- Passive imputation. A derived column, such as a sum score or a ratio, is recomputed from its parts after each step instead of being imputed, so that it stays consistent with them.
- Predictor selection. With many columns, each regression uses only the columns that are correlated with the target or with its missingness. This keeps the regressions small and of full rank.
- Joint modelling. Draw all missing values from one multivariate model, for example the multivariate normal by data augmentation. It has a clear theory but is less flexible for mixed column types. For multivariate normal data, MICE with linear regressions uses conditionals that are compatible with that joint model.
- Monotone patterns. If the columns can be ordered so that a missing entry in one column implies a missing entry in all later columns, a single pass in that order, where each column is regressed only on the earlier columns, needs no iteration.
When to use it
Use MICE when several columns of a data set have missing values, the data can be taken to be missing at random, and the columns are of different types, so that no single joint model is natural. It is the standard tool for this in medical and social science data. Include in the imputation models every variable of the later analysis, including the outcome, and any variable that predicts the missingness. If only one column is incomplete, the iteration is not needed, and plain regression imputation gives the same result. If the missingness depends on the missing values themselves, MICE alone does not remove the bias; a sensitivity analysis or a model for the missingness is needed.
Pitfalls
- Too few sweeps. The chains must forget the rough start. Run several chains and plot the mean and variance of the imputed values against the sweep. A trend, or chains that do not mix, means that more sweeps are needed or that the models are poorly set up.
- Leaving out the outcome. If the outcome of the analysis is not a predictor in the models for the incomplete covariates, the imputed covariates have no relation with the outcome, and the estimated effects are biased toward zero.
- Analysis and imputation models that disagree. If the analysis has interactions or squared terms that the linear imputation models do not contain, the imputed values do not carry these relations. Impute the derived terms as columns of their own or use models that contain them.
- Matching in the tail. Predictive mean matching copies observed values, so it is biased when the missing values lie outside the range of the observed ones, as in the example.
- Collinearity and perfect prediction. A derived column that is a function of other columns makes the regression singular. A binary column that some predictor separates perfectly makes the logistic fit diverge. Remove such predictors or use passive imputation.
- Missing not at random. The method uses only the observed relations between the columns. If the missing values are systematically different from observed values with the same other columns, the imputations are biased in the same way.
- One imputation. A single completed table treats imputed values as data and gives standard errors that are too small. Use , and more when the fraction of missing information is large.
Implementations
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-by-chained-equations/. The authors are listed in prov/XHM517.jsonl.
import math
import random
from collections.abc import Sequence
from typing import NamedTuple
Row = list
Table = list
def _inverse(a: list) -> list:
"""Gauss-Jordan inverse with partial pivoting. Cost O(p^3)."""
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]))
if m[p][c] == 0:
raise ZeroDivisionError("predictors are collinear")
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 _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(max(s, 0.0)) if i == j else s / low[j][j]
return low
def bayes_regression_draw(
x: Sequence[Sequence[float]], y: Sequence[float], rng: random.Random
) -> tuple[list, list, float]:
"""Fit OLS and draw (beta*, sigma*) from the posterior under p(beta, log sigma) = const.
Returns (beta-hat, beta*, sigma*). sigma*^2 = RSS / chi2(n - p) and
beta* ~ N(beta-hat, sigma*^2 (X'X)^-1). Precondition: n > p and X of full
column rank. Cost O(n p^2 + p^3).
"""
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))
sigma2 = rss / (2.0 * rng.gammavariate((len(y) - p) / 2.0, 1.0))
low = _cholesky(v)
z = [rng.gauss(0.0, 1.0) for _ in range(p)]
s = math.sqrt(sigma2)
bstar = [beta[i] + s * sum(low[i][j] * z[j] for j in range(i + 1)) for i in range(p)]
return beta, bstar, s
class MiceResult(NamedTuple):
imputations: list # m completed tables (lists of rows)
chain_means: list # chain_means[l][t][j]: mean of the imputed values of column j after sweep t
def mice(
data: Sequence[Sequence[float | None]],
m: int = 5,
iters: int = 10,
seed: int = 0,
method: str = "norm",
donors: int = 5,
) -> MiceResult:
"""Multiple imputation by chained equations for numeric columns.
data is a table of n rows and p columns with None for a missing value.
Each incomplete column, from left to right, is imputed from a Bayesian
linear regression on all other columns (with an intercept), using their
current values. method "norm" draws y* = x'beta* + sigma* z; method "pmm"
takes the observed value of one of the `donors` observed rows whose
predicted mean x'beta-hat is closest to x'beta*. Observed values never change.
Precondition: every column has more than p observed values and the
regressions have full rank. Cost: O(m iters q (n p^2 + p^3)) for q incomplete columns.
"""
rng = random.Random(seed)
n, p = len(data), len(data[0])
miss = [[i for i in range(n) if data[i][j] is None] for j in range(p)]
obs = [[i for i in range(n) if data[i][j] is not None] for j in range(p)]
todo = [j for j in range(p) if miss[j]]
sets, traces = [], []
for _ in range(m): # @line L1
cur = [list(r) for r in data]
for j in todo: # @line L2
pool = [data[i][j] for i in obs[j]]
for i in miss[j]:
cur[i][j] = rng.choice(pool)
trace = []
for _t in range(iters): # @line L3
for j in todo: # @line L4
design = [[1.0] + [cur[i][k] for k in range(p) if k != j] for i in range(n)]
xo = [design[i] for i in obs[j]]
yo = [data[i][j] for i in obs[j]]
beta, bstar, s = bayes_regression_draw(xo, yo, rng) # @line L5
if method == "norm":
for i in miss[j]:
cur[i][j] = sum(b * c for b, c in zip(bstar, design[i])) + s * rng.gauss(0.0, 1.0) # @line L6
elif method == "pmm":
pred_obs = [sum(b * c for b, c in zip(beta, r)) for r in xo]
for i in miss[j]:
target = sum(b * c for b, c in zip(bstar, design[i]))
near = sorted(range(len(yo)), key=lambda k: (abs(pred_obs[k] - target), k))[:donors]
cur[i][j] = yo[rng.choice(near)]
else:
raise ValueError("method must be 'norm' or 'pmm'")
trace.append([sum(cur[i][j] for i in miss[j]) / len(miss[j]) if miss[j] else None for j in range(p)])
sets.append(cur) # @line L7
traces.append(trace)
return MiceResult(sets, traces) # @line L8
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_by_chained_equations.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multiple-imputation-by-chained-equations/. The authors are listed in prov/XHM517.jsonl.
import math
import random
from fractions import Fraction
from multiple_imputation_by_chained_equations import bayes_regression_draw, mice
from stdist import t_ppf
def exact_ols(x, y):
"""Normal equations solved in exact rational arithmetic; returns (beta, (X'X)^-1, rss)."""
p = len(x[0])
fx = [[Fraction(v) for v in r] for r in x]
fy = [Fraction(v) for v in y]
a = [[sum(r[i] * r[j] for r in fx) for j in range(p)] + [Fraction(int(i == j)) for j in range(p)] for i in range(p)]
for c in range(p):
piv = next(r for r in range(c, p) if a[r][c] != 0)
a[c], a[piv] = a[piv], a[c]
pv = a[c][c]
a[c] = [v / pv for v in a[c]]
for r in range(p):
if r != c:
f = a[r][c]
a[r] = [u - f * v for u, v in zip(a[r], a[c])]
inv = [row[p:] for row in a]
xty = [sum(r[i] * yi for r, yi in zip(fx, fy)) for i in range(p)]
beta = [sum(inv[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(fx, fy))
return [float(b) for b in beta], [[float(v) for v in row] for row in inv], float(rss)
def make_table(seed, n, miss_cols=(0,), rate=0.3):
rng = random.Random(seed)
rows = []
for _ in range(n):
z = rng.gauss(0, 1)
x = 0.5 * z + rng.gauss(0, 1)
y = 1 + x - z + rng.gauss(0, 1)
rows.append([y, x, z])
for r in rows:
for j in miss_cols:
if rng.random() < rate:
r[j] = None
return rows
def test_one_incomplete_column_is_single_bayesian_regression_imputation():
data = make_table(1, 40)
res = mice(data, m=1, iters=1, seed=99)
# reference: same random stream, independent arithmetic
rng = random.Random(99)
miss = [i for i, r in enumerate(data) if r[0] is None]
obs = [i for i, r in enumerate(data) if r[0] is not None]
pool = [data[i][0] for i in obs]
for _ in miss:
rng.choice(pool)
x = [[1.0, data[i][1], data[i][2]] for i in obs]
beta, inv, rss = exact_ols(x, [data[i][0] for i in obs])
s2 = rss / (2.0 * rng.gammavariate((len(obs) - 3) / 2.0, 1.0))
low = [[0.0] * 3 for _ in range(3)]
for i in range(3):
for j in range(i + 1):
t = inv[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
low[i][j] = math.sqrt(t) if i == j else t / low[j][j]
zs = [rng.gauss(0, 1) for _ in range(3)]
bstar = [beta[i] + math.sqrt(s2) * sum(low[i][j] * zs[j] for j in range(3)) for i in range(3)]
for i in miss:
expect = bstar[0] + bstar[1] * data[i][1] + bstar[2] * data[i][2] + math.sqrt(s2) * rng.gauss(0, 1)
assert abs(res.imputations[0][i][0] - expect) < 1e-9
def test_observed_values_kept_and_all_filled():
data = make_table(2, 60, miss_cols=(0, 1, 2), rate=0.2)
for method in ("norm", "pmm"):
res = mice(data, m=3, iters=4, seed=5, method=method)
assert len(res.imputations) == 3 and len(res.chain_means[0]) == 4
for table in res.imputations:
for r0, r1 in zip(data, table):
assert all(v is not None for v in r1)
assert all(a == b for a, b in zip(r0, r1) if a is not None)
def test_pmm_imputes_only_observed_values():
data = make_table(3, 50, miss_cols=(0, 1), rate=0.3)
res = mice(data, m=2, iters=3, seed=6, method="pmm")
for j in (0, 1):
seen = {r[j] for r in data if r[j] is not None}
for table in res.imputations:
assert all(table[i][j] in seen for i in range(len(data)) if data[i][j] is None)
def test_posterior_draw_moments():
rng = random.Random(7)
x = [[1.0, float(v)] for v in range(12)]
y = [0.5 + 0.8 * v + rng.gauss(0, 1) for v in range(12)]
beta, inv, rss = exact_ols(x, y)
r = 20000
draws = [bayes_regression_draw(x, y, rng) for _ in range(r)]
s2 = [d[2] ** 2 for d in draws]
assert abs(sum(s2) / r / (rss / (12 - 2 - 2)) - 1) < 0.03 # E sigma^2 = RSS / (n - p - 2)
for k in range(2):
mk = sum(d[1][k] for d in draws) / r
sd = math.sqrt(rss / 8 * inv[k][k])
assert abs(mk - beta[k]) < 4 * sd / math.sqrt(r)
assert abs(draws[0][0][k] - beta[k]) < 1e-9
def pool(qs, us):
m = len(qs)
qbar = sum(qs) / m
w = sum(us) / m
b = sum((q - qbar) ** 2 for q in qs) / (m - 1)
t = w + (1 + 1 / m) * b
df = (m - 1) * (1 + w / ((1 + 1 / m) * b)) ** 2
return qbar, t, df
def test_coverage_two_incomplete_columns_measured():
# Measured, not proved. y and x both incomplete, missingness depends on z (MAR).
rng = random.Random(8)
reps, n = 60, 150
hits_mean = hits_slope = cc_hits = 0
for rep in range(reps):
rows = []
for _ in range(n):
z = rng.gauss(0, 1)
x = 0.5 * z + rng.gauss(0, 1)
y = 1 + x - 2 * z + rng.gauss(0, 1)
py =1 / (1 + math.exp(-(-0.8 + 1.5 * z)))
px = 1 / (1 + math.exp(-(-1.2 - 1.0 * z)))
rows.append([None if rng.random() < py else y, None if rng.random() < px else x, z])
res = mice(rows, m=5, iters=5, seed=rep)
qs, us, qs2, us2 = [], [], [], []
for t in res.imputations:
ys = [r[0] for r in t]
my = sum(ys) / n
qs.append(my)
us.append(sum((v - my) ** 2 for v in ys) / (n - 1) / n)
beta, inv, rss = exact_ols([[1.0, r[1], r[2]] for r in t], ys)
qs2.append(beta[1])
us2.append(rss / (n - 3) * inv[1][1])
qbar, tv, df = pool(qs, us)
hits_mean += abs(qbar - 1) <= t_ppf(0.975, df) * math.sqrt(tv)
qbar, tv, df = pool(qs2, us2)
hits_slope += abs(qbar - 1) <= t_ppf(0.975, df) * math.sqrt(tv)
obs_y = [r[0] for r in rows if r[0] is not None]
mc = sum(obs_y) / len(obs_y)
se = math.sqrt(sum((v - mc) ** 2 for v in obs_y) / (len(obs_y) - 1) / len(obs_y))
cc_hits += abs(mc - 1) <= 1.96 * se
assert hits_mean / reps > 0.85 and hits_slope / reps > 0.85
assert cc_hits / reps < 0.5
History
Van Buuren, Boshuizen and Knook (1999) used a cycle of one regression model per incomplete variable to impute missing blood pressure values in a survival analysis of older people, and published software under the name MICE. Raghunathan, Lepkowski, Van Hoewyk and Solenberger (2001) gave the same idea as sequential regression multivariate imputation for survey data. Van Buuren, Brand, Groothuis-Oudshoorn and Rubin (2006) introduced the name fully conditional specification, showed by simulation that incompatible models often do little harm, and compared it with joint modelling. The R package mice, described by van Buuren and Groothuis-Oudshoorn (2011), made the method the most widely used form of multiple imputation. Liu, Gelman, Hill, Su and Kropko (2014) studied the stationary distribution of such iterative imputations.
References
- S. van Buuren and K. Groothuis-Oudshoorn, mice, Multivariate imputation by chained equations in R, Journal of Statistical Software 45(3), 2011, pages 1 to 67 (the algorithm, the univariate imputation methods including predictive mean matching, passive imputation, predictor selection and convergence checks)
- S. van Buuren, J. P. L. Brand, C. G. M. Groothuis-Oudshoorn and D. B. Rubin, Fully conditional specification in multivariate imputation, Journal of Statistical Computation and Simulation 76(12), 2006, pages 1049 to 1064 (compatible and incompatible conditional models, and simulations of their effect)
- S. van Buuren, H. C. Boshuizen and D. L. Knook, Multiple imputation of missing blood pressure covariates in survival analysis, Statistics in Medicine 18(6), 1999, pages 681 to 694 (the chained regression imputation of the covariates)
- T. E. Raghunathan, J. M. Lepkowski, J. Van Hoewyk and P. Solenberger, A multivariate technique for multiply imputing missing values using a sequence of regression models, Survey Methodology 27(1), 2001, pages 85 to 95 (sequential regression multivariate imputation)
- S. van Buuren, Flexible Imputation of Missing Data, second edition, CRC Press, 2018, Chapter 3 (univariate imputation, Bayesian regression draws and predictive mean matching) and Chapter 4 (multivariate missing data and fully conditional specification)
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag XHM517 Edit this page History Report an error Markdown