2.1.3 · D2Data Preprocessing & Feature Engineering

Visual walkthrough — Outlier detection and treatment

2,952 words13 min readBack to topic

We assume you know nothing beyond: a point is a pair of numbers, and you can measure a straight-line gap with a ruler. Everything else is earned below.


Step 1 — A point, a centre, and the naive ruler

WHAT. We have data with two features. Call them (say, house size in sqft) and (say, number of bedrooms). Each house is a dot on a flat picture: its horizontal position is , its vertical position is . The pile of dots has a centre — the average house — which we write (Greek letter "mu", just means "the middle point").

WHY. To ask "is this house weird?" we first need a reference. The natural reference is the centre of the crowd. Weirdness = far from centre. So we need a way to measure "far".

PICTURE. Below, the orange dot is one house , the navy dot is the centre . The straight magenta ruler between them is the everyday distance everyone learns first.

Figure — Outlier detection and treatment

We chose Pythagoras (the square root of a sum of squares) and not, say, just adding the gaps, because a straight ruler laid between two dots physically obeys Pythagoras. That is exactly what "straight-line distance" means.


Step 2 — Why the plain ruler lies

WHAT. We now spread the crowd out unevenly. Suppose sqft varies over thousands while bedrooms varies over a handful. The cloud of dots is a long thin stretched blob, wide along and short along .

WHY. The plain ruler counts "3000 sqft away" and "3 bedrooms away" with the same importance. But 3000 sqft is a tiny step for that feature (it ranges over huge numbers), while 3 bedrooms is a huge step for its feature (it barely ranges at all). Equal ruler-length does not mean equal weirdness.

PICTURE. Two points sit on the same magenta circle — same Euclidean distance from centre. Yet point (violet) lies inside the blob and point (orange) pokes out of it. Equal ruler, wildly unequal weirdness. The ruler is fooled.

Figure — Outlier detection and treatment

Step 3 — First fix: divide each direction by its spread

WHAT. For each feature separately, measure its typical spread — the standard deviation ("sigma"), how far a typical point sits from the centre along that one axis. Then rescale: instead of raw gaps, use gaps counted in units of that feature's own spread.

WHY. If bedrooms typically wander by but sqft wanders by , then "3 bedrooms off" is spreads — genuinely far — while "3000 sqft off" is spreads — the same weirdness. Dividing by converts every axis to a common, unit-free currency: "how many typical spreads away." (This is exactly the z-score idea from the parent note, now applied per axis.)

PICTURE. We squash the wide blob and stretch the short one until the cloud becomes a round ball. Now equal ruler-length genuinely means equal weirdness — for the moment.

Figure — Outlier detection and treatment

Step 4 — The leftover problem: tilt (correlation)

WHAT. Real blobs are not just wide-or-tall; they are usually tilted. Big houses tend to have more bedrooms, so the cloud leans diagonally — as sqft goes up, bedrooms go up too. This leaning is called correlation.

WHY. Step 3 only stretched along the horizontal and vertical axes. It cannot un-tilt a diagonal cloud. A point that lies along the tilt direction (big house, many rooms) is normal even if it's far. A point that lies across the tilt (big house, few rooms) breaks the pattern and is weird — even at the same rescaled distance. Standardizing per-axis is blind to this.

PICTURE. Two points on the same standardized circle: violet rides along the diagonal grain of the blob (normal); orange cuts against the grain (anomalous). Same rescaled distance, different truth. We still need to account for the tilt.

Figure — Outlier detection and treatment

Step 5 — The object that stores width AND tilt: the covariance matrix

WHAT. Bundle everything the blob's shape knows into one small table of four numbers, the covariance matrix ("capital sigma"):

WHY. We need a single object that encodes both how wide the blob is in each direction and how tilted it is. The two diagonal entries store the widths (variance = spread squared). The two off-diagonal entries store the tilt: means no lean (upright blob), means the "up-right" lean of our houses, means a "down-right" lean. One table, the whole shape.

PICTURE. The blob with its two natural axes drawn on it: a long axis (the grain, where the blob is widest) and a short axis (across the grain). is precisely the recipe for these two axes and their lengths.


Step 6 — Undoing the shape: the whitening transform

WHAT. We want a mathematical operation that grabs the tilted, stretched blob and squeezes it back into a perfect round ball of radius 1 — un-tilt and un-stretch in one move. That operation is applying the inverse of , written .

