Data quality

Missing values: fill them without inventing anything

Every real database has holes: an amount not entered, a date left blank, a code 9999 that means “unknown”. A quick fill hides four traps: it shrinks the spread and invents effects, biases the estimates when the outcome is left out, lets the future fill the past, and turns codes into values. We measure each one on simulated data, then show how our engine avoids them, with the formulas behind each choice, and what no imputation can do.

Four traps, measured

Before any model, the holes in a table get filled, often in a few lines and by habit. The errors do not show: the model runs, the scores look fine, and the coefficients are wrong. On simulated data whose truth is known, the usual shortcuts fall into four traps:

  1. Filling with the mean: with 30% of values missing, 0.70 of the variance remains, and a variable with no effect at all receives a coefficient of 0.87 instead of 0.
  2. Leaving the outcome out of the imputation: the same coefficient is still 0.48 instead of 0.
  3. Learning the fill on every year: the test years shape the values of the training years, and the backtest borrows from the future.
  4. Keeping codes such as 9999 as values: in an income column, one code 999,999 in ten rows is enough to triple the mean.

A value is rarely missing by chance: a claim amount is blank because the claim is still open, an income because the client declined to give it, a sensor reading because the machine was stopped. And an imputation does not recover the missing truth. An imputed value is a plausible value, consistent with what is observed and with the imputation model; it is not the value we believe the person really had. What a good imputation tries to preserve is the shape of the data, its distributions, the relations between variables and the uncertainty, not each individual value; no method guarantees that perfectly.

Trap 1: the mean fill, a spike and a false effect

Replacing every missing value by the mean of the others looks neutral. It is not: the filled values pile up on one point, so the spread of the column shrinks, and so does its link with any other variable. With a share p of values missing completely at random, x the column as it would be complete, x~ the same column filled with the mean and z another, fully observed variable:

Var(x~)≈(1−p)Var(x),ρ(x~,z)≈1−pρ(x,z)
(1)

On a simulated column of 10,000 rows with 30% missing, the standard deviation falls from 0.99 to 0.83 after a mean fill, and 0.70 of the variance remains; our engine keeps 0.99. Worse, in a regression the lost signal moves to the other variables:

  1. a variable x truly drives the outcome;
  2. the mean fill flattens x, and part of its signal is lost;
  3. a variable z, correlated with x but with no effect of its own, picks up what x no longer carries;
  4. the model gives z an effect it does not have.

On simulated data where z has no effect at all (30 data sets of 10,000 rows, 30% of x missing completely at random, averaged), filling x with its mean gives z a coefficient of 0.87 instead of 0: an effect invented by the imputation, which a pricing or scoring model would then carry on every row. That is the answer to “my model works, why care about the imputation?”: the score may look fine while the reasons the model gives are wrong.

The same column filled with the mean and by our engine, against the complete truth
The same column filled with the mean and by our engine, against the complete truth
Coefficient of a variable with no effect after imputing another one, by method
Coefficient of a variable with no effect after imputing another one, by method

Trap 2: the outcome left out of the equations

Many data scientists have learned never to let the outcome near the preprocessing. That rule protects a model meant to score new rows; it does not hold for estimating effects on historical data. There, leaving an observed outcome out of the imputation equations attenuates its relationship with the imputed variables and biases the model fitted afterwards: in the simulation above, 0.48 instead of 0 for the variable with no effect. This never means that the outcome may enter the preparation of a model meant to score new rows. Our engine therefore keeps two sets of equations:

  1. To estimate on history, the outcome enters the imputation equations on the rows where it is known at the valuation date: the coefficient falls to 0.004, against 0.003 when the incomplete rows are simply dropped.
  2. To score a new row, whose outcome is not known yet, the equations are learned without it, so that nothing from the future is ever needed.

Which set is used is declared, never guessed: declaring the outcome selects the history equations; without a declared outcome, the equations learned without it apply.

Trap 3: learning the fill on every year

