Machine Learning β€Ί Features and Support Vector Machines β€Ί Day 174

Day 174: Handling Missing Data

Day 174 of 365 β€” Handling Missing Data

Master the mathematical theory and practical implementation of Handling Missing Data: understand Donald Rubin's 1976 taxonomy (MCAR, MAR, MNAR), compare SimpleImputer vs MissingIndicator vs KNNImputer vs IterativeImputer (MICE), derive the NaN-Euclidean distance metric from scratch, and analyze how Gradient Boosted Decision Trees natively route missing values during tree construction.

Course
Machine Learning
Category
Features and Support Vector Machines
Reading time
β‰ˆ 50 min
Practical time
β‰ˆ 60 min
Lesson duration
1h 50m
Last verified
2026-08-29

Hands-on lab for this lesson

Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/machine-learning/day-174-handling-missing-data

  1. Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
    git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git
    cd ai-roadmap-365.github.io
  2. Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path β€” section / subsection / week / day:
    cd labs/sections/machine-learning/day-174-handling-missing-data
  3. Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work β€” read it before running anything.
  4. Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
    bash tests/run_tests.sh   # or the test command named in the lab README

You can also open the lab as a local page (works offline, shows the file tree and expected output).

Learning objectives

By the end of this lesson you will be able to:

Prerequisites

Why this matters

In academic machine learning benchmarks (like MNIST or CIFAR-10), datasets are perfectly sanitized with zero missing values.

In the real world, missing data is ubiquitous:

If you handle missing data naively:

  1. Listwise Deletion (df.dropna()) Destroys Your Dataset: In a dataset with 50 columns where each column has only 5% missingness, dropping rows with any NaN discards over 92% of all samples!
  2. Mean Imputation Distorts Variances and Covariances: Replacing NaNs with the column average artificially shrinks variance sigma^2, inflates correlation test statistics, and produces severe bias under non-random missingness.
  3. Algorithms Crash: Scikit-learn Linear Regression, SVMs, and neural networks raise immediate ValueError: Input contains NaN.

Mastering the statistical mechanics of missingness (Rubin’s taxonomy) and modern imputation algorithms is essential for building robust real-world AI.


The idea in plain language

Imagine a physician examining a patient’s medical chart with several blank lines:

Treating all three cases as a simple β€œfill with average” destroys vital medical insights.


Historical background

In 1976, Harvard statistician Donald Rubin published the foundational paper Inference and Missing Data in Biometrika. Rubin formalized the three fundamental mechanisms of missingness: MCAR, MAR, and MNAR, revolutionizing statistical epidemiology.

In 1987, Rubin published Multiple Imputation for Nonresponse in Surveys, laying the groundwork for Bayesian multiple imputation.

In 1999, Stef van Buuren and Karin Groothuis-Oudshoorn developed MICE (Multivariate Imputation by Chained Equations), enabling scalable regression-based round-robin imputation across complex survey databases.

In 2016, Tianqi Chen and Carlos Guestrin published XGBoost, introducing sparsity-aware split finding, which enabled Gradient Boosted Decision Trees to learn optimal default routing directions for missing values natively during tree construction without requiring any pre-imputation.


What it is β€” and what it is not

Let us establish what missing data handling is and is not:

What it IS:

What it is NOT:


Why it was created and what problems it solves

Principled missing data handling resolves five critical operational and statistical failures:

  1. Prevents Sample Destruction from Listwise Deletion: Recovers 80% of training data that would otherwise be discarded by dropna().
  2. Preserves Multivariate Feature Covariances: KNNImputer and MICE reconstruct missing coordinates while respecting natural non-linear correlations.
  3. Captures Informative MNAR Signals: Binary MissingIndicator flags allow models to learn from the act of omission (e.g. unfiled tax returns).
  4. Guarantees Numerical Stability in Distance Metrics: NaN-Euclidean distance allows nearest-neighbor search over incomplete vectors.
  5. Enables Production Fault-Tolerance: Production models process incoming JSON payloads with missing fields gracefully without throwing runtime exceptions.

How it works

Let us formulate the mathematics of Donald Rubin’s taxonomy, NaN-Euclidean distance, and imputation algorithms.

1. Donald Rubin’s Taxonomy of Missingness (1976)

