Outlier Detection
After this lesson, you will be able to:
- Detect outliers using the right statistical tool — Z-score for clean bell-shaped data, modified Z-score (with MAD) for skewed or heavy-tailed data, and the IQR rule when you cannot trust normality at all
- Use multivariate methods — Mahalanobis distance, Local Outlier Factor (LOF), and Isolation Forest — to catch points that look normal on each axis individually but together form an impossible combination
- Decide what to do with each outlier — drop it, cap it (winsorize), transform the variable (log), or keep it — based on whether the value is a data error, a rare-but-real event, or the actual signal you are trying to model
- Avoid the four traps that ruin outlier work — removing points before splitting train/test, using mean-and-std on heavy-tailed data, deleting all extreme values without investigating, and treating fraud detection like data cleaning
Before you start
Don't worry if "outlier" feels like a fuzzy word — by the end of this lesson you will have four sharp definitions and a flowchart for when to use each.
#What Is an Outlier, Really?
There are three reasons a point might be flagged as an outlier, and your response depends entirely on which one you are looking at:
- Data-entry error: Someone typed "999" for missing age. Drop it (or impute it).
- Measurement error: A broken thermometer reported 200°C in your weather data. Drop it.
- Rare-but-real event: A genuine $9,000 transaction (a wedding ring, an emergency vet bill, fraud). Do not drop it — this is often the signal you are trying to predict.
The hardest cases are when you cannot tell which of the three you have. That is when you reach for the multivariate methods later in this lesson.
#Statistical Methods: When You Trust the Distribution
#Z-Score: The Bell-Curve Detector
The classic test: how many standard deviations is this point from the mean?
The 0.27% beyond three standard deviations is derived in Descriptive Statistics & Distributions, the 1.5 IQR fence below is derived in Quantiles, Shape & Reading Real Data, and so is the 0.6745 constant of the modified Z-score. Here is a result that is new, and that explains the snake-eating-its-tail problem exactly: there is a ceiling on how large a Z-score can get.
#Modified Z-Score: The Robust Cousin
#IQR Rule: The Distribution-Free Workhorse
Tukey's classic. No assumptions about shape — just look at the middle 50% and flag anything far from it.
A small startup's payroll has eight salaries: seven between $40K and $200K, and one founder paid $1.2M. You apply the standard Z-score rule (|Z| > 3). What happens?
This is the snake-eating-its-tail problem. The single huge value pulls up both the mean and the standard deviation, so when you compute its own Z-score, the denominator has been inflated by the very outlier you are trying to catch. The modified Z-score (using median + MAD) does not have this problem — that is exactly why it exists.
#Multivariate Methods: When Single-Axis Detection Fails
A 6-foot-tall person is normal. A 100-pound person is normal. A 6-foot-tall, 100-pound person is an outlier. None of the univariate detectors above can find them.
#Mahalanobis Distance
Generalize the Z-score to multiple dimensions, accounting for correlations between features.
Why this distance equals the ordinary distance after whitening the data, and the 2D radius 2.448 that holds 95% of the Gaussian, are derived in Multivariate Gaussian & Joint Distributions, in the Math track. In d dimensions the squared distance of Gaussian data follows a chi-squared distribution with d degrees of freedom, which is the cutoff mentioned above; that lesson works the two-dimensional case.
The catch: Mahalanobis assumes a single Gaussian blob. If your data has multiple clusters, it fails — points between clusters look "central" by the global covariance.
#Local Outlier Factor (LOF)
Compare a point's local density to the density of its neighbors. If you live in a sparse area while your neighbors live in dense areas, you are flagged.
from sklearn.neighbors import LocalOutlierFactor
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.05)
labels = lof.fit_predict(X) # -1 = outlier, +1 = inlier#Isolation Forest
A different idea entirely: build random binary trees that split the data on random features at random thresholds. Outliers, by definition, get isolated in fewer splits, because they are sparse — there is "more room around them" for a random cut to separate them.
from sklearn.ensemble import IsolationForest
iso = IsolationForest(contamination=0.01, random_state=42)
labels = iso.fit_predict(X) # -1 = outlier, +1 = inlier
scores = iso.score_samples(X) # lower = more anomalous#How the Isolation Forest Scores a Point
The score comes from the average number of random splits needed to isolate a point, compared with what is typical for a tree of that size. Two results are needed: the typical path length c(n), and the score that turns a path length into a number between 0 and 1.
Now turn the average path length of one point into a score.
The contamination setting does not change these scores. It only sets the cutoff: scikit-learn takes that percentile of the training scores as the threshold, so exactly that share of the training rows is flagged by construction (5,000 normal Gaussian points flagged 1.0% at contamination 0.01 and 5.0% at 0.05). It is an assumption about how many outliers there are, not a measurement. Set it too high and normal rows are flagged, too low and real outliers are missed.
#One-Class SVM (briefly)
Learns a tight boundary around the bulk of the data; anything outside is an outlier. Powerful but slow on large datasets and very sensitive to the kernel choice. Rarely the right first tool today — Isolation Forest and LOF have largely replaced it for tabular data, though it is still used in network-traffic anomaly detection.
#The Decision Rubric: Drop, Cap, Transform, or Keep?
Detection is the easy part. The hard question is what to do with the flagged points. Here is the decision tree professional teams actually use:
1. Is the value impossible? (age = 999, temperature = 5000°C)
→ DROP (or impute) — it's a data error.
2. Is the value rare-but-real, AND is it the signal you want to predict?
→ KEEP — this is anomaly detection, not cleaning.
(e.g. fraud, equipment failure, rare disease)
3. Is the variable heavy-tailed (income, file sizes, response times)
AND your model assumes normality?
→ TRANSFORM (log, Box-Cox, Yeo-Johnson) — keeps all data, fixes the shape.
4. Is the value real but unrepresentative of the population
you'll deploy on?
→ CAP (winsorize at 1st/99th percentile) — keeps the row, neutralizes
the extreme.
5. Is the value real and representative? Don't touch it.
#A Mini Outlier-Detection Workshop
Tests: Verify each method returns a boolean mask of the same length as the input. Verify Z-score and modified-Z disagree on the synthetic data. Verify IQR(3.0) flags strictly fewer points than IQR(1.5).
#Visualizing the Cleaning Process
#Key Takeaways
- The detector you reach for depends on the distribution shape. Z-score for clean bell curves, modified Z-score (with MAD) for skewed or heavy-tailed data, IQR when you cannot trust the shape at all, Mahalanobis or Isolation Forest when single-axis detectors miss the multivariate combinations
- Detection ≠ removal. Once you have flagged a point, ask whether it is a data error (drop), a heavy-tail expression of the same variable (transform), an unrepresentative real value (cap), or the signal you are trying to predict (keep)
- Z-score lies on the data it was meant to clean. The mean and standard deviation are themselves dragged toward the outliers, so the Z-score of the worst outlier comes back below 3 and your detector reports "all clear"; switch to median + MAD or IQR the moment you see a skewed histogram
- Multivariate outliers are invisible to univariate methods. A 6-foot, 100-pound person is normal on each axis; only Mahalanobis distance, LOF, or Isolation Forest can catch the impossible combination, and combinations are where most production fraud and anomaly cases actually live
- Fit detectors on the training set only, then apply to test. Fitting an outlier detector on the full dataset before splitting is the same kind of leakage as fitting a scaler on it; in cross-validation, the detector goes inside the sklearn Pipeline so it refits per fold
#Quick Check
Your dataset of website session durations has a histogram with a long right tail (most sessions 1-5 minutes, but some go for hours). You apply the Z-score rule with |Z| > 3 and find zero outliers. What is most likely happening?