An imputation is a model, and it follows the same rule as any model: its parameters are learned on the training data only, then frozen and applied to the rest. The most common leak is the simplest one:

  1. Wrong. Compute the median over 2018 to 2025, fill, then split into training (2018 to 2023) and test (2024 and 2025): the test years have already shaped the values of the training years.
  2. Right. Split first; learn statistics, equations and donors on 2018 to 2023 only; freeze them; apply them unchanged to 2024, 2025 and every new row.

Time adds a second trap. In a series, using the value of tomorrow to fill today is acceptable to reconstruct history after the fact, and forbidden to forecast today: rebuilding the past and predicting in real time are two different jobs. Our engine therefore works “as of” a valuation date τ. When the data are dated, every column used declares the date aij at which the value of column j on row i becomes known: from the start, at the date of its row, or at a date recorded in another column; a dated table without that declaration is refused. At the valuation date, the value used is:

x~ij(τ)=xij if aij≤τ,x~ij(τ)=missing if aij>τ
(2)

The outcome follows the same rule: it enters the equations only on the rows where it is already known. Take a claim: accident on 1 January, diagnosis recorded on 5 January, payment on 20 January. For a valuation on 10 January, the diagnosis can be used; the payment, although it is in the file today, is treated as not yet known, whether it is a column to fill or the outcome. When the valuation date is the training cutoff, which is the default, nothing recorded after it is used to fill the past, neither as a value nor as a learned parameter; at an earlier valuation date, the values used are those known then, but the learned parameters come from all the training rows.

One limit remains, and we state it: the random draws of the final imputation share one generator, and the stopping rule of the chained equations is computed on all the imputed rows together, so the imputed past can change when more recent rows are imputed in the same call. This limit is stated, not yet corrected. Until then, keep the imputed history once and for all.

Trap 4: codes that pretend to be values

Many systems write 9999, -1 or 0 when they mean “unknown”. An income column reads 42,000; 38,000; 51,000; 999,999; 46,000: left as it is, the code becomes a real value and drags every average: here one code in five values raises the mean from 44,250 to 235,400, more than five times, and one in ten would still triple it. 999,999 means “unknown” only by a convention of the source system, which our engine cannot recognise by itself: it is emptied because it is declared. Declared codes are turned into missing values before anything is learned, and then imputed like any other gap. Values that only look like codes are flagged for a person to confirm, never changed silently: detecting is not deciding. The rule is simple: the smallest or the largest observed value v is flagged when it appears n(v)≥rmaxw≠vn(w) times, n(w) being the number of training rows equal to w and r a declared ratio, 5 by default; a code that appears once, as in the example, is not flagged. Such codes are one of the simple checks that, run to the end, find what nobody was looking for, as described in our article on serendipity through rigour.

Every imputed column also gets an indicator, 1 where the value was missing. After imputation, two clients can both show an income of 42,000, one declared, the other imputed; the indicator, 0 for the first and 1 for the second, lets the model tell them apart, which matters whenever not answering is itself a behaviour.

Missing is not the same as not applicable. A repair cost is missing when a repair took place and its amount was never entered; it is not applicable when the claim had no repair. A declared rule says when a column applies: a blank where it does not apply is a structural absence, never imputed, and it gets its own indicator, distinct from the missing indicator, so the model can tell “unknown” from “does not exist”.

Our engine, step by step: weights, chained equations, donors

The engine runs in a fixed order: declared codes are emptied and values not yet known at the valuation date are treated as missing; everything is then learned on the declared training rows only; values that do not apply are never filled; each incomplete column starts from its weighted median, or its most frequent category, and the chained equations take over.

Each customer counts once. When one customer has many rows, several policies, claims or monthly records, a plain average lets that customer impose its values. Each independent unit u therefore carries a weight ωu, equal to 1 by default, or its exposure when that is declared, shared among its rows where the column is observed:

wi=ωu(i)nu(i)(3)

where u(i) is the unit of row i and nu the number of training rows of unit u where the column is observed. These weights enter the medians and frequencies, the scaling of the predictors, the equations, the draw of donors and the stopping rule.

Chained equations. Each incomplete column j gets its own equation, learned on the training rows Oj where it is observed:

(β^0,β^)=argminβ0,β∑i∈Ojwi(xij−β0−β⊤zi)2+λ‖β‖2,x^ij=β^0+β^⊤zi
(4)