Let Y = (Y_{obs}, Y_{mis}) represent the full data matrix partitioned into observed components Y_{obs} and missing components Y_{mis}. Let M be a binary missingness indicator matrix where M_{i, j} = 1 if Y_{i, j} is missing, and 0 otherwise.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                      RUBIN'S MISSINGNESS TAXONOMY                      β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1. MCAR: P(M | Y_obs, Y_mis) = P(M)                                    β”‚
β”‚ 2. MAR:  P(M | Y_obs, Y_mis) = P(M | Y_obs)                            β”‚
β”‚ 3. MNAR: P(M | Y_obs, Y_mis) depends directly on Y_mis                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

A. Missing Completely at Random (MCAR)

P(M | Y_{obs}, Y_{mis}) = P(M)

B. Missing at Random (MAR)

P(M | Y_{obs}, Y_{mis}) = P(M | Y_{obs})

C. Missing Not at Random (MNAR)

P(M | Y_{obs}, Y_{mis}) depends directly on Y_{mis} itself.


2. The NaN-Euclidean Distance Metric

To compute Euclidean distance between two vectors u, v in R^D when some coordinates are NaN:

Let text{valid}(u, v) = { j in {1, ..., D} : u_j neq text{NaN} text{ and } v_j neq text{NaN} }. Let D_{text{valid}} = |text{valid}(u, v)| be the number of mutually observed coordinates, and D_{text{total}} = D.

The Scaled NaN-Euclidean Metric Formula:

d_{text{NaN}}(u, v) = sqrt( (D_{text{total}} / D_{text{valid}}) * sum_{j in text{valid}(u, v)} (u_j - v_j)^2 )


3. Imputation Algorithm Comparison

AlgorithmMechanismComputational ComplexityBest Used For
SimpleImputer(mean)Replaces NaN with training mean mu_jO(N * D) (Instant)Fast baseline for Gaussian MCAR features
SimpleImputer(median)Replaces NaN with training medianO(N * D) (Instant)Skewed numerical features with outliers
MissingIndicatorAppends binary boolean flag I_{mis} in {0, 1}O(N * D) (Instant)Informative MNAR missingness
KNNImputerNaN-Euclidean distance-weighted neighbor averageO(N^2 * D) (Slow)Tabular datasets (N < 50,000) with MAR correlations
IterativeImputer (MICE)Round-robin Bayesian Ridge chained equationsO(T * N * D^2) (Medium)Complex multivariate tabular datasets
Native GBDT BranchingOptimal default split child routingO(1) overheadXGBoost, LightGBM, CatBoost

4. Native GBDT Missing Value Routing (Sparsity-Aware Split Finding)

Gradient Boosted Decision Trees (XGBoost / LightGBM) do not require pre-imputation.

During tree construction at node m for feature x_j:

  1. Calculate gradient statistics for all samples where x_j is observed: G_{obs} = sum g_i, H_{obs} = sum h_i.
  2. Calculate gradient statistics for all samples where x_j is NaN: G_{mis} = sum g_i, H_{mis} = sum h_i.
  3. Evaluate Two Routing Hypotheses:
    • Hypothesis Left: Send all NaN instances to the Left child node.
    • Hypothesis Right: Send all NaN instances to the Right child node.
  4. The tree selects whichever default direction yields the higher split gain Delta L.
  5. During inference, if x_j is NaN, it follows the learned default direction automatically.

An everyday analogy

Think of missing data handling as a detective reconstructing a torn crime scene photograph:

  1. Listwise Deletion (dropna()): The detective burns every photograph that has a small torn corner, leaving only 3 completely intact photos out of 100 (Destroys 97% of evidence).
  2. Mean Imputation: The detective paints every torn hole with flat generic gray paint (Destroys image contrast and local details).
  3. KNN Imputation (The Restoration Artist): The detective examines adjacent intact photographs of the same room and paints the missing section using the textures of neighboring angles (Preserves local context).
  4. MissingIndicator (The Forensic Tag): The detective places a red evidence tag on every torn hole, noting that the tear was made by scissors (proving intentional tampering / Informative MNAR Signal).

Examples in practice

Let us visualize Donald Rubin’s missing data taxonomy:

