Lesson 5 of 9
Handling Missing Data: Simple, KNN & Iterative Imputation Strategies
Missing data is an unavoidable reality in production ML. Missingness mechanisms are statistically classified into: Missing Completely at Random (MCAR), Missing at Random (MAR), and Missing Not at Random (MNAR). Replacing missing values with a naive constant can distort distributions and destroy feature correlations. Modern Scikit-Learn provides sophisticated imputation strategies: SimpleImputer (mean/median/mode), KNNImputer (feature-space neighborhood distance), and IterativeImputer (MICE - chained regression equations).
Comparing Imputation Strategies in Scikit-Learn
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer, KNNImputer
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.ensemble import ExtraTreesRegressor
# Ground truth correlated data
np.random.seed(42)
n_samples = 500
x1 = np.random.normal(50, 10, n_samples)
x2 = 2.5 * x1 + np.random.normal(0, 5, n_samples) # Strong linear dependency
x3 = 0.5 * x1 - 0.2 * x2 + np.random.normal(0, 2, n_samples)
X_clean = np.column_stack([x1, x2, x3])
# Introduce 20% artificial MAR missingness into feature x2
mask = np.random.uniform(0, 1, n_samples) < 0.2
X_corrupted = X_clean.copy()
X_corrupted[mask, 1] = np.nan
# 1. Simple Median Imputation (Distorts correlation between x1 and x2)
med_imputer = SimpleImputer(strategy='median', add_indicator=True)
X_median = med_imputer.fit_transform(X_corrupted)
# 2. KNN Imputer (Finds k nearest neighbors in non-missing dimensions)
knn_imputer = KNNImputer(n_neighbors=5, weights='distance')
X_knn = knn_imputer.fit_transform(X_corrupted)
# 3. Iterative Imputer (MICE: models x2 as a function of x1 and x3)
mice_imputer = IterativeImputer(
estimator=ExtraTreesRegressor(n_estimators=50, random_state=42),
max_iter=10,
random_state=42
)
X_mice = mice_imputer.fit_transform(X_corrupted)
# Measure reconstruction Mean Absolute Error against ground truth
actual_vals = X_clean[mask, 1]
print(f"Simple Median Imputation MAE : {np.mean(np.abs(actual_vals - X_median[mask, 1])):.4f}")
print(f"KNN Imputation MAE : {np.mean(np.abs(actual_vals - X_knn[mask, 1])):.4f}")
print(f"MICE Iterative Imputer MAE : {np.mean(np.abs(actual_vals - X_mice[mask, 1])):.4f} (Preserves joint covariance!)")Pro Tip: Always Include Missingness Indicators
In production, the fact that a value is missing is often informative in itself (MNAR). For example, a customer refusing to provide household income on a credit application has a fundamentally different default risk than someone reporting $50,000. In Scikit-Learn, set `add_indicator=True` in your imputer to append a binary column tracking which values were imputed.
MlHandlingMissingValues Visual Representation
Hands-On Challenge: Build a Native GBDT Imputation Benchmark
Tree algorithms like LightGBM and HistGradientBoostingClassifier handle `NaN` natively during node splitting without explicit imputation. Compare the ROC-AUC of LightGBM trained directly on raw `NaN` values against LightGBM trained on MICE-imputed features.
Quick Quiz & Key Concept Checks
Common Pitfall: Imputing Categorical Modes on Rare Classes
Imputing the most frequent category (mode) on an imbalanced categorical column inflates the dominant class and suppresses the variance of minority groups. Impute with an explicit `'MISSING'` category token instead.