Lesson 7 of 9
Outlier Detection: IQR, Z-Score & Isolation-Based Anomaly Filtering
Outliers can severely distort parametric machine learning models (OLS regression, neural networks, SVMs) by exerting disproportionate leverage on squared loss terms. Outliers can be caused by measurement corruption (sensor errors, impossible typos) or legitimate extreme events (high-value fraud). Detecting and handling outliers using parametric Z-scores, non-parametric Interquartile Range (IQR), and multivariate Isolation Forests is a mandatory step before model training.
Univariate vs Multivariate Outlier Detection in Code
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
# Generate synthetic dataset with normal data and injected outliers
np.random.seed(42)
n_normal = 1000
income = np.random.normal(65000, 15000, n_normal)
debt_ratio = np.random.beta(2, 5, n_normal)
# Injected extreme anomalies
n_outliers = 15
income_outliers = np.random.uniform(250000, 500000, n_outliers)
debt_outliers = np.random.uniform(0.8, 1.0, n_outliers)
df = pd.DataFrame({
'income': np.concatenate([income, income_outliers]),
'debt_ratio': np.concatenate([debt_ratio, debt_outliers])
})
# 1. UNIVARIATE IQR METHOD (Non-parametric boxplot fences)
def detect_iqr_outliers(series: pd.Series, factor=1.5):
q25 = series.quantile(0.25)
q75 = series.quantile(0.75)
iqr = q75 - q25
lower_fence = q25 - factor * iqr
upper_fence = q75 + factor * iqr
return (series < lower_fence) | (series > upper_fence)
iqr_mask = detect_iqr_outliers(df['income'])
print(f"IQR detected univariate income outliers: {iqr_mask.sum()}")
# 2. MULTIVARIATE ISOLATION FOREST
# Isolates anomalies by building random binary trees. Anomalies require fewer splits.
iso_forest = IsolationForest(contamination=0.015, random_state=42)
# -1 indicates an anomaly, 1 indicates inlier
iso_preds = iso_forest.fit_predict(df[['income', 'debt_ratio']])
df['is_anomaly'] = (iso_preds == -1)
print(f"Isolation Forest detected multivariate anomalies: {df['is_anomaly'].sum()}")
print("Sample detected anomalies:")
print(df[df['is_anomaly']].head(4))Pro Tip: Winsorization (Clipping) vs Row Deletion
Do not automatically drop outlier rows, especially in small datasets where deleting 5% of rows discards statistical power. Instead, use Winsorization (`np.clip` or `scipy.stats.mstats.winsorize`) to cap values at the 1st and 99th percentiles. This preserves the sample size while neutralizing leverage on gradient steps.
MlDetectingOutliers Visual Representation
Hands-On Challenge: Build a RobustScaler Pipeline
Compare the sensitivity of `StandardScaler` (uses mean and variance) vs `RobustScaler` (uses median and interquartile range) when applied to features containing extreme 100x outliers. Demonstrate why tree models are invariant to monotonic outlier scaling while linear models are not.
Quick Quiz & Key Concept Checks
Common Pitfall: Outlier Filtering on the Test Dataset
Never filter or remove outliers from your test partition. Your production model will encounter real-world extreme values. Removing outliers from the test set artificially sanitizes the benchmark and conceals catastrophic failure modes during deployment.