zi holds, scaled with weights learned on the training rows, the current values of the other declared columns and their missing indicators, the declared complete predictors and, in the history equations of trap 2, the outcome yi where it is known; λ is a declared penalty, 1 by default. A yes-or-no column gets a penalised logistic regression, a categorical one a penalised multinomial logistic, an ordered one a proportional-odds model, and its value is drawn from the predicted probabilities, restricted to the values that respect the declared rules. The equations run in turn, column after column, until two successive rounds no longer move the mean and the standard deviation of the imputed values by more than ε observed standard deviations (ε=0.01 by default; for categories, the change of their frequencies), within 20 rounds at most; otherwise the column is reported as not converged.

Donors. Why not write the prediction itself? Because for many variables a prediction is not a possible value: 2.38 children, a negative duration, an amount never seen. The prediction is used as a coordinate to find records that look alike; the value written is the observed value of a real record, a donor (predictive mean matching). For a receiver i, the row to fill, the same equation gives the prediction x^d of every candidate donor row d. Each unit other than the receiver’s offers one row, its closest row whose value respects the declared rules for this receiver; 𝒟i holds the rows of the k units whose offered prediction is closest, those with the smallest distance |x^d−x^i| (k=5 by default); di is the donor drawn:

P(di=d)=ωu(d)∑d′∈𝒟iωu(d′)(d∈𝒟i),xi*=xdi
(5)

With equal weights, the draw is uniform among the k units. Two properties follow. Each imputed value is the observed value of a training row of another unit: it never leaves the range of the donors’ values, and an integer stays an integer. That holds for donors only: on request, the engine can write the regression prediction itself, which can leave that range. And the spread is kept: 1.00 times the observed variance in the simulation of trap 1, against 0.70 with the mean. That is a measured property, not a guarantee that the whole distribution is reproduced exactly.

Declared rules are checked for each receiver before a value is written. Bounds, whole numbers, a list of allowed values, or one column that may not exceed another, such as an amount paid never above the amount claimed. Nothing is clipped to a bound: when no compatible value exists, the cell stays empty and the report counts it.

Which method? Chosen out of sample, with simultaneous bounds

The median or donors, the observed frequencies or a model of the categories: which should fill a given column? The tempting answer is the method with the smallest reconstruction error, and it is a trap: the median minimises the absolute error precisely because it writes the same central value everywhere, which is trap 1 again. On request, our engine decides column by column, out of sample, judging the error and the distribution together.

Hiding values that are known. The rows are split into folds grouped by independent unit, chronological when the data are dated (learn on the past, validate on the next block). On the validation side, observed values are hidden, and the same hidden cells serve every method. In the main scenario, row i is hidden with probability:

πi=min(1,cp^i),∑i∈𝒯wimin(1,cp^i)∑i∈𝒯wi=r
(6)

where p^i is the probability that the value is missing, from a weighted logistic model of the absence on the other numeric columns, 𝒯 the training side of the fold, r its observed missing rate, and c the constant that matches that rate, found by bisection. A control scenario hides uniformly at the same rate, and stress scenarios set the rate to 30% and 50%. Everything a fold learns, the rate, the spread, the model of the absence and the constant, comes from its training side only, and only its validation rows are imputed.

Comparing two methods. For a number, each hidden cell costs the absolute error scaled by the observed spread; for a category, minus the logarithm of the probability given to the true category before any draw. With Cu the hidden cells of unit u, xi(m) the value written by method m, s the weighted standard deviation of the observed values on the training side, and pu the normalised weight of unit u, the relative degradation of method m against a competitor j and its standard error are:

ℓm,u=1|Cu|∑i∈Cu|xi(m)−xi|s,θ^m,j=∑upuℓm,u∑upuℓj,u−1,sem,j2=∑upu2(ℓm,u−(1+θ^m,j)ℓj,u∑vpvℓj,v)2
(7)

One bound for all comparisons at once. A method is compared with every competitor, in every scenario and at every rate: that family F of comparisons is tested together, not one by one. The units are resampled 200 times with replacement and the whole chain is refitted in each replicate, giving θf* and sef* for each comparison f:

