Exercises — Outlier detection and treatment
This is your self-testing lab for the parent topic. Every problem is graded from L1 (just recognise the idea) up to L5 (put it all together). Read the problem, try it on paper, THEN open the solution.
Before we start, one promise: every symbol is defined the moment it appears. If a formula uses , we say " (mu) = the average of all the numbers" right there. Nothing is assumed.

Quick symbol dictionary (we re-explain each in context too):
- ::: the -th data value (e.g. one person's age).
- (mu) ::: the mean — add all values, divide by how many there are.
- (sigma) ::: the standard deviation — the typical distance of a point from the mean.
- ::: the 25th and 75th percentiles — cut points where 25% and 75% of sorted data lie below.
- ::: the 5th and 95th percentiles — the values below which 5% and 95% of the sorted data fall (used for capping in L4).
- ::: , the width of the middle half of the data.
Level 1 — Recognition
Recall Solution L1.1
The z-score answers "how many typical spreads is this point from the mean ?"
- . Since , yes, it is flagged as an outlier.
- The minus sign means : the point sits below the mean (to the left on the chalk number line). A positive would mean above/right. Answer: outlier, and it is a low value.
Recall Solution L1.2
Pick IQR. The IQR uses percentiles () which are rank-based — they only care about the position of sorted values, not their magnitude. So a handful of huge incomes cannot inflate or . The z-score uses and , both of which get dragged upward by that same rich tail, hiding the very outliers you want to catch.
Level 2 — Application
Recall Solution L2.1
What we do: measure the width of the middle half, then push out by that width on each side. Anything beyond is "far from the bulk." Check every point: the smallest is (, fine). The largest is . Since , is an outlier. All others fall inside the fences. Answer: IQR , fences , outlier .
Recall Solution L2.2
- At threshold : , NOT flagged.
- At the looser threshold : , still NOT flagged (only just misses). This is the self-masking problem in action: is visibly extreme, yet by pulling up to and inflating to , it hides under the threshold.
Level 3 — Analysis
Recall Solution L3.1
(a) Z-score: Since : NOT flagged. (b) IQR: Since : flagged. (c) Why the disagreement: the single value is included in the computation of both and , so it inflates its own ruler — balloons to , dividing the distance down to . The IQR is built only from , which sit inside the tight cluster ; the value never touches them, so the ruler stays honest and catches it.
Recall Solution L3.2
First, the tools:
- Euclidean distance measures straight-line distance, treating each feature independently. Here it barely distinguishes A and B — both are sqft above mean.
- Mahalanobis distance inserts , the inverse of the covariance matrix (which stores each feature's spread on its diagonal and the correlation between them off-diagonal). This rotates and rescales space so the ruler runs along the natural correlation ridge.
Verdict: House A should be flagged. It has huge
sqftbut few bedrooms — it breaks the correlation (big houses should have many rooms). Mahalanobis measures distance off the correlation ridge, so A lands far away. House B follows the ridge (big + many rooms), so even though it's far from the mean, it's a "normal-looking" big house → low .
Look at the figure: the yellow ellipse is the "normal" region Mahalanobis draws. B stays inside the tilted ellipse; A pops out sideways.

Level 4 — Synthesis
Recall Solution L4.1
Recall and are the 5th and 95th percentiles — the low and high cut values that leave of the data below and above respectively. Capping rule — pull anything past a percentile back to that percentile, leave the middle untouched: Go value by value:
- (capped up to )
- is in (unchanged)
- (capped down)
- (on the boundary, kept)
- (on the boundary, kept)
- (capped down) Result: . Why rank order survives: capping is a monotone operation — if before, then after. So "who is bigger than whom" never flips; we only compress the extremes inward. The distribution's tails get flattened (less variance) but the ordering — crucial for rank-based models — is preserved.
Recall Solution L4.2
(a) KEEP. The outliers are the signal — removing fraud from a fraud detector deletes the target. This is the domain of 3.3.02-Anomaly-detection, where rarity is the whole point. (b) REMOVE. Age is physically impossible → a data error, not variation. No transform can rescue a corrupted value. (c) TRANSFORM (e.g. log or Winsorize). Medium sample, values are real and meaningful but distort and hence any scaling. A linear model is mean-based and sensitive, so we compress rather than delete — keeping the information while calming the leverage.
Level 5 — Mastery
Recall Solution L5.1
Local Outlier Factor (LOF) compares a point's local density to the density of its neighbors: where is the set of 's nearest neighbors, and (local reachability density) is roughly "how tightly packed is the region around this point" — high lrd = dense, low lrd = sparse.
First, what is and how do you choose it? The number is how many nearest neighbors you look at to define "local." It is a hyperparameter you pick, not something the data hands you:
- Too small (e.g. ): the estimate is jumpy — a single oddly-placed neighbor swings the verdict.
- Too large (e.g. near the cluster size): "local" stops being local; you blur across clusters and lose the very locality LOF exists for.
- Rule of thumb: many practitioners start around , and choose at least as large as the smallest cluster you'd still call a group (so a genuine small cluster isn't mistaken for outliers). Often you scan a range of and check stability.
Now the two points, using normal, outlier:
- Point : its nearest neighbors are units away (in the clusters), but those neighbors have their own neighbors only away. So is far sparser than its neighbors are → ratio is large → → flagged.
- Point : its neighbors are the edge points of both clusters, which are themselves relatively isolated on that side. 's density and its neighbors' densities are comparable → → not flagged. is a legitimate transition point, not an anomaly. The lesson: global methods only know one "normal" band, so a sparse-but-expected gap point looks abnormal. LOF adapts to local density and rescues it.
Read the figure to lock this in. Look at the pink star in the upper right: it stands alone, while the crowd it's nearest to is itself tightly packed — that mismatch is what makes big. Now look at the yellow square in the middle gap: it's isolated too, but so are the cluster-edge neighbors it points to, so the ratio stays near . The whole trick is in that comparison — notice how the arrows contrast "sparser than neighbors" () versus "as sparse as neighbors" ().

Recall Solution L5.2
(1) Detector — IQR (not z-score). The feature is right-skewed, so get dragged by the tail (self-masking, exactly as L2.2 and L3.1 showed). The rank-based IQR fences stay honest. If we later add more features, we'd escalate to Mahalanobis or dedicated 3.3.02-Anomaly-detection to catch correlation-breaking points.
(2) Treatment — TRANSFORM, specifically Winsorization or a log transform. The sample is medium ( rows) and the high earners are real, meaningful values, so we compress rather than delete. Capping keeps rank order (proved monotone in L4.1); a log transform pulls in the tail multiplicatively without discarding rows.
(3) Downstream consequence to check — feature scaling. k-NN is distance-based: every prediction depends on how far points are apart. An untreated outlier stretches the income axis so it dominates every distance, drowning out other features. So after capping we must re-run 2.1.02-Feature-scalingand-normalization so income sits on a scale comparable to the rest. Two more consequences worth flagging: an outlier-distorted variance can wrongly inflate or sink this feature's ranking in 2.2.01-Feature-selection; and while 4.1.03-Regularization partly tames outlier leverage in parametric models, it is not a substitute for treatment in a distance-based model like k-NN.
Recall Self-test checklist (reveal to grade yourself)
Why does a big outlier hide from z-score? ::: It inflates (the denominator), shrinking its own z-score — self-masking. What makes IQR robust? ::: It uses rank-based percentiles , untouched by extreme magnitudes. Why the multiplier in Tukey's fences? ::: Empirical compromise — flags only of clean normal data (few false alarms) while still catching real strays. What is in LOF and how is it chosen? ::: The neighborhood size (a hyperparameter); pick it big enough to be stable and at least as large as the smallest real cluster, often around . What does add in Mahalanobis distance? ::: It rescales/rotates space along correlations, so distance is measured off the natural correlation ridge. When is a far-from-mean point NOT an outlier? ::: When it obeys the correlation pattern (Mahalanobis) or matches its neighbors' local density (LOF). Which treatment preserves rank order? ::: Winsorization (capping) — it's monotone.