WHY the inverse, and not itself? describes how a round ball got stretched into the data blob. To reverse a stretch you apply its inverse — exactly like undoing "multiply by 5" with "multiply by ." Where the blob is wide (large variance), shrinks that direction, so travelling there is cheap (counts little toward distance). Where the blob is thin, expands it, so travelling across the grain is expensive (counts a lot). This is the un-fooling we wanted in Steps 2 and 4, both handled at once.

PICTURE. Left: the raw tilted blob with two mismatched points. Right: after applying the whitening transform the blob is a clean unit circle, and now the anomalous point clearly sits outside while the normal one sits inside. Straight ruler on the right = honest weirdness.


Step 7 — Assembling the Mahalanobis distance

WHAT. Now measure the plain squared ruler in the whitened world. Starting from the raw gap vector , whitening and then measuring length gives:

WHY this exact shape. Read it right-to-left as a story:

  • — the raw arrow from centre to point, still in the distorted world.
  • — apply the "undo-the-blob" button: the arrow is now in the fair round world.
  • — the leading row-vector multiplies the whitened arrow to form Pythagoras' sum of squares in that fair world (this is the matrix way of writing "square each component and add").
  • the outer — turn the squared length back into an ordinary length, so the units make sense.

PICTURE. The final annotated formula, each chunk coloured and tagged with the job it performs: raw arrow → whiten → measure → square-root.


Step 8 — Every special case, checked

WHAT & WHY. A ruler you trust must behave sensibly at the extremes. We walk each one.

Case A — no correlation, equal spread (, ). Then and , so Mahalanobis collapses to the plain ruler divided by spread — exactly the z-score. Sanity: passed.

Case B — no correlation, unequal spread (, ). Then and which is exactly the standardized distance of Step 3. The tilt machinery correctly does nothing when there is no tilt. Sanity: passed.

Case C — the point IS the centre (). Then , so : the centre is zero-weird. As you slide toward , shrinks smoothly to 0. No blow-up.

Case D — a perfectly redundant feature (degenerate blob). If two features are identical (perfect correlation), the blob collapses to a line, the determinant becomes , so is not positive-definite and does not exist — is undefined. WHY it must fail: you cannot un-stretch a blob that has zero thickness in some direction; the "undo" button has nothing finite to undo. Fix in practice: drop or merge the redundant feature (see 2.2.01-Feature-selection) before computing .

PICTURE. Four mini-panels, one per case: (A) round ball, (B) axis-stretched ball, (C) point at centre with , (D) collapsed line with a red "no inverse" cross.


The one-picture summary

Everything above compressed: raw tilted blob (plain ruler fooled) → apply to whiten → round ball where the honest ruler flags the true anomaly. The threshold circle uses the cutoff mentioned in the parent so you can say statistically how weird is too weird.

Recall Feynman retelling — say it back in plain words

Imagine a crowd of dots that looks like a tilted, stretched pancake. You want to know if a new dot is a stranger. A plain ruler is unfair: it counts a long-but-normal direction the same as a short-but-strange direction. So you invent a magic squishing move — the whitening transform, written — that grabs the pancake and rounds it into a perfect ball. All the built-in tilt (covariance ) and stretch (variances ) of the data got baked into one little table , so its inverse knows exactly how to un-bake it. In that fair round world you finally lay down your ordinary ruler, and its length is the Mahalanobis distance: cheap to travel along the crowd's grain, expensive to travel across it. Points beyond the threshold circle are the true outliers. When there's no tilt and equal spread, the magic move does nothing and you're back to a plain z-score — which is exactly how you know the idea is trustworthy.

Recall Quick self-test

Why apply (the inverse) rather than itself? ::: describes how a round ball got stretched into the data blob; to undo that stretch we apply its inverse — the transform for which — cheapening the wide directions and expensive-ing the thin ones. What does in mean, and what does become? ::: No tilt/correlation; reduces to the per-axis standardized (z-score) distance. Why does break when two features are identical? ::: The blob collapses to a line, the determinant hits zero so is not positive-definite, does not exist, and there is nothing finite to "un-stretch."

Related vault notes: this ruler feeds anomaly systems in 3.3.02-Anomaly-detection; the per-axis rescaling echoes 2.1.02-Feature-scalingand-normalization; robustness of statistics connects to 2.1.01-Missing-data-handling and shrinking large effects to 4.1.03-Regularization. Hinglish version: 2.1.03 Outlier detection and treatment (Hinglish).