Chapter 4 of 42 · ~18 min read & lab+60 XP
Chapter 4 · Machine Learning

Data Cleaning: Handling Missing Values, Duplicates & Outliers

MCAR vs. MAR vs. MNAR missingness, Mean/Median/KNN imputation, Missingness Indicator flags, and IQR vs. Z-Score outlier treatment

What Is It?

Data Cleaning prepares raw tables for ML by fixing missing values (NaNs), removing duplicate records, and detecting or capping extreme outliers before training.

Why Is It Required?

Most algorithms (Linear Regression, SVM, KNN, Neural Nets) crash on NaN values, and a single corrupted outlier (like age = 999) can tilt an entire regression line.

Everyday Analogy: Removing rocks and weeds from soil before planting seeds — even premium seeds won't grow in a pile of gravel.
Why ML Engineers & Data Scientists Actually Need This

Real-world production databases are 10%–40% missing or messy — clean imputation is the difference between a working model and a ValueError: Input contains NaN crash.

ML / AI Engineer

Production pipelines must handle unseen NaN values at inference time without crashing, even if a column had zero missing values during training.

Data Scientist

Understanding why a value is missing (e.g., blank credit_history means a new borrower) often yields the strongest predictive feature in the entire table.

Interview & Debug Edge

Classic interview question: 'When should you impute with the median instead of the mean, and when should you add a missingness flag?'

Step 0 · Test Your Gut Before Any Math!

A house-price column is heavily right-skewed with a few $50M mansions. Which single-value imputer is safest for missing prices?

What You Will Master in This Chapter
  • Choose between dropping rows, Mean/Median/Mode imputation, and KNN/Iterative imputation.
  • Explain why adding a binary was_missing indicator column often boosts model accuracy when data is Missing Not At Random (MNAR).
  • Detect outliers using both the IQR rule (1.5×IQR1.5 \times \text{IQR}) and Z-Score (∣z∣>3|z| > 3), and choose between dropping vs. Winsorizing (clipping).
  • Fit every imputer strictly on the training split to prevent data leakage.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
IQR = Q_3 - Q_1Say aloud:“Interquartile Range”
Plain-English Meaning
The spread of the middle 50% of data (75th percentile minus 25th percentile).
Everyday Example
If Q1=20 and Q3=40, IQR=20, so upper fence = 40 + 1.5×20 = 70.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Missing values and outliers are signals, not just annoyances. Before blindly deleting rows or filling zeros, ask two questions: (1) Is the missingness itself informative? (add a col_is_missing flag!), and (2) Is an outlier a sensor bug (age = -5) or a real high-value event (a VIP whale customer)?

1. Missing Value Strategies: Drop vs. Impute vs. Flag

Everyday Story First (Zero Math Yet!)

Suppose a medical form has a blank field for blood_sugar. Maybe the nurse forgot to type it (random), or maybe the doctor skipped the test because the patient looked completely healthy (informative!).

Practical Imputation Playbook

  • Numerical (symmetric): Mean imputation.
  • Numerical (skewed / has outliers): Median imputation (safe default!).
  • Categorical: Mode (most frequent) OR a dedicated "Missing" category (often best!).
  • Missingness Indicator (col_was_missing = 0/1): Always test adding a binary flag whenever >5%> 5\% of a column is missing — if missingness is MNAR (Missing Not At Random), the flag carries huge predictive signal!
  • Leakage Rule: Compute the median/mode ONLY on the training set, then apply that exact number to validation and test sets.

2. Outlier Detection: IQR Fences vs. Z-Score & Winsorization

Everyday Story First (Zero Math Yet!)

One typo turning $50.00 into $50,000 can ruin an entire Linear Regression slope. Yet blindly deleting valid high-spend customers can blind your model to VIPs.

Two Standard Detection Rules

  1. IQR Rule (Best for Skewed Data): Flag values below Q1−1.5⋅IQRQ_1 - 1.5 \cdot \text{IQR} or above Q3+1.5⋅IQRQ_3 + 1.5 \cdot \text{IQR}.
  2. Z-Score Rule (Best for Bell-Shaped Data): Flag values with ∣z∣>3|z| > 3.

Three Ways to Treat Outliers

  • Drop if it is clearly a data-entry/sensor bug (age = 999, weight = -10).
  • Winsorize (Clip) to the 1st and 99th percentiles so extreme valid values don't explode gradients.
  • Keep + Use Robust Models: Tree models (Random Forest, XGBoost) and Huber Loss naturally ignore extreme input outliers.
Hands-On Mini-Lab · Inject One Outlier ($1,000k) and Watch 3 Scalers React!

Raw salaries ($k): [40, 60, 80, 100, 1000]. Look at what happens to the 4 normal employees [40, 60, 80, 100]:

MinMax [0, 1]
[0.00, 0.02, 0.04, 0.06]

CRUSHED into [0.00, 0.06]!

StandardScaler (μ, σ)
[-0.58, -0.53, -0.47, -0.42]

All 4 normal people look negative!

RobustScaler (Med, IQR)
[-1.00, -0.50, 0.00, 0.50]

100% UNCHANGED by the outlier!

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Almost never! Filling missing age or temperature with 0 tells the model the person is a newborn or it is freezing outside, distorting means and slopes.

Interactive Visual Lab
Lab Challenge: Compare how outliers distort standard scaling vs. robust preprocessing.
Interactive Animation • Feature Scaling & Optimization

Unscaled Ravine (Zig-Zag!) vs. StandardScaler Circle (Straight Shot!)

Watch both gradient-descent marbles race simultaneously with the exact same learning rate!

Raw Unscaled (Age vs. Salary)
After StandardScaler (μ=0, σ=1)
0%
GD Step 0/12
Raw Unscaled: steep salary-vs-age walls force wild vertical oscillation. StandardScaler (μ=0, σ=1): circular contours send gradients straight to the global minimum in half the steps!
Intuition Takeaway: Clean data by imputing skewed numbers with the training-set median, preserving informative missingness with a binary flag, and clipping (Winsorizing) extreme outliers using IQR bounds.
Production NumPy & PyTorch Code Patterns
import numpy as np

# Leakage-Free Median Imputation + Missingness Flag + IQR Clipping
train = np.array([22.0, 25.0, np.nan, 28.0, 30.0, 29.0, 250.0])  # 250 is an outlier
test  = np.array([24.0, np.nan, 310.0])

# 1. Fit statistics STRICTLY on training data
train_valid = train[~np.isnan(train)]
med = float(np.median(train_valid))
q1, q3 = np.percentile(train_valid, [25, 75])
iqr = q3 - q1
lo, hi = q1 - 1.5 * iqr, q3 + 1.5 * iqr

def clean_feature(arr: np.ndarray):
    was_missing = np.isnan(arr).astype(float)
    filled = np.where(np.isnan(arr), med, arr)
    clipped = np.clip(filled, lo, hi)
    return np.column_stack([clipped, was_missing])

print(f"Train median={med:.1f}, IQR bounds=[{lo:.1f}, {hi:.1f}]")
print("Cleaned test [value, was_missing]:\n", clean_feature(test))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Computing the median on the entire dataset before train_test_split.
Best Practice: Always split first, then .fit() the imputer on X_train and .transform() X_val and X_test.
Chapter Mastery Check (+60 XP)
Score: 0 / 1
1Why is adding a binary col_was_missing indicator column often helpful alongside median imputation?

Apply What You Learned — Solve Matching Coding Problems