Architecture diagram comparing Missing Completely at Random (MCAR), Missing at Random (MAR), and Missing Not at Random (MNAR).

Below is the geometric execution flow of NaN-Euclidean distance and KNNImputer:

Animated flow chart showing 2D projection with missing coordinates, NaN-Euclidean distance scaling, nearest neighbor search, and coordinate imputation.

Let us examine real Python code demonstrating SimpleImputer with MissingIndicator vs KNNImputer inside a Pipeline:

import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer, KNNImputer, MissingIndicator
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

# 1. Generate Synthetic Tabular Dataset with Missing Values (MAR & MNAR)
rng = np.random.default_rng(42)
n_samples = 500

X_clean = rng.normal(loc=10.0, scale=3.0, size=(n_samples, 4))
# Feature 0 & 1 determine target
y = (X_clean[:, 0] * 1.5 - X_clean[:, 1] * 2.0 > 0).astype(int)

# Corrupt data with missing values (20% NaNs)
X_corrupt = X_clean.copy()
nan_mask_0 = rng.uniform(size=n_samples) < 0.20
nan_mask_1 = (X_clean[:, 0] > 12.0) & (rng.uniform(size=n_samples) < 0.40) # MAR/MNAR condition
X_corrupt[nan_mask_0, 0] = np.nan
X_corrupt[nan_mask_1, 1] = np.nan

print(f"Total Missing Values in Dataset: {np.isnan(X_corrupt).sum()} / {X_corrupt.size}")

# 2. Strategy A: Simple Median Imputer with MissingIndicator Flags
pipe_median_indicator = Pipeline([
    ("imputer", SimpleImputer(strategy="median", add_indicator=True)),
    ("scaler", StandardScaler()),
    ("classifier", LogisticRegression(solver="lbfgs", random_state=42))
])

# 3. Strategy B: KNNImputer (k=5)
pipe_knn = Pipeline([
    ("imputer", KNNImputer(n_neighbors=5)),
    ("scaler", StandardScaler()),
    ("classifier", LogisticRegression(solver="lbfgs", random_state=42))
])

# 4. Evaluate via 5-Fold Cross Validation
cv_median = cross_val_score(pipe_median_indicator, X_corrupt, y, cv=5, scoring="accuracy")
cv_knn = cross_val_score(pipe_knn, X_corrupt, y, cv=5, scoring="accuracy")

print("=== Missing Data Strategy Benchmark ===")
print(f"Median Imputer + MissingIndicator 5-Fold CV Accuracy: {np.mean(cv_median):.4f} +/- {np.std(cv_median):.4f}")
print(f"KNNImputer (k=5) 5-Fold CV Accuracy:                  {np.mean(cv_knn):.4f} +/- {np.std(cv_knn):.4f}")

Implications: security, privacy, performance, scalability, and cost

DimensionCharacteristicPractical Implication
Privacy Inversion in MNAR DataMissingness flags reveal private traits.MissingIndicator on medical tests can reveal that a patient has a condition even if the numerical test result is omitted.
KNNImputer Compute ScalingQuadratic O(N^2 * D) pairwise distances.KNNImputer is too slow for real-time inference on millions of rows. Use SimpleImputer or native GBDT routing in low-latency production APIs.
Train/Serve Skew in ImputationMissingness ratios shifting in production.If a sensor starts failing 80% of the time in production compared to 5% during training, imputed values will drift; monitor missingness rates with Prometheus/Evidently.
Categorical Imputation Mode BiasMode imputation inflating majority class.In high-cardinality categories with 40% missingness, mode imputation creates massive artificial spikes; use a dedicated "Missing" category token instead.

Alternatives: free, open source, and commercial

Imputation Tool / LibraryMethodologyBest Used For
SimpleImputer(add_indicator=True)Fast univariate summary + boolean flagProduction linear models and neural networks.
KNNImputer (scikit-learn)NaN-Euclidean nearest neighbor averagingSmall-to-medium tabular datasets (N < 50,000).
IterativeImputer (scikit-learn MICE)Chained Bayesian regression loopsComplex multivariate clinical/survey datasets.
LightGBM / XGBoost Native NaNsSparsity-aware default branch routingIndustrial tabular gradient boosting (No imputation needed).
Datawig (Deep Learning Imputation)Deep neural network tabular imputationComplex multi-modal tabular data with text/images.

