Outlier detection and treatment
The key question: Is this outlier telling us something important, or is it corrupting our model?
Understanding Outliers
WHY do outliers matter?
- Model sensitivity: Many ML algorithms (linear regression, k-means, PCA) are mean-based and highly sensitive to extreme values
- Gradient instability: Large outliers create steep gradients, causing optimization to oscillate
- Feature scale distortion: Outliers inflate variance, making normalization ineffective
- Decision boundary shift: In classification, outliers pull boundaries toward them
WHAT makes a point an outlier?
- Statistical deviation (e.g., >3σ from mean)
- Isolation in feature space
- Low local density
- Domain-specific thresholds (e.g., human age > 150 years)
Detection Methods
1. Statistical Methods (Univariate)
Derivation:
- Start with the definition of standard deviation:
- This measures typical spread around
- Dividing by gives a dimensionless measure: "how many typical spreads away?"
- By the 68-95-99.7 rule for normal distributions: ~99.7% of data lies within
- WHY this works: Standardizes comparison across different scales
Threshold: (or 2.5, depending on tolerance)
WHY this step works: The z-score converts absolute distances to relative distances, making it scale-invariant.
Derivation:
- (25th percentile) and (75th percentile) define the middle 50% of data
- IQR measures the spread of this central bulk
- WHY 1.5? Tukey's empirical rule: balances sensitivity vs. false positives. For normal data, this catches ~0.7% as outliers
- Points beyond fences are far from the bulk, even if distribution is skewed
WHY this step works: Uses percentiles (rank-based), so immune to extreme values that would distort mean/std.
Z-score approach:
mean = 43.6, std = 42.8
z_150 = (150 - 43.6) / 42.8 = 2.48WHY this step? We're standardizing the distance. Result: 150 is NOT flaged (|z| < 3) because the outlier itself inflated std!
IQR approach:
Q1 = 25.5, Q3 = 33.5, IQR = 8
Upper fence = 33.5 + 1.5*8 = 45.5WHY this step? We use the middle 50% to define "normal," ignoring extremes. Result: 150 > 45.5, correctly flagged.
Lesson: IQR is robust when outliers contaminate mean/std.
2. Multivariate Methods
where is the mean vector, is the covariance matrix.
Derivation from first principles:
- Euclidean distance in :
- Problem: Treats all dimensions equally, ignores correlations
- Standardize each dimension: Divide by → distance in "units of spread"
- Problem: Still ignores correlations (e.g., height & weight are correlated)
- Account for covariance: The covariance matrix encodes both variances (diagonal) and correlations (off-diagonal)
- Whitening transformation: transforms data to unit sphere where dimensions are uncorrelated
- Final distance: is the squared distance in this transformed space
WHY this works:
- If features are independent, is diagonal → reduces to standardized Euclidean
- If corelated, it down-weights the "redundant" dimensions
- Follows a distribution under normality, giving a statistical threshold
Threshold: (97.5th percentile of chi-squared with degrees of freedom)
WHY Mahalanobis helps:
- Euclidean distance treats both equally far from mean [2000 sqft, 3 beds]
- Mahalanobis recognizes sqft and bedrooms are correlated (r ≈ 0.8)
- House A violates this correlation → higher , flaged as anomaly
- House B follows the pattern → lower , not flagged
Step-by-step calculation (simplified 2D):
mu = [2000, 3]
Sigma = [[1e6, 0.8*1000*2], # cov(sqft, beds) = r*σ_sqft*σ_beds
[0.8*1000*2, 4]]
Sigma_inv = inverse(Sigma)
x_A = [5000, 2]
diff_A = x_A - mu = [3000, -1]
D_M_A = sqrt(diff_A^T @ Sigma_inv @ diff_A) ≈ 8.2WHY this value? The negative correlation component (many sqft but few beds) adds to distance.
3. Density-Based: Local Outlier Factor (LOF)
where local reachability density (lrd) is:
and reachability distance:
Derivation logic:
- k-distance: Distance to the -th nearest neighbor of
- Reachability distance: Uses -dist as "smoothing" factor
- WHY? Prevents instability when points are very close
- If is far from , use actual distance
- If is in 's neighborhood, use -dist(o) to stabilize
- LRD: Inverse of average reachability distance → higher lrd = denser region
- LOF: Ratio of neighbors' density to point's density
- LOF ≈ 1: similar density to neighbors (normal)
- LOF >> 1: much lower density than neighbors (outlier)
WHY this works: Adapts to varying densities. A point in a sparse cluster isn't an outlier if its neighbors are also sparse.
Dense cluster A: [points at (0,0) ± 0.5]
Dense cluster B: [points at (10,0) ± 0.5]
Sparse middle: (5, 0)
Far outlier: (20, 5)
Z-score (global): Both (5,0) and (20,5) are flagged (far from global mean ≈ (5,0)) LOF (local):
- (20,5): LOF ≈ 5 (neighbors are at distance ~11, but their neighbors are at ~0.5) → outlier
- (5,0): LOF ≈ 1.2 (neighbors from both clusters are also relatively isolated) → not outlier
WHY this matters: The middle point is expected (transition region), but far point is truly anomalous.
Treatment Strategies
When to KEEP outliers:
- Domain knowledge confirms it's valid (e.g., CEO salary in employee data)
- Target of interest (fraud detection, rare disease diagnosis)
- Tree-based models (decision trees, random forests) handle outliers via splits
When to REMOVE:
- Data errors (age = 200, negative prices)
- Sample size is large (>10,000) and outliers are <0.1%
- Linear/distance-based models (regression, KNN, SVM with RBF kernel)
When to TRANSFORM:
- Reduce impact without losing information
- Medium sample size (1,000-10,000)
- Outliers have business meaning but distort statistics
Treatment Methods
1. Capping (Winsorization)
P_5 & \text{if } x_i < P_5 \\ x_i & \text{if } P_5 \leq x_i \leq P_{95} \\ P_{95} & \text{if } x_i > P_{95} \end{cases}$$ where $P_5$, $P_{95}$ are the 5th and 95th percentiles. **WHY this works**: Preserves the order (monotonicity) while limiting extreme values. Outliers still affect the model, just less so. **2. Log Transform** $$x_i^{\text{log}} = \log(x_i + c)$$ where $c$ is a constant (often 1) to handle zeros. **Derivation of why this reduces outlier impact:** - Log is a **monotonic, concave** function: $\frac{d^2}{dx^2}\log(x) = -\frac{1}{x^2} < 0$ - Concavity means: equal absolute differences at high values compress more than at low values - Example: $\log(1000) - \log(100) = \log(10) = 2.3$, but $(1000 - 100) = 900$ - The 900-unit difference in original space becomes a 2.3-unit difference in log space - **Result**: High outliers are "pulled back" toward the bulk **WHY this step works**: Converts multiplicative relationships to additive, making models more stable. **3. Robust Scaling** $$x_i^{\text{scaled}} = \frac{x_i - \text{median}}{\text{IQR}}$$ **WHY this works**: Median and IQR are computed from the middle 50%, unaffected by outliers. Compare to standard scaling $\frac{x - \mu}{\sigma}$, which outliers corrupt. **4. Bining/Discretization** $$x_i^{\text{bined}} = \begin{cases} 0 & \text{if } x_i < Q_1 \\ 1 & \text{if } Q_1 \leq x_i < Q_2 \\ 2 & \text{if } Q_2 \leq x_i < Q_3 \\ 3 & \text{if } x_i \geq Q_3 \end{cases}$$ **WHY this works**: Converts numeric to ordinal, making exact values irrelevant. A value of 1000 and 1000 both map to bin 3. > [!example] Treatment Comparison > **Scenario**: Income feature [20K, 25K, 28K, 30K, 35 500K] for predicting loan default | Method | Result | Impact on Model | |--------|--------|---------------| | **Keep** | [20K, 25K, .., 500K] | Linear model: coefficient overweights income (driven by 500K outlier) | | **Remove** | [20K, 25K, 28K, 30K, 35K] | Loses info about high earners (may be relevant: rich people default less?) | | **Cap at P95** | [20K, .., 35K, 35K] | Preserves order, but 500K→35K loses signal if high income truly matters | | **Log transform** | [9.9, 10.1, ..., 13.1] | 500K→13.1: still largest but proportional impact reduced. **Best if multiplicative effect** | | **Robust scale** | [-1.1, -0.3, 0, 0.4, 1.4, 104] | 500K→104: still extreme in scaled space (IQR only 10K) | | **Bin (quartiles)** | [0, 1, 1, 2, 2, 3] | Information loss but robust. Tree models can still split on bin3. | **Decision rule**: - If income-default relationship is **multiplicative** (e.g., 2x income → 0.5x default rate): **log transform** - If 500K is likely an error: **remove** or **cap** - If using **tree models**: **keep** (trees isolate it with splits) - If using **linear model** and high incomes are rare: **cap** or **bin** > [!mistake] Common Mistake: Blindly Removing All Outliers > **Why it feels right**: "Outliers are errors, clean them out!" **Steel-man this intuition**: Outliers do cause problems for many models. In controlled environments (lab experiments), they often are errors. **Why it's wrong**: 1. **You lose information**. In real-world data (sales, user behavior), extreme values are often the most interesting (power users, viral products). 2. **You change the population**. If you remove all incomes >100K, your model won't work for high earners. 3. **Test-time mismatch**. Production data will have outliers; if your model never saw them, it will fail. **The fix**: - **Investigate first**: Plot the outliers, check if they're errors (domain knowledge). - **Transform, don't remove**: Use robust methods that reduce impact but retain information. - **Model choice**: Use algorithms robust to outliers (trees, robust regression) if outliers are expected. - **Stratified treatment**: Cap errors, keep rare but valid cases, flag anomalies for separate handling. > [!mistake] Z-Score on Contaminated Data > **Why it feels right**: "Standard deviations are the standard way to measure spread!" **Steel-man**: Z-scores are well-grounded in theory (CLT, normal distribution) and easy to interpret. **Why it fails**: The very outliers you're trying to detect inflate $\mu$ and $\sigma$, making them **invisible**. **Example**: ``` Data: [1, 2, 3, 4, 5, 100] Mean = 19.2, Std = 39.3 Z-score of 100 = (100 - 19.2) / 39.3 = 2.05 (not flagged!) ``` **The fix**: Use **robust statistics** (median, MAD, IQR) or **iterative methods** (remove detected outliers, recalculate, repeat). > [!recall]- Explain to a 12-Year-Old > Imagine you're tracking how much time your classmates spend on homework each day. Most kids spend 1-2 hours. But one kid says they spend 15 hours—that's an **outlier**. Now, is that kid lying? Or maybe they're super dedicated? Or they misunderstood and included sleep time? You need to **detect** if they're truly different, then **decide** what to do. **Detection** is like asking: "Is this kid's number way too weird?" You can: - Check if they're more than "3 big jumps" away from average (Z-score) - See if they're outside the range where most kids are (IQR) - Compare them to their study-group friends—if everyone in the group spends 1 hour but they claim 15, that's suspicious (LOF) **Treatment** is choosing: - **Ignore them** if it's clearly wrong (maybe they wrote "15" instead of "1.5") - **Keep them** if it's real (some kids do study a lot!) - **Squish the number** down a bit so it doesn't mess up your average too much (capping or log transform) The key: Don't just delete weird numbers automatically. Understand **why** they're weird first! > [!mnemonic] OUTLIER Treatment > **O**bserve context (domain knowledge) > **U**se robust statistics (median/IQR, not mean/std) > **T**ransform before removing (log, cap) > **L**ocal methods for varying density (LOF) > **I**nvestigate causes (error vs. rare event) > **E**valuate model impact (test with/without) > **R**etain if target-relevant (fraud, anomalies) ## Algorithm-Specific Considerations | Algorithm | Sensitivity | Recommended Approach | |--------|-------------|----------------------| | **Linear Regression** | High (OLS minimizes squared errors → outliers dominate) | Remove/cap or use robust regression (Huber, RANSAC) | | **Logistic Regression** | Medium (sigmoid bounds influence, but still gradient-based) | Cap extreme features, use regularization (L1/L2) | | **Decision Trees** | Low (splits isolate outliers into small partitions) | Keep outliers (tree adapts), but cap if >5% of data | | **Random Forest** | Very Low (averaging + bagging reduces outlier impact) | Keep outliers | | **K-Means** | High (mean-based centroids pulled by outliers) | Remove or use K-medoids/DBSCAN | | **KNN** | High (distance-based → outliers distort neighborhoods) | Remove or use robust scaling + distance weighting | | **SVM** | Medium (depends on kernel; RBF sensitive, linear less so) | Scale with robust scaler, cap extremes | | **Neural Networks** | Medium (mini-batch gradient averaging helps, but large errors still propagate) | Clip gradients, use batch norm, cap/log transform | ## Connections - [[2.1.01-Missing-data-handling]] - Outliers and missing data often co-occur; both require domain knowledge - [[2.1.02-Feature-scalingand-normalization]] - Robust scaling explicitly handles outliers; standard scaling doesn't - [[2.2.01-Feature-selection]] - Outliers can distort correlation-based selection methods - [[3.3.02-Anomaly-detection]] - Outlier detection is a form of unsupervised anomaly detection - [[4.1.03-Regularization]] - L1/L2 regularization reduces model sensitivity to outliers in training data - [[2.3.01-Encoding-categorical-variables]] - Rare categories act like outliers in categorical space #flashcards/ai-ml What is an outlier? :: A data point that differs significantly from other observations, measured by statistical distance (z-score, IQR) or density (LOF). Why does the IQR method use 1.5 × IQR for fences? ::: Tukey's empirical rule: balances sensitivity and false positives. For normal data, catches ~0.7% as outliers. Uses percentiles, so robust to the outliers themselves. Derive the Mahalanobis distance formula from Euclidean distance :: Start with Euclidean $\sqrt{(x-\mu)^T(x-\mu)}$. To account for different scales and correlations, transform to space where covariance is identity: $\Sigma^{-1/2}(x-\mu)$. Distance in transformed space is $(x-\mu)^T\Sigma^{-1}(x-\mu)$. What does LOF ≈ 1 vs LOF >> 1 indicate? ::: LOF ≈ 1 means point's density is similar to neighbors (normal). LOF >> 1 means point's local density is much lower than neighbors (outlier). Adapts to varying densities. When should you KEEP outliers instead of removing them? ::: (1) Domain knowledge confirms validity, (2) They're the target of interest (fraud, anomalies), (3) Using tree-based models that handle them via splits, (4) Sample size is small and removing loses signal. Why does log transform reduce outlier impact? ::: Log is concave: $d^2/dx^2 \log(x) < 0$. Equal absolute differences at high values compress more than at low values. E.g., 1000→100 (900 units) becomes log(1000)→log(100) (2.3 units). Pulls extremes toward bulk. Derive robust scaling formula and explain why it works ::: $x_{\text{scaled}} = (x - \text{median}) / \text{IQR}$. Median and IQR are computed from middle 50% of data, so outliers don't affect them. Compare to $(x - \mu)/\sigma$, where outliers inflate both $\mu$ and $\sigma$. Why does z-score fail on contaminated data? ::: Outliers inflate both mean $\mu$ and std $\sigma$. This makes outliers appear closer to mean in z-score space. E.g., [1,2,3,4,5,100]: $\mu$=19.2, $\sigma$=39.3, z(100)=2.05 (not flagged). Use robust stats (median, MAD) instead. Compare Linear Regression vs Random Forest sensitivity to outliers ::: Linear Regression: High (OLS minimizes squared errors → outliers dominate loss). Random Forest: Very Low (bagging + averaging + tree splits isolate outliers). Keep outliers for RF, remove/cap for LR. What's the reachability distance in LOF and why use it? ::: $\text{reach-dist}_k(x,o) = \max(\text{dist}(x,o), k\text{-dist}(o))$. Uses $k$-dist as smoothing factor to prevent instability when points are very close. If $x$ far from $o$, use actual distance; if $x$ in $o$'s neighborhood, use $k$-dist(o). When to use capping vs log transform for outliers? ::: Capping: When outliers are likely errors or extreme values don't add signal. Preserves order. Log transform: When relationship is multiplicative (e.g., income → default) or distribution is log-normal. Reduces impact proportionally. Why is Mahalanobis distance better than Euclidean for corelated features? ::: Euclidean treats all dimensions equally, ignoring correlations. Mahalanobis uses covariance matrix $\Sigma^{-1}$ to down-weight redundant (correlated) dimensions and account for different scales. E.g., large house with few bedrooms violates sqft-bedroom correlation → high $D_M$. ## 🖼️ Concept Map ```mermaid flowchart TD OUT[Outlier] TYPE[Legit signal / error / variation] WHY[Why they matter] MEAN[Mean-based algorithms] DETECT[Detection methods] STAT[Statistical univariate] Z[Z-Score] IQR[IQR Method] ISO[Isolation / low density] THRESH[Thresholds] OUT -->|can be| TYPE OUT -->|impacts| WHY WHY -->|distort| MEAN OUT -->|found via| DETECT DETECT -->|includes| STAT STAT -->|uses| Z STAT -->|uses| IQR Z -->|flags if| THRESH IQR -->|flags beyond| THRESH DETECT -->|also uses| ISO Z -->|assumes normality| MEAN IQR -->|robust to skew| STAT ``` ## 🔊 Hinglish (regional understanding) > [!intuition]- Hinglish mein samjho > ![[audio/2.1.03-Outlier-detection-and-treatment.mp3]] ## 🔊 Hinglish (regional understanding) > [!intuition]- Hinglish mein samjho > Dekho, outliers samajhna bahut simple hai — ye woh data points hain jo baaki sab se ekdum alag behave karte hain, jaise class ka woh "weird kid" jo sabse alag hi chalta hai. Ab yaha core intuition ye hai ki har outlier galat nahi hota. Kabhi ye ek genuine signal hota hai (jaise fraud ya koi rare disease), aur kabhi ye sirf ek error hota hai (sensor kharab, ya data entry mein galti). To asli sawaal yahi hai — kya ye point humein kuch important bata raha hai, ya humaare model ko corrupt kar raha hai? > > Ye matter isliye karta hai kyunki bahut saare ML algorithms — jaise linear regression, k-means, PCA — mean pe based hote hain, aur mean extreme values se easily distort ho jaata hai. Ek hi bada outlier poore model ka gradient unstable kar sakta hai, variance ko inflate kar deta hai, aur classification mein decision boundary ko apni taraf kheench leta hai. Detection ke liye do main methods yaad rakho: **Z-score** batata hai ki point mean se kitne standard deviations door hai (usually |z| > 3 outlier), lekin iska ek problem hai — jab outlier khud hi std ko badha deta hai, toh woh chhup jaata hai. Iske against **IQR method** middle 50% data (Q1 se Q3) use karke fences banata hai, isliye ye extreme values se affect nahi hota — yani zyada robust hai. > > Woh ages waala example dekho: [22, 25...150]. Z-score ne 150 ko outlier maana hi nahi kyunki us 150 ne khud std itna bada kar diya! Lekin IQR ne turant pakad liya kyunki woh sirf central bulk pe dhyaan deta hai. Ye lesson practically bahut kaam ka hai — jab tumhare data mein already extreme values ghusi hui ho, tab mean-based methods dhokha de sakte hain, aur rank-based (percentile) methods jaise IQR zyada trustworthy hote hain. Aur jab features aapas mein correlated ho, tab **Mahalanobis distance** use karte ho jo correlation aur scale dono ko account karta hai. Bas yahi intuition apne mind mein clear rakho — tool tabhi sahi choose kar paoge.