Algorithm Search⌘K

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
Properties
randomizednot exactofflineiterative
Origin
S. van Buuren, H. C. Boshuizen, D. L. Knook, 1999

Multiple imputation by chained equations (MICE) makes the mm 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 mm tables. The mm 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 YY with nn rows and pp numeric columns, in which some entries are missing, a number of imputations m≥2m \ge 2 and a number of sweeps T≥1T \ge 1. For a column jj, OjO_j is the set of rows where YijY_{ij} is observed and MjM_j the set where it is missing. The qq incomplete columns are those with Mj≠∅M_j \ne \emptyset. For each of them the user chooses a conditional model; here it is the normal linear regression of column jj on a constant and the other p−1p - 1 columns, with the prior π(β,σ2)∝1/σ2\pi(\beta, \sigma^2) \propto 1/\sigma^2.

The output is mm completed tables. Each one agrees with YY 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 ∣Oj∣>p|O_j| > p for every incomplete column and regressions of full rank.

The algorithm

  1. MICE(Y, m, T)
  2. 1for l ← 1 to m do
  3. 2fill each missing entry with a random observed value of its column
  4. 3for t ← 1 to T do
  5. 4for each incomplete column j, from left to right do
  6. 5draw (β*, σ*) from the posterior of the regression of column j on the other columns, rows O_j
  7. 6for 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
  8. 7store the completed table as imputation l
  9. 8return the m completed tables

Line L5 fits ordinary least squares to the rows of OjO_j, 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 σ∗2=RSS/c\sigma^{*2} = \mathrm{RSS}/c with c∼χ∣Oj∣−p2c \sim \chi^2_{|O_j| - p} and β∗=β^+σ∗Lu\beta^* = \hat\beta + \sigma^* L u with LLT=(XTX)−1LL^{\mathsf T} = (X^{\mathsf T}X)^{-1} and uu 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 jj, 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 TT 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 xiTβ∗x_i^{\mathsf T}\beta^*, finds the 5 observed rows of the column whose fitted values xkTβ^x_k^{\mathsf T}\hat\beta are closest to it, and copies the observed value of one of them at random.

Example

