Sub topic 10
When SimpleImputer Is Not Enough
This chapter assumes you can use SimpleImputer inside a Pipeline, and that you know why imputers are fitted on training data only. It covers where simple imputation breaks down and what to try next.
What SimpleImputer ignores
SimpleImputer fills each column on its own. It uses one number per column, computed from that column alone. This causes three problems.
- Relationships between columns are ignored. If
incomeis missing, the fill value is the same for a student and a senior manager. - Variance shrinks. Every filled entry gets the same value, so the column's spread drops. Correlations with other columns weaken too.
- The reason for the gap is ignored. Data can be missing completely at random, missing in a way that depends on other columns, or missing because of the value itself. For example, high earners may skip the income question. A column mean cannot repair that last case.
You saw add_indicator=True earlier. It helps a model notice that a value was absent. It does not make the filled value any more accurate.
Option 1: KNNImputer
KNNImputer fills a gap using the rows most similar to the incomplete one. It measures distance only over the features both rows have. It then averages the neighbors' values for the missing column.
import numpy as np
from sklearn.impute import KNNImputer
X = np.array([[1, 2],
[3, 4],
[np.nan, 6],
[8, 8]])
imputer = KNNImputer(n_neighbors=2)
print(imputer.fit_transform(X))
# [[1. 2. ]
# [3. 4. ]
# [5.5 6. ]
# [8. 8. ]]The third row has 6 in the second column. Its two closest rows on that column are [3, 4] and [8, 8]. The imputer fills the gap with the mean of their first values, (3 + 8) / 2 = 5.5.
Keep these points in mind:
- Distances depend on feature scale. Put a scaler before the imputer, or large-valued columns will dominate the neighbor search. A scaler such as
StandardScalerskips NaN when it fits, so it can come first. - Prediction cost grows with the training set, because
transformsearches the stored training rows. - It handles only numeric columns.
Option 2: IterativeImputer
IterativeImputer treats each incomplete column as a target. It trains a regression model (by default BayesianRidge) on the other columns to predict it. It cycles through the columns for several rounds until the fills settle.
It is still marked experimental, so you must enable it explicitly:
import numpy as np
from sklearn.experimental import enable_iterative_imputer # noqa: F401
from sklearn.impute import IterativeImputer
X = np.array([[1.0, 2.0],
[2.0, 4.0],
[3.0, 6.0],
[4.0, np.nan]])
imputer = IterativeImputer(random_state=0)
X_filled = imputer.fit_transform(X)
print(X_filled[3]) # the NaN becomes a value close to 8The second column is twice the first, so the model learns that relationship and fills a value near 8. SimpleImputer would have filled the column mean of 4.
Set random_state for reproducible results. Convergence can be slow, so watch for a ConvergenceWarning and raise max_iter if it appears. If you set sample_posterior=True, the imputer draws values from a predictive distribution instead of returning one best guess. Running it several times then gives you multiple imputations.
Option 3: let the model handle NaN
Some estimators accept NaN directly, so you can skip imputation. HistGradientBoostingClassifier and HistGradientBoostingRegressor learn at each split which branch missing values should follow. This often works well on tabular data, and it also keeps the missingness signal.
Choosing between them
| Method | Uses other columns | Cost | Categorical data |
|---|---|---|---|
| `SimpleImputer` | No | Very low | Yes |
| `KNNImputer` | Yes, by similarity | High at transform time | No |
| `IterativeImputer` | Yes, by regression | Medium to high | No |
| Native NaN support | Learned in splits | Low | Depends on the estimator |
Comparing methods fairly
More sophisticated imputers do not always give better predictions. Compare candidates by swapping the imputer step inside the same Pipeline and cross-validating. That way each method is fitted only on training folds, as in the leakage chapter.
import numpy as np
from sklearn.experimental import enable_iterative_imputer # noqa: F401
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 Pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 4))
y = (X[:, 0] + X[:, 1] > 0).astype(int)
X[rng.random(X.shape) < 0.15] = np.nan # 15% missing at random
for name, imp in [("simple", SimpleImputer(strategy="median")),
("knn", KNNImputer(n_neighbors=5)),
("iterative", IterativeImputer(random_state=0))]:
pipe = Pipeline([("scale", StandardScaler()),
("impute", imp),
("clf", LogisticRegression())])
print(name, cross_val_score(pipe, X, y, cv=5).mean().round(3))The exact scores depend on your library versions. What matters is the pattern: one pipeline, one swapped step, the same folds.
Exercise
A dataset has columns height_cm and weight_kg, which are strongly correlated. About 20% of weight_kg is missing. Why might IterativeImputer beat SimpleImputer(strategy="mean") here, and what should you do before using KNNImputer on the same data?
Show answer
SimpleImputer gives every missing weight the same value, so a tall person and a short person get the same fill, and the column's variance shrinks. IterativeImputer can regress weight on height and fill each gap with a value that fits that row. Before using KNNImputer, scale the columns (for example with StandardScaler). Otherwise the larger-valued column dominates the distance and the neighbors are chosen poorly.