KNN and Iterative Imputation
A median fill gives every incomplete row the same value, whatever else we know about it. But columns are rarely independent: a tall person tends to weigh more, a large flat tends to cost more, a hot day tends to have high electricity use. Methods 7 and 8 of the eight use the other columns to make a better guess:
- KNN imputation fills a gap with the average of the most similar complete rows.
- Iterative (model-based) imputation fits a regression model for each incomplete column on the others, and repeats until the fills settle.
Both work best when values are missing at random given the observed columns (MAR): the other columns then really do carry the information needed. Neither can fix MNAR (Missing-Value Analysis).
KNN imputation from scratch
To fill row r's missing feature j: compute distances from r to every training row that has feature j, using only the features both rows have; take the k nearest; average their values of j.
import numpy as np
# height (cm), weight (kg), shoe size (EU); one weight missing
train = np.array([[160, 55, 37], [165, 60, 38], [170, 66, 40], [175, 72, 42],
[180, 79, 43], [185, 85, 45], [158, 52, 36], [190, 92, 46]], float)
row = np.array([178, np.nan, 43.0])
def knn_fill(row, train, k=3):
filled = row.copy()
for j in np.where(np.isnan(row))[0]:
cand = train[~np.isnan(train[:, j])]
shared = ~np.isnan(row)
d = np.sqrt(((cand[:, shared] - row[shared]) ** 2).sum(axis=1))
nearest = np.argsort(d, kind="stable")[:k]
print("nearest rows:", cand[nearest].tolist(), "distances:", np.round(d[nearest], 2).tolist())
filled[j] = cand[nearest, j].mean()
return filled
print("KNN fill: ", np.round(knn_fill(row, train), 1).tolist())
print("median fill:", [178.0, float(np.median(train[:, 1])), 43.0])nearest rows: [[180.0, 79.0, 43.0], [175.0, 72.0, 42.0], [185.0, 85.0, 45.0]] distances: [2.0, 3.16, 7.28]
KNN fill: [178.0, 78.7, 43.0]
median fill: [178.0, 69.0, 43.0]
The KNN fill uses the three people of most similar height and shoe size and lands at 78.7 kg, while the median of all weights is 69.0 kg whatever the person looks like. Note that distances depend on the units: here height and shoe size have similar spreads, but in general you scale before KNN imputation (see Min-Max, Z-Score, Robust and Max-Abs Scaling), otherwise the column with the largest numbers decides who the neighbours are.
scikit-learn's KNNImputer does the same with a NaN-aware Euclidean distance (nan_euclidean_distances), which rescales the distance by the share of coordinates used, so rows with more shared features are not unfairly "far".
Iterative imputation
IterativeImputer (still marked experimental, so it needs an extra import) works column by column:
- Start by filling every gap with a simple value (the mean).
- For each incomplete column
j: fit a regressor (by defaultBayesianRidge) that predictsjfrom all other columns, on the rows wherejis observed; replace the gaps injwith its predictions. - Repeat step 2 over all columns for several rounds (
max_iter), until the fills change by less thantol.
This is the idea behind MICE (multiple imputation by chained equations). With sample_posterior=True and different seeds it can produce several plausible completed datasets, which lets a statistician measure how much the conclusions depend on the guesses.
Comparing the methods
The best test of an imputer is to hide values you know, impute them and measure the error. We generate correlated housing data, hide 20% of one column at random (MCAR, so the comparison is fair), and fit every imputer on a training part only:
import numpy as np
from sklearn.experimental import enable_iterative_imputer # noqa: F401
from sklearn.impute import IterativeImputer, KNNImputer, SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
n = 800
area = rng.normal(80, 25, n).clip(25) # m2
rooms = np.round(area / 25 + rng.normal(0, 0.6, n)).clip(1)
age = rng.uniform(0, 60, n)
price = 2.5 * area + 15 * rooms - 0.8 * age + rng.normal(0, 20, n) # thousands
X = np.column_stack([area, rooms, age, price])
hide = rng.random(n) < 0.2
X_miss = X.copy()
X_miss[hide, 0] = np.nan # area is missing for 20%
train = np.arange(n) < 600
test_hidden = ~train & hide
imputers = {
"mean": SimpleImputer(strategy="mean"),
"median": SimpleImputer(strategy="median"),
"KNN (k=5, scaled)": make_pipeline(StandardScaler(), KNNImputer(n_neighbors=5)),
"iterative": IterativeImputer(max_iter=10, random_state=0),
}
for name, imp in imputers.items():
imp.fit(X_miss[train])
out = imp.transform(X_miss[~train])
if name.startswith("KNN"):
out = imp[0].inverse_transform(out) # back to m2
err = out[hide[~train], 0] - X[test_hidden, 0]
print(f"{name:18s} RMSE of imputed area: {np.sqrt(np.mean(err ** 2)):5.1f} m2")
print("std of area:", round(float(X[:, 0].std()), 1), " hidden test values:", int(test_hidden.sum()))mean RMSE of imputed area: 22.6 m2
median RMSE of imputed area: 22.6 m2
KNN (k=5, scaled) RMSE of imputed area: 8.3 m2
iterative RMSE of imputed area: 7.6 m2
std of area: 24.4 hidden test values: 43
The mean and median fills are off by about one standard deviation of the column (RMSE 22.6 against a standard deviation of 24.4 m2), which is what "knowing nothing" costs. KNN uses rooms and price and cuts the error to 8.3 m2, and iterative imputation, whose linear regressor matches how this data was generated, gets to 7.6 m2. On real data the ranking varies: KNN copes better with non-linear relations, iterative imputation with many weakly related columns. Measure it on your own data the same way.
Note:
StandardScalerignoresNaNwhen it fits and passes them through when it transforms, which is why it can sit in front ofKNNImputerin a pipeline.
Better fills, better models?
A smaller imputation error does not automatically mean a better model; what counts is the final score, measured with cross-validation where the imputer is refitted inside every fold:
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 Ridge
from sklearn.model_selection import KFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
n = 800
area = rng.normal(80, 25, n).clip(25)
rooms = np.round(area / 25 + rng.normal(0, 0.6, n)).clip(1)
age = rng.uniform(0, 60, n)
price = 2.5 * area + 15 * rooms - 0.8 * age + rng.normal(0, 20, n)
X = np.column_stack([area, rooms, age])
X[rng.random(n) < 0.3, 0] = np.nan # 30% of area missing
cv = KFold(5, shuffle=True, random_state=0)
for name, imp in [("median", SimpleImputer(strategy="median")),
("median + flag", SimpleImputer(strategy="median", add_indicator=True)),
("KNN", KNNImputer(n_neighbors=5)),
("iterative", IterativeImputer(random_state=0))]:
pipe = make_pipeline(StandardScaler(), imp, Ridge())
r2 = cross_val_score(pipe, X, price, cv=cv, scoring="r2")
print(f"{name:14s} R2 {r2.mean():.3f}")median R2 0.842
median + flag R2 0.842
KNN R2 0.884
iterative R2 0.887
Predicting price (5-fold CV, R², 800 rows), the imputers that use the other columns win (0.884 and 0.887 vs 0.842 for the median; the flag adds nothing because area is missing completely at random). The gain is real but modest here because rooms already carries much of what area would tell the model. KNN and iterative imputation also cost more: KNN keeps the whole training set in memory and searches it for every row at prediction time, which matters in production.
Pitfalls
- Fitting the imputer on all rows before cross-validation: the neighbours and regressions then include validation rows. Keep the imputer in the pipeline.
- Using the target as an input to imputation at training time: it seems smart (price helps guess area!), but at prediction time the target is unknown, so the imputer would see different inputs. In the first comparison above, price was used only to judge imputers, not inside a model that predicts price.
- KNN without scaling: the largest-valued column picks the neighbours.
- Trusting imputed values as data: they are guesses. Report results with the share of imputed values, and add indicators when missingness may be informative.
Practice
- Why does
KNNImputerneed scaled inputs, whileIterativeImputerwithBayesianRidgemostly does not?
Answer
KNN compares rows by Euclidean distance, which is dominated by large-valued columns. A linear regression adapts its coefficients to each column's units, so rescaling a column only rescales its coefficient (apart from the small effect of the prior in BayesianRidge).
- Your dataset has 5 million rows. Which of the two methods do you try first, and why?
Answer
Iterative imputation with a linear model: it costs a few regressions per round and predicts in constant time per row. KNN imputation needs a neighbour search over the training rows for every incomplete row, which is slow and memory-hungry at that size (approximate nearest-neighbour indexes help, but add complexity).
Test yourself
What does KNN imputation use to fill a missing value?
- The column mean
- The average value of that column in the k most similar rows
- A constant
- The next row
What does each round of iterative imputation do for an incomplete column?
- Copies the previous row
- Fits a regressor predicting it from the other columns and replaces its gaps with the predictions
- Deletes rows with gaps
- Sorts the column
How do you compare imputers fairly?
- By the number of rows they fill
- By hiding known values, imputing them with imputers fitted on training data, and measuring the error; and by the model's cross-validated score
- By speed only
- By the mean of the imputed column
Which missingness mechanism can KNN and iterative imputation NOT fix?
- MCAR
- MAR
- MNAR
- None of them