The table has n=200n = 200 rows and three columns (y,x,z)(y, x, z), generated by z∼N(0,1)z \sim N(0, 1), x=0.5z+e1x = 0.5z + e_1 and y=1+x−2z+e2y = 1 + x - 2z + e_2 with independent standard normal e1,e2e_1, e_2. The value yy is missing with probability 1/(1+e0.8−1.5z)1/(1 + e^{0.8 - 1.5z}) and xx with probability 1/(1+e1.2+z)1/(1 + e^{1.2 + z}), so the missingness depends only on the complete column zz, which is missing at random. In the data set used here (seed 1 of Python's random.Random), 77 values of yy and 45 values of xx are missing, 8 rows miss both, and 86 rows are complete. Rows with large zz often lose yy, and those rows have small yy, so the mean of the observed yy is 1.2451.245, while the mean of all 200 values before deletion is 0.6320.632.

The table shows the mean of the 77 imputed yy 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 1.2571.257 in the first run, the mean of the observed values. One sweep moves it to about −0.3-0.3, 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 0.0530.053 −0.454-0.454 −0.425-0.425 −0.512-0.512 −0.216-0.216 −0.290-0.290 −0.206-0.206 −0.312-0.312
chain 2 −0.339-0.339 −0.774-0.774 −0.612-0.612 −0.435-0.435 −0.465-0.465 −0.270-0.270 −0.770-0.770 −0.274-0.274
chain 3 −0.385-0.385 −0.170-0.170 −0.115-0.115 −0.554-0.554 −0.533-0.533 −0.266-0.266 −0.107-0.107 −0.479-0.479

With m=5m = 5 and T=10T = 10, the five estimates of the mean of yy are 0.6530.653, 0.7180.718, 0.8370.837, 0.6410.641 and 0.5530.553. Rubin's rules give Qˉ=0.680\bar Q = 0.680, W=0.0178W = 0.0178, B=0.0111B = 0.0111, the total variance W+(1+1/m)B=0.0312W + (1 + 1/m)B = 0.0312 and ν=21.9\nu = 21.9, so the 95% interval is (0.314,1.047)(0.314, 1.047). The interval from the observed yy alone is 1.245±0.321.245 \pm 0.32, which misses the true mean 11. For the coefficient of xx in the regression of yy on xx and zz, the pooled estimate is 0.8440.844 with interval (0.532,1.156)(0.532, 1.156); here BB is larger than WW, the fraction of the variance due to the missing data is 0.730.73, and ν\nu is only 7.57.5.

The next table is measured, not proved. It repeats the setup for 300 data sets (m=5m = 5, T=5T = 5) and gives the mean error of the estimate and the coverage of the nominal 95% interval for the mean of yy and for the coefficient of xx. The complete-case mean uses all observed yy; the complete-case regression uses the rows where yy and xx are both observed. The Monte Carlo standard error of a coverage near 0.950.95 is about 0.0130.013.

method mean of yy: bias mean of yy: coverage coefficient of xx: bias coefficient of xx: coverage
MICE, normal draws 0.0020.002 0.9630.963 −0.005-0.005 0.9400.940
MICE, predictive mean matching 0.0580.058 0.9000.900 −0.064-0.064 0.8930.893
complete cases 0.5880.588 0.0630.063 0.0000.000 0.9600.960

Three things show. Complete cases fail badly for the mean. They are fine for the regression coefficient, because the missingness depends only on zz, which is in the regression. Predictive mean matching is biased here: the missing yy 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 mTqmTq regression draws. Line L5 draws exactly from the posterior of the normal linear model with the prior 1/σ21/\sigma^2. If only one column is incomplete, every stored table is an exact and independent posterior predictive draw for any T≥1T \ge 1, 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 YY has nn rows and pp columns. For a column jj, OjO_j is the set of rows where YijY_{ij} is observed and MjM_j the set of rows where it is missing; the incomplete columns are the qq columns with Mj≠∅M_j \ne \emptyset. The regression of column jj has the design matrix X(j)X^{(j)} with a constant column and the p−1p - 1 other columns, so it has pp coefficients. The preconditions are: for every incomplete column, ∣Oj∣>p|O_j| > p, and the rows of X(j)X^{(j)} in OjO_j 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 YijY_{ij} equal to the observed value for every jj and every i∈Oji \in O_j.

Proof. The working table starts as a copy of the data. Only two lines write to it. Line L2 writes the entries (i,j)(i, j) with i∈Mji \in M_j, and line L6 writes the entries (i,j)(i, j) with i∈Mji \in M_j for the current column jj. No line writes an entry with i∈Oji \in O_j. □\square

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 i∈Mji \in M_j a value from the observed values of column jj, which exist because ∣Oj∣>p≥1|O_j| > p \ge 1. The other entries are observed. Line L6 replaces a number with the real number xiTβ∗+σ∗zx_i^{\mathsf T}\beta^* + \sigma^* z. No line writes a missing marker. □\square

Lemma 3 (the draw of line L5 is the exact posterior of a normal linear model). Let y∈Rky \in \mathbb R^{k} and X∈Rk×pX \in \mathbb R^{k \times p} have full column rank with k>pk > p. Put β^=(XTX)−1XTy\hat\beta = (X^{\mathsf T}X)^{-1}X^{\mathsf T}y and RSS=∥y−Xβ^∥2\mathrm{RSS} = \lVert y - X\hat\beta\rVert^2. Under the model y∣β,σ∼N(Xβ,σ2Ik)y \mid \beta, \sigma \sim N(X\beta, \sigma^2 I_k) with the prior density π(β,σ2)∝1/σ2\pi(\beta, \sigma^2) \propto 1/\sigma^2, the posterior is given by σ2=RSS/c\sigma^2 = \mathrm{RSS}/c with c∼χk−p2c \sim \chi^2_{k-p}, and then β∣σ2∼N(β^,σ2(XTX)−1)\beta \mid \sigma^2 \sim N(\hat\beta, \sigma^2(X^{\mathsf T}X)^{-1}). The step of line L5 draws cc as twice a Gamma variate with shape (k−p)/2(k - p)/2 and β∗=β^+σ∗Lz\beta^* = \hat\beta + \sigma^* L z with LLT=(XTX)−1LL^{\mathsf T} = (X^{\mathsf T}X)^{-1} and zz standard normal, so it draws from this posterior.

Proof. The identity ∥y−Xβ∥2=RSS+(β−β^)TXTX(β−β^)\lVert y - X\beta\rVert^2 = \mathrm{RSS} + (\beta - \hat\beta)^{\mathsf T}X^{\mathsf T}X(\beta - \hat\beta) holds because XT(y−Xβ^)=0X^{\mathsf T}(y - X\hat\beta) = 0. The posterior density is therefore proportional to

(σ2)−k/2−1exp⁡(−RSS2σ2)exp⁡(−(β−β^)TXTX(β−β^)2σ2).(\sigma^2)^{-k/2 - 1}\exp\Bigl(-\frac{\mathrm{RSS}}{2\sigma^2}\Bigr)\exp\Bigl(-\frac{(\beta - \hat\beta)^{\mathsf T}X^{\mathsf T}X(\beta - \hat\beta)}{2\sigma^2}\Bigr).

For fixed σ2\sigma^2, the last factor is the kernel of N(β^,σ2(XTX)−1)N(\hat\beta, \sigma^2(X^{\mathsf T}X)^{-1}), and its integral over β\beta is a constant times (σ2)p/2(\sigma^2)^{p/2}. So the marginal density of σ2\sigma^2 is proportional to (σ2)−(k−p)/2−1exp⁡(−RSS/(2σ2))(\sigma^2)^{-(k-p)/2 - 1}\exp(-\mathrm{RSS}/(2\sigma^2)). The change of variable c=RSS/σ2c = \mathrm{RSS}/\sigma^2 gives a density proportional to c(k−p)/2−1e−c/2c^{(k-p)/2 - 1}e^{-c/2}, which is χk−p2\chi^2_{k-p}. Twice a Gamma variate with shape aa and scale 1 is χ2a2\chi^2_{2a}. The matrix (XTX)−1(X^{\mathsf T}X)^{-1} is positive definite, so its Cholesky factor LL exists, and β^+σ∗Lz\hat\beta + \sigma^* Lz has mean β^\hat\beta and covariance σ∗2LLT\sigma^{*2}LL^{\mathsf T}. □\square

Lemma 4 (one incomplete column gives exact draws for any T). Suppose only column jj is incomplete. Then every visit of lines L5 and L6 draws the missing values of column jj from the posterior predictive law of the model of Lemma 3, fitted to the rows OjO_j 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 T≥1T \ge 1, and the mm tables are independent given the data.

Proof. With q=1q = 1, the predictors of column jj are the other columns, which are complete and never change (Lemma 1). The response values in line L5 are the observed values YijY_{ij}, i∈Oji \in O_j. So the input of line L5 is the same at every visit, and by Lemma 3 the pair (β∗,σ∗)(\beta^*, \sigma^*) is a draw from the posterior. Line L6 then draws Yij=xiTβ∗+σ∗ziY_{ij} = x_i^{\mathsf T}\beta^* + \sigma^* z_i with fresh independent ziz_i, 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 jj is not a predictor of itself. Each sweep and each imputation uses fresh random numbers, so the stored tables are independent draws. □\square

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 jj is one of the observed values YkjY_{kj}, k∈Ojk \in O_j.

Proof. The variant replaces line L6 by a choice among the donors, which are rows of OjO_j, and writes the observed value of the chosen donor. Line L2 also writes observed values. □\square

Theorem (termination, cost and output). The run stops after exactly mTqmTq executions of line L5. It returns mm 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 mm, TT and qq elements, and their bodies have no other loops except the loops over the finite sets MjM_j. So line L5 runs mTqmTq 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 q=1q = 1. ■\blacksquare

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 qq 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 O(np)O(np), forms XTXX^{\mathsf T}X in O(np2)O(np^2), inverts it and takes the Cholesky factor in O(p3)O(p^3), and draws p+1p + 1 random variates. Line L6 costs O(p)O(p) per missing entry, at most O(np)O(np) per column. Lines L5 and L6 run mTqmTq times, so the time is O(mTq(np2+p3))O(mTq(np^2 + p^3)). The line L2 fill costs O(np)O(np) per imputation. The working table and the design take O(np)O(np) space, and the mm stored tables take O(mnp)O(mnp).

The pmm variant also has to find the nearest fitted values. The reference implementation sorts all ∣Oj∣|O_j| distances for each missing entry, which costs O(∣Mj∣ ∣Oj∣log⁡∣Oj∣)O(|M_j|\,|O_j| \log |O_j|) per visit. Sorting the fitted values once and using binary search brings this to O((∣Oj∣+∣Mj∣)log⁡∣Oj∣)O((|O_j| + |M_j|)\log |O_j|).

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 mm 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 m≥5m \ge 5, 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.

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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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
  • a scene preset for the example