Sub topic 10
When SimpleImputer is not enough
This chapter assumes you know the fit/transform pattern, have used SimpleImputer inside a Pipeline or ColumnTransformer, and understand why imputers are fitted on training data only. The goal is to tell when a single column statistic is a poor guess, and what to use instead.
What SimpleImputer cannot see
SimpleImputer fills each column from that column alone. The fill value is one number per column, the same for every row. That has three consequences.
- It ignores other columns. If
weightis missing for a person who is 190 cm tall, the imputer still writes the average weight of everyone. - It shrinks variance. Every filled cell sits exactly at the center of the column, so it adds no spread. If a fraction
pof a column is mean-imputed, the column's variance falls to roughly(1 - p)times the variance of the observed values. - It weakens relationships. The filled rows lie on the column's center line, so correlations with other columns move toward zero. Linear model coefficients and correlation-based feature selection then see less signal than is really there.
Whether this matters depends on why the values are missing. Statisticians use three labels:
| Mechanism | Meaning | Effect on simple imputation |
|---|---|---|
| MCAR (missing completely at random) | Missingness is unrelated to any value, observed or not. | Bias is small. Variance shrinkage is the main cost. |
| MAR (missing at random) | Missingness depends on other observed columns. | The column mean is biased. Imputing from the other columns helps. |
| MNAR (missing not at random) | Missingness depends on the missing value itself, such as high earners skipping the income question. | No imputer can recover the value. An indicator column can still capture the pattern. |
You cannot prove which mechanism applies from the data alone. You can check for MAR by comparing other columns between rows where a value is missing and rows where it is present. If they differ clearly, MCAR is unlikely.
A concrete failure: mean versus a relationship
In this small matrix the second column is always twice the first. The last row is missing its first value.
import numpy as np
from sklearn.experimental import enable_iterative_imputer # noqa: F401
from sklearn.impute import IterativeImputer, SimpleImputer
from sklearn.linear_model import LinearRegression
X = np.array([[1.0, 2.0],
[2.0, 4.0],
[3.0, 6.0],
[4.0, 8.0],
[np.nan, 6.0]])
X_simple = SimpleImputer(strategy="mean").fit_transform(X)
print(X_simple[-1]) # [2.5 6. ]
iterative = IterativeImputer(estimator=LinearRegression(), random_state=0)
X_iter = iterative.fit_transform(X)
print(np.round(X_iter[-1], 2)) # [3. 6.]The mean imputer returns 2.5. The iterative imputer notices that the first column equals half the second, so it returns 3.0. Real data is noisier than this, but the mechanism is the same: the other columns carry information that SimpleImputer throws away.
The alternatives
scikit-learn offers three more ways to handle missing values in a feature matrix. Each is a different trade of cost against fidelity.
KNNImputer: borrow from similar rows
KNNImputer finds the n_neighbors rows closest to the incomplete row and averages their values for the missing column. Distance is computed with nan_euclidean, which uses only the columns present in both rows and rescales for the ones left out.
import numpy as np
from sklearn.impute import KNNImputer
X = np.array([[1, 2, np.nan],
[3, 4, 3],
[np.nan, 6, 5],
[8, 8, 7]])
imputer = KNNImputer(n_neighbors=2)
print(imputer.fit_transform(X))
# [[1. 2. 4. ]
# [3. 4. 3. ]
# [5.5 6. 5. ]
# [8. 8. 7. ]]For the first row, the two nearest neighbors are rows 2 and 3 (values 3 and 5), so the fill is 4. For the third row, the neighbors are rows 2 and 4 (values 3 and 8), so the fill is 5.5.
Things to know before using it:
- Scale first. Distances are dominated by large-valued columns. Put a
StandardScalerbefore the imputer.StandardScalerignores NaN when computing its statistics and passes them through, so this order works. - It is numeric only. There is no meaningful distance for raw strings. Encode categorical columns first, or impute them separately.
- Cost grows with data size.
transformcompares each incomplete row with all training rows, so it gets slow on large datasets. - Neighbors are a hyperparameter. A small
n_neighborsgives noisy fills. A large one drifts back toward the column mean. Tune it with cross-validation. Settingweights="distance"gives closer rows more influence.
IterativeImputer: model each column from the others
IterativeImputer treats each column with missing values as a regression target and the other columns as inputs. It starts from a simple fill (the mean by default). Then it cycles through the columns, refitting a regressor on the rows where the target is observed and re-predicting the missing cells. It stops when the values stop changing or after max_iter rounds.
Points specific to this class:
- It is still experimental. You must run
from sklearn.experimental import enable_iterative_imputerbefore importing it. Its API may change between releases. - The default regressor is
BayesianRidge. You can pass any regressor asestimator. A tree ensemble can capture non-linear relationships, but it is slower and its fills can look "stair-stepped". - Convergence is not guaranteed. If it stops at
max_iterwithout meetingtol, you get aConvergenceWarning. Raisemax_iteror check the data for extreme outliers. - Setting
sample_posterior=Truedraws fills from a distribution instead of using the point estimate. This restores some of the lost variance. It requires an estimator that supportsreturn_std, such asBayesianRidge. Running it several times with different seeds gives you the basis of multiple imputation. - It is numeric only, as with
KNNImputer.
Models that accept NaN directly
Some estimators do not need an imputer at all. HistGradientBoostingClassifier and HistGradientBoostingRegressor learn at each split which branch missing values should follow, so NaN is a usable signal. Several tree-based estimators in recent scikit-learn versions also accept NaN. Check the documentation of your installed version, because support varies by estimator.
This avoids invented values entirely. The cost is that you commit to a model family. A linear model, an SVM, or a neural network still needs imputed inputs.
MissingIndicator and add_indicator
A fill value hides the fact that a value was absent. If missingness itself predicts the target (MNAR, or MAR with a strong link), keep that signal. SimpleImputer, KNNImputer and IterativeImputer all accept add_indicator=True. The standalone MissingIndicator transformer does only the indicator part, for use in a ColumnTransformer alongside a different imputer.
Comparing approaches fairly
The question "which imputer is best" has an answer only for a given dataset and model. Compare candidates by putting each inside a Pipeline and scoring with cross-validation, so every fold fits the imputer on its own training part only.
import numpy as np
from sklearn.experimental import enable_iterative_imputer # noqa: F401
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import IterativeImputer, KNNImputer, SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
n = 500
x0 = rng.normal(size=n)
x1 = x0 + rng.normal(scale=0.3, size=n) # strongly related to x0
x2 = rng.normal(size=n)
X = np.column_stack([x0, x1, x2])
y = (x0 + 0.5 * x2 + rng.normal(scale=0.5, size=n) > 0).astype(int)
# Remove about 30% of the x0 values at random
X[rng.random(n) < 0.3, 0] = np.nan
candidates = {
"mean": make_pipeline(
SimpleImputer(strategy="mean"), LogisticRegression()),
"mean+flag": make_pipeline(
SimpleImputer(strategy="mean", add_indicator=True),
LogisticRegression()),
"knn": make_pipeline(
StandardScaler(), KNNImputer(n_neighbors=5), LogisticRegression()),
"iterative": make_pipeline(
IterativeImputer(random_state=0), LogisticRegression()),
"native NaN": HistGradientBoostingClassifier(),
}
for name, model in candidates.items():
scores = cross_val_score(model, X, y, cv=5)
print(f"{name:12s} {scores.mean():.3f}")The scores depend on the random data, so do not expect particular numbers. In this setup x1 is a good stand-in for x0, so KNNImputer and IterativeImputer have information to use that the mean imputer ignores. On data where the columns are unrelated, they often score no better than the mean, and they cost more.
Failure modes to watch for
- Imputing before splitting. Any imputer that sees test rows during
fitleaks information. Model-based imputers leak more thanSimpleImputer, because they learn relationships and not only a mean. Keep them inside the pipeline. - Fitting on the full dataset for the final model, then evaluating on the same data. Cross-validate the whole pipeline instead of imputing once up front.
- Treating imputed values as real. After imputation, a downstream model sees an invented number and a measured one as equally reliable. Indicator columns, or a model that reports uncertainty, make the difference visible.
- Heavy missingness. When more than about half of a column is missing, every imputer is mostly guessing. Consider dropping the column, or keeping only an indicator derived from it.
- Categorical columns.
KNNImputerandIterativeImputerreject string data. A common route is to impute categoricals withSimpleImputer(strategy="most_frequent")or a constant such as"missing", encode them, and then run the numeric imputer on the encoded result. Keep in mind that one-hot columns are 0/1 values, so averaging them yields fractions. - Inflated certainty from a single fill. One filled dataset treats every guess as truth. If you need honest uncertainty, such as confidence intervals on coefficients, single imputation of any kind understates it. Multiple imputation, for example repeated
IterativeImputer(sample_posterior=True)runs, is the standard remedy, and it goes beyond what a plainPipelineoffers.
Choosing, in practice
| Situation | Reasonable choice |
|---|---|
| Few missing values, columns mostly unrelated | `SimpleImputer` with median (numeric) or `most_frequent` (categorical) |
| Missingness may carry signal | Any imputer plus `add_indicator=True` |
| Columns strongly related, moderate data size | `IterativeImputer` or `KNNImputer` (scale first for KNN) |
| Gradient-boosted trees as the final model | Native NaN handling, optionally with no imputer |
| Need uncertainty estimates | Multiple imputation with `IterativeImputer(sample_posterior=True)` over several seeds |
| More than half of a column is missing | Consider dropping the column, or keep only the indicator |
The usual workflow is: build a SimpleImputer baseline inside a pipeline, record its cross-validated score, then try one or two alternatives under identical folds. Keep the more complex imputer only if the improvement is larger than the fold-to-fold variation.
Exercise
A dataset has columns height and weight, strongly correlated. About 25% of weight is missing, mostly for tall people. A colleague fills it with SimpleImputer(strategy="mean") and finds that a linear model's coefficient on weight is smaller than expected. Give two reasons from this chapter that explain it, and name one change you would try.
Show answer
First, the mean fills are all the same value, so they add no spread and pull the correlation between weight and the target (and height) toward zero, which shrinks the coefficient. Second, the missingness depends on height (MAR), so the missing weights are systematically higher than the average and the mean fill is biased low for those rows. A change to try is IterativeImputer or KNNImputer (scaled first), which use height to predict the missing weights. Adding add_indicator=True is also reasonable. In both cases, put the imputer in a pipeline and compare cross-validated scores.
Exercise
You fit KNNImputer(n_neighbors=3) on a table where one column is annual income in dollars (values in the tens of thousands) and another is age in years. The fills for age look nearly random. What is the likely cause, and how do you fix it?
Show answer
The distance calculation is dominated by income, because its numbers are far larger than age. Neighbors are effectively chosen by income alone, so the age fills are not based on similar rows overall. Add a StandardScaler before KNNImputer in the pipeline (it passes NaN through), so both columns contribute comparably to the distance.
Exercise
Why does the comparison code in this chapter put each imputer inside a Pipeline passed to cross_val_score, instead of imputing X once before cross-validation?
Show answer
Imputing once would let the imputer learn from rows that later land in the validation folds, which is data leakage and makes scores look better than they will be on new data. Inside a pipeline, cross_val_score refits the imputer on each training fold only and applies it to the matching validation fold.