cα=q1−α(maxf∈Fθf*−θ^fsef*),m non-inferior⟺θ^f+cαsef<δ for every comparison f of m
(8)

q1−α is the quantile of order 1−α over the replicates, α=5%, and δ=5% is the non-inferiority margin, the largest extra error accepted, declared before any validation and never learned. A method is non-inferior when, even at its simultaneous upper bound, it is never more than 5% worse than any competitor.

The distribution is checked as well. On the hidden cells, the engine measures signed deviations from the truth: variance ratio minus 1, the gap at the 10th, 25th, 50th, 75th and 90th percentiles in observed standard deviations, the change of association with every other column (Spearman for numbers, Cramér’s V for categories), and the gap of frequencies for categories. A method is excluded when a distortion is demonstrated: the bootstrap interval of the deviation, between its 5th and 95th percentiles, lies entirely beyond the declared margin (0.2 for the variance ratio, 0.25 standard deviations for a percentile, 0.1 for an association or the frequencies). These are individual guards, deliberately not corrected for multiplicity: a false exclusion only falls back to the declared default, while a missed distortion would keep a method that distorts. A method that leaves a hidden cell empty is excluded too.

The decision. The candidates, by default the simple base (the median, or the observed frequencies) and the declared default (donors, or a model of the categories), are taken in a declared order of simplicity, and the first one that is non-inferior and not excluded is kept. If none qualifies, the declared default applies, and it has been evaluated like the others; if the default itself is excluded, nothing is imputed in its place: the whole call stops with a refusal that names the column and the reason.

On one simulated data set with known truth, 300 customers with two rows each, the engine ran with its declared settings. For a column that the others predict, the median’s error was 92% higher than the donors’ in the main scenario, its simultaneous upper bound reached +143%, and its spread was destroyed (variance ratio 0.00): the donors, 48% lower in the main scenario, with every simultaneous bound below −28%, were kept. For a column that nothing predicts, the median had the smaller error, 25% below the donors, and was non-inferior; a choice by error alone would have kept it. Its spread was destroyed again, so it was excluded; the donors, 33% worse on error, were not shown non-inferior, so the declared default, the donors, applied, and the report says why. Testing the eight comparisons of a column together raised the critical value to 2.50 and 2.61, against 1.64 for a single one-sided bound: that is the price of a choice that does not chase chance.

The report gives, for each column, the basis of the method used: selected out of sample with the criteria and margins actually measured, default with the reason, or declared. It never says “best”. A declared method is never replaced silently: a selection requested together with a declared method is refused. The selection never replaces the judgement on the final model by a reconstruction error: when it is explicitly forced on a table that carries an outcome, it is refused with an explicit reason; in the automatic mode with an outcome, the declared default methods are kept and the report says so; and by default no selection is run.

Out-of-sample selection on simulated data: simultaneous bounds of the extra error, and the verdict of our engine
Out-of-sample selection on simulated data: simultaneous bounds of the extra error, and the verdict of our engine

How sure are we? Several tables and Rubin’s rules

Suppose a missing age could plausibly be 38, 42, 47 or 51. A single table that writes one of them, or worse 44.5, pretends to know. Several imputed tables instead write 42 in the first, 51 in the second, 38 in the third, and so on; the model is fitted on each, and the results are combined. If the conclusions barely move from one table to the next, the missing values did not matter much; if they move a lot, the final uncertainty must say so. On request, our engine produces M tables; each has its equations re-estimated on a bootstrap sample of the training units and its donors drawn again; with Q^l the estimate on table l and Ul its variance, Rubin’s rules combine them:

Q¯=1M∑l=1MQ^l,U¯=1M∑l=1MUl,B=1M−1∑l=1M(Q^l−Q¯)2,T=U¯+(1+1M)B
(9)

U¯ is the variance within the tables, B the variance between them, and T the total variance of Q¯: the more the tables disagree, the larger B, and the wider the confidence intervals. The degrees of freedom of the interval follow Barnard and Rubin when those of the complete-data model are given. Whether this matters depends on the goal. To predict, an imputation is judged like the model: out-of-sample performance, calibration, stability, no leakage. To explain, unbiased coefficients and honest standard errors are needed as well, and that is where several imputations and Rubin’s rules become indispensable.

Measured on 300 simulated data sets of 400 rows, each row its own unit. The quantity estimated is the coefficient of one variable in a linear regression of the outcome on two variables; its true value is 2. That variable is missing at random given the other one, which is fully observed (a logistic model on it), about 31% of its values on average. The goal is to estimate on this history, not to score new rows: all 400 rows are training rows, there is no validation side, and the outcome enters the imputation equations. The 20 tables are made as above, equations re-estimated on a bootstrap of the units and donors drawn again, then combined by Rubin’s rules with the Barnard–Rubin degrees of freedom. Coverage of the nominal 95% interval, with its 95% Monte-Carlo interval: before any value is removed, 95% (285 of 300, between 92% and 97%). After a mean fill, never (0 of 300): the estimate falls to 1.23. With one table filled by our engine and analysed as if it were observed, 91% (272 of 300, between 87% and 93%): the interval is too narrow, 0.34 wide, because it ignores the doubt about the filled values. With 20 tables combined by Rubin’s rules, 96% (289 of 300, between 94% and 98%), for a width of 0.39. Here, dropping the incomplete rows, the competent standard for this design, does as well, 96% (287 of 300, between 93% and 97%), because the absence depends only on a variable of the model; it pays with a wider interval, 0.40, and it no longer holds when the absence depends on the outcome. Multiple imputation by chained equations with the outcome, correctly used, is what our engine implements; we have not measured it against another implementation, so the gains shown here are against the naive fills only. And these coverages concern inference on history: to score new rows, whose outcome is not known, our engine uses the equations learned without it, and the imputation is then judged out of sample like the model, not by a coverage.

Coverage of the 95% interval of a coefficient after imputation, by method
Coverage of the 95% interval of a coefficient after imputation, by method

What the engine refuses, and what no imputation can do

Chained equations and donors rest on one assumption, missing at random (MAR below): once the declared variables are known, the absence no longer depends on the missing value. With R the indicator that a value is missing and X=(Xobs,Xmis) the data, observed and missing:

MCAR:P(R∣X)=P(R),MAR:P(R∣X)=P(R∣Xobs),MNAR:P(R∣X) depends on Xmis
(10)

When the value itself drives its absence, the highest incomes hidden precisely because they are high, no imputation by chained equations or by donors resolves the problem, ours included: the observed data cannot identify a mechanism that depends on values that were never observed.

What the tool does measure is whether the absence can be predicted. For each column, a model of its missing indicator on the other numeric columns is scored out of sample: folds grouped by unit, or chronological with a time column (learn on the past, test the next block), with an interval obtained by resampling the units. The measure is the AUC, the probability that a row where the value is missing gets a higher score than a row where it is observed; 0.5 is chance. An AUC clearly above 0.5, its whole interval above it, only says that the absence carries an observable signal. It never proves missing at random, and an AUC near 0.5 never excludes missing not at random.

When missing not at random is plausible, it calls for declared assumptions and a sensitivity analysis: shift the imputed values by a chosen amount and check whether the conclusions hold. Such scenarios rest on assumptions that the observed data can neither confirm nor refute: they show how much the conclusions depend on them, not which one is true.

The engine refuses, by name, rather than guess: a column with missing values whose type is not declared; a table without a declared independent unit or without declared training rows; dated data without the date at which each column becomes known; several tables with a method that draws nothing at random; a selection forced on a table with an outcome; a selection in which even the declared default is excluded.

Its stated limits: the equations are linear (penalised regressions and logistic models), with no forests as long as no out-of-sample gain is shown; donors cannot extrapolate beyond the range of their values, and the report says how often a receiver’s prediction fell outside the range of the donors’ predictions; only declared codes are emptied; the dependence of the imputed past on more recent rows imputed in the same call, described in trap 3, is not yet corrected; and with an outcome, the method is not chosen out of sample, because the loss of the final model, which would then prevail, is not implemented.

Three rules, and what you receive

Three rules sum up the method: never learn from the future; never confuse an imputed value with an observed one; never hide the uncertainty that missing values create.

You receive the completed table with exactly the same rows and the same index, the columns you did not declare untouched, an indicator of missing values for every declared column that had any, and an indicator of not applicable values where a rule declares them. You also receive a report, which gives for each column:

  1. its status (filled; not converged; some values left empty by the rules; not filled, too few units observed; or filled by a simple draw because the model could not be fitted) and the method actually used;
  2. how many values were missing, how many were not applicable, how many were filled;
  3. how many declared codes were replaced, and which values look like codes without having been declared;
  4. how many units had an observed value in the training data;
  5. whether the chained equations converged;
  6. how many values stayed empty for lack of a value compatible with the rules;
  7. for a numeric column, the variance of the completed column divided by that of the observed values.

For the whole table, it adds how often a receiver’s prediction fell outside the range of the predictions of the whole donor pool and how far its nearest donor was, the categories never seen in the training data, and the diagnostic of the absences described above. The same procedure serves an insurer’s claims base, a CRM full of blank fields, sensor series with gaps or a financial panel. Free text, names, labels and addresses, follows another path: it is cleaned with dictionaries and similarity, described in our article on cleaning text data.

References

D. B. Rubin (1976), “Inference and missing data”, Biometrika; D. B. Rubin (1987), Multiple Imputation for Nonresponse in Surveys, Wiley; S. van Buuren and K. Groothuis-Oudshoorn (2011), “mice: Multivariate Imputation by Chained Equations in R”, Journal of Statistical Software; R. J. A. Little (1988), “Missing-data adjustments in large surveys”, Journal of Business & Economic Statistics (predictive mean matching); K. G. M. Moons et al. (2006), “Using the outcome for imputation of missing predictor values was preferred”, Journal of Clinical Epidemiology; J. Barnard and D. B. Rubin (1999), “Small-sample degrees of freedom with multiple imputation”, Biometrika; P. H. Westfall and S. S. Young (1993), Resampling-Based Multiple Testing, Wiley (simultaneous bounds by the maximum over the family); A. E. Hoerl and R. W. Kennard (1970), “Ridge regression: biased estimation for nonorthogonal problems”, Technometrics; P. McCullagh (1980), “Regression models for ordinal data”, Journal of the Royal Statistical Society B.

Raphael Sebbah

About the author

Raphael Sebbah

Actuary (ISUP) and data scientist, founder of Smart Data Science. Formerly at Amundi (CAAM), Dexia, AIG and Phoenix; co-author of research published in The European Physical Journal C and Brain Communications.

LinkedIn · ORCID · Google Scholar

More publications

Publications
Data quality

Serendipity through rigour: the findings nobody was looking for

Domain checks, cross-variable rules, reconciliations and totals split by part: how consistency checks uncovered more than ILS 1 million.

Read the article
Data quality

One value, fifty spellings: dictionaries, fuzzy matching and human validation

A city typed in capitals, a product with a missing letter, “N/A” where nothing was known: free-text fields multiply the spellings of a few real values, and every analysis built on them inherits the noise. Cleaning them is not about making a machine “understand language”. It is about never letting a resemblance become a false business fact: certain rules first, a key that destroys nothing, similarity as a suggestion only, vetoes, and the last word to someone who knows the business.

Read the article
Statistics

Correlations: deciding which relations deserve to be read

A correlation matrix can give hundreds of mathematically correct numbers and several false conclusions. Computing a correlation is not our problem; deciding which test to read, and whether the relation deserves to be read at all, is. This article follows our correlation and test engines step by step, in the order they run, with the rules that decide and the measurements that show where the usual shortcuts go wrong: what one observation is, which quantity is compared and which test it calls for, which assumptions are checked and on what, what time, controls and segments change, how many tests were really run, and what the engines refuse to compute rather than guess.

Read the article

Let’s build better decisions together

Tell us about the decision you need to make.

A few lines are enough: your sector, the data you have and what you want to improve. We reply personally with a first view of the approach.

  • A few lines are enough
  • NDA on request
  • Code and documentation handed over