Imputation MethodHandles Non-LinearityProduces Indicator FlagsInference SpeedScalability (N > 100k)
Listwise Deletion (dropna)N/A (Discards data)NoInstantDiscards too many rows
SimpleImputerNoOptional (add_indicator)MicrosecondsExcellent (O(N))
KNNImputerYes (Local neighbors)NoMillisecondsPoor (O(N^2))
IterativeImputer (MICE)Yes (Regression)NoSecondsMedium (O(N * D^2))
Native GBDT BranchingYes (Optimal split)Built-inMicrosecondsUltra-High

When to use it β€” and when not to

When to USE Conditional Imputation (KNNImputer / SimpleImputer + MissingIndicator):

When NOT to perform Heavy Manual Imputation:


Knowledge check

  1. Rubin Taxonomy: MCAR (random), MAR (depends on observed features), MNAR (informative missingness).
  2. Listwise Deletion Flaw: dropna() discards massive portions of data and introduces severe selection bias.
  3. NaN-Euclidean Metric: Scales observed squared differences by D_{total} / D_{valid}.
  4. Native GBDT Handling: Trees evaluate sending NaNs left vs right and pick the direction maximizing split gain.

Hands-on exercise

In this hands-on exercise, you will implement the compute_nan_euclidean_distance formula and build a distance-weighted KNNImputer from scratch.

import numpy as np

# Step 1: Implement NaN-Euclidean Distance
def nan_euclidean_dist(u, v):
    u, v = np.asarray(u, dtype=float), np.asarray(v, dtype=float)
    valid = ~np.isnan(u) & ~np.isnan(v)
    k = np.sum(valid)
    if k == 0:
        return float("inf")
    diffs_sq = (u[valid] - v[valid]) ** 2
    return np.sqrt((len(u) / k) * np.sum(diffs_sq))

# Step 2: Implement KNN Imputer from Scratch
def knn_imputer_scratch(X, k=2):
    X = np.asarray(X, dtype=float).copy()
    n_samples, n_features = X.shape
    col_means = np.nanmean(X, axis=0)
    
    for i in range(n_samples):
        row = X[i]
        nan_cols = np.where(np.isnan(row))[0]
        if len(nan_cols) == 0:
            continue
        
        # Calculate distances to all other samples
        dists = []
        for j in range(n_samples):
            if i == j:
                dists.append((float("inf"), j))
            else:
                dists.append((nan_euclidean_dist(row, X[j]), j))
        
        dists.sort(key=lambda x: x[0])
        nbrs = [idx for d, idx in dists if not np.isinf(d)][:k]
        
        for c in nan_cols:
            vals = [X[nbr, c] for nbr in nbrs if not np.isnan(X[nbr, c])]
            X[i, c] = np.mean(vals) if len(vals) > 0 else col_means[c]
            
    return X

# Step 3: Test on Corrupted Matrix
X_raw = np.array([
    [10.0, np.nan, 100.0],
    [10.0, 50.0, 100.0],
    [10.0, 52.0, 100.0],
    [90.0, 900.0, 900.0]
])

X_imputed = knn_imputer_scratch(X_raw, k=2)

print("=== KNN Imputation Scratch Verification ===")
print("Original Row 0:", X_raw[0])
print("Imputed Row 0: ", np.round(X_imputed[0], 2))
print(f"Imputed Value:   {X_imputed[0, 1]:.2f} (Expected average of [50.0, 52.0] = 51.00)")

Expected output

=== KNN Imputation Scratch Verification ===
Original Row 0: [ 10.  nan 100.]
Imputed Row 0:  [ 10.  51. 100.]
Imputed Value:   51.00 (Expected average of [50.0, 52.0] = 51.00)

Validate your work

  1. Confirm that X_imputed[0, 1] == 51.0 (mean of the 2 nearest neighbors [10, 50, 100] and [10, 52, 100]).
  2. Verify that np.isnan(X_imputed).any() == False.
  3. Confirm that nan_euclidean_dist([1, np.nan], [4, np.nan]) == np.sqrt(2/1 * 9) = 4.2426.

Troubleshooting

Common mistakes

  1. Imputing -999 for Linear/SVM Models: Forces gradient descent and hyperplanes to treat -999 as a valid numerical point.
  2. Dropping Rows in Production Inference: The production API cannot drop user requests; it must impute missing values to serve a prediction.

Practice assignment

  1. Implement IterativeImputer (MICE) Round-Robin Loop: Write mice_imputer_scratch(X, max_iter=5) that initializes NaNs with column medians and iteratively predicts each missing column using Ridge regression on all other features.
  2. Implement Categorical Missing Imputation: Write CategoricalImputer(fill_value="Missing") replacing missing strings with a dedicated distinct token.

Extension challenge

Build an Enterprise Missing Data Resilience Benchmark:

  1. Ingest the California Housing dataset.
  2. Inject synthetic missingness under 3 experimental conditions: (a) 30% MCAR, (b) 30% MAR, (c) 30% MNAR.
  3. Benchmark 4 end-to-end pipelines:
    • Pipeline 1: SimpleImputer(mean) + Ridge
    • Pipeline 2: SimpleImputer(median) + MissingIndicator + Ridge
    • Pipeline 3: KNNImputer(k=5) + Ridge
    • Pipeline 4: Native LightGBM (Zero imputation)
  4. Plot comparative RMSE and test runtime across all 3 missingness mechanisms.

Quiz

Q1. What is the fundamental difference between Missing Completely at Random (MCAR) and Missing Not at Random (MNAR) in Donald Rubin’s taxonomy?

  1. Under MCAR, the probability of missingness is completely independent of both observed and unobserved data; under MNAR, the probability of missingness depends directly on the unobserved value itself (e.g. wealthy individuals refusing to disclose high income)
  2. MCAR only applies to integers; MNAR only applies to text strings
  3. MCAR means 100% of data is missing
  4. MNAR means missing values were caused by computer hardware failure
Show answer

Answer: A. Under MCAR, the probability of missingness is completely independent of both observed and unobserved data; under MNAR, the probability of missingness depends directly on the unobserved value itself (e.g. wealthy individuals refusing to disclose high income)

MCAR is pure random coin-flip missingness. MNAR contains informative signal because the missingness mechanism is linked to the true unobserved quantity.

Q2. Why is Listwise Deletion (calling df.dropna() to delete all rows with any missing value) usually a terrible practice in applied machine learning?

  1. It drastically reduces sample size N (often throwing away 70-90% of observations) and introduces severe selection bias if data is MAR or MNAR, distorting population distributions
  2. Listwise deletion is illegal in Python
  3. Listwise deletion causes memory leaks
  4. Listwise deletion only works for linear models
Show answer

Answer: A. It drastically reduces sample size N (often throwing away 70-90% of observations) and introduces severe selection bias if data is MAR or MNAR, distorting population distributions

If each of 20 features has 5% independent missingness, dropping rows with any missing value discards (1 - 0.95^20) = 64% of all training samples, destroying predictive power.

Q3. What is the formula for NaN-aware Euclidean distance between two vectors u and v with missing entries?

  1. d(u, v) = sqrt( (D_total / D_valid) * sum_{j in valid} (u_j - v_j)^2 ), where D_total / D_valid scales the observed squared differences up to account for unobserved dimensions
  2. d(u, v) = sum |u_j - v_j|
  3. d(u, v) = sqrt( sum (u_j - v_j)^2 ) with NaNs replaced by 0
  4. d(u, v) = max(u) - min(v)
Show answer

Answer: A. d(u, v) = sqrt( (D_total / D_valid) * sum_{j in valid} (u_j - v_j)^2 ), where D_total / D_valid scales the observed squared differences up to account for unobserved dimensions

The scaling factor D_total / D_valid adjusts the computed distance so pairs with fewer overlapping coordinates are fairly compared to pairs with full overlap.

Q4. Why is combining SimpleImputer(strategy="median") with MissingIndicator(add_indicator=True) highly effective for linear models on MNAR data?

  1. The median fills numerical gaps with a stable baseline, while the binary MissingIndicator feature flag allows linear models to learn a dedicated weight for the informative missingness condition
  2. MissingIndicator converts all numbers to integers
  3. It runs 100x faster than mean imputation
  4. It prevents overfitting automatically
Show answer

Answer: A. The median fills numerical gaps with a stable baseline, while the binary MissingIndicator feature flag allows linear models to learn a dedicated weight for the informative missingness condition

If missingness is informative (e.g. patient didn’t take blood test because they felt healthy), the binary missing flag carries vital predictive signal.

Q5. How do Gradient Boosted Decision Trees (XGBoost, LightGBM, CatBoost) natively handle missing values without manual imputation?

  1. At each decision split, the algorithm evaluates sending all samples with NaN to the left child versus the right child, and picks the default direction that maximizes the split loss reduction gain
  2. They delete rows with NaNs during tree building
  3. They replace NaNs with the number -999
  4. They convert NaNs to zero
Show answer

Answer: A. At each decision split, the algorithm evaluates sending all samples with NaN to the left child versus the right child, and picks the default direction that maximizes the split loss reduction gain

GBDTs treat missingness as a distinct branch choice, finding the optimal default child direction directly during greedy split optimization.

Q6. How does IterativeImputer (Multivariate Imputation by Chained Equations / MICE) work?

  1. It models each feature with missing values as a function of all other features in a round-robin regression loop, iteratively updating estimates until predictions stabilize
  2. It computes the global dataset median 100 times
  3. It clusters the data with K-Means
  4. It drops columns one by one
Show answer

Answer: A. It models each feature with missing values as a function of all other features in a round-robin regression loop, iteratively updating estimates until predictions stabilize

MICE treats missing value imputation as a series of predictive modeling tasks, preserving complex multivariate relationships across features.

Q7. What is the computational complexity limitation of KNNImputer on large datasets?

  1. KNNImputer requires computing all pairwise NaN-Euclidean distances across all N samples, scaling as O(N^2 * D), which becomes prohibitively slow for large tabular datasets (N > 50,000)
  2. KNNImputer cannot run on multi-core CPUs
  3. KNNImputer is limited to 10 features
  4. KNNImputer only works on binary data
Show answer

Answer: A. KNNImputer requires computing all pairwise NaN-Euclidean distances across all N samples, scaling as O(N^2 * D), which becomes prohibitively slow for large tabular datasets (N > 50,000)

Finding nearest neighbors requires O(N^2) pairwise distance computations, making KNNImputer expensive for large-scale enterprise datasets.

Q8. Why MUST missing value imputers be fitted strictly on the training set and NOT the combined dataset?

  1. Computing imputation statistics (such as mean or median) across the full dataset causes data leakage, allowing test fold target information and distributions to contaminate training
  2. Imputers cannot process more than 1000 rows
  3. Test data cannot contain NaNs
  4. Scikit-learn crashes if you fit on test data
Show answer

Answer: A. Computing imputation statistics (such as mean or median) across the full dataset causes data leakage, allowing test fold target information and distributions to contaminate training

Imputing globally leaks test set distribution medians and correlations into training folds, producing artificially optimistic validation scores.

Glossary

Missing Completely at Random (MCAR)
A missing data mechanism where the probability of missingness is completely independent of both observed and unobserved data.
Missing at Random (MAR)
A missing data mechanism where missingness depends systematically on observed features but not on the unobserved missing value itself.
Missing Not at Random (MNAR)
A missing data mechanism where the probability of missingness depends directly on the unobserved value itself, carrying informative signal.
Listwise Deletion (Complete Case Analysis)
Discarding any observation that contains one or more missing values across any feature column.
SimpleImputer
A univariate imputation transformer that replaces missing values with fixed summary statistics (mean, median, mode, or constant).
MissingIndicator
A binary transformation that outputs boolean indicator features marking the exact coordinates of missing data in the original matrix.
NaN-Euclidean Distance
A modified Euclidean distance metric that calculates pairwise distances across mutually observed coordinates and scales by total dimension ratio.
KNNImputer
A multivariate imputation algorithm that imputes missing coordinates using the distance-weighted average of the k nearest neighbors.
IterativeImputer (MICE)
Multivariate Imputation by Chained Equations: modeling each missing feature as a regression function of all other features in round-robin cycles.
Default Split Direction (GBDT NaNs)
The optimal tree branching direction (left or right) chosen by gradient boosted trees to route missing values based on maximum split gain.

Sources and further reading


Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.