2.5.13 · D4Unsupervised Learning

Exercises — Anomaly detection methods

3,659 words17 min readBack to topic

A quick symbol reminder so line one is followable:

  • = the mean vector, the "center of normal" (average of all training points).
  • = the covariance matrix, the "shape/spread" of normal data.
  • = probability density at point : big where data piles up, tiny out in empty space.
  • = Mahalanobis distance squared — distance measured in units of the data's own spread.
  • = path length in one isolation tree (how many yes/no splits to isolate a point); = its average over all the trees in the forest.
  • = the density threshold; below it, we shout "anomaly!".

Level 1 — Recognition

L1.1

A dataset has features. You compute for a new point and get . Your threshold is . Is normal or an anomaly?

Recall Solution

The rule is: flag as anomaly only if (strict — equality would count as normal). Here , and . Since , we have . Answer: NORMAL. A larger density means the point sits where data is common.

L1.2

Two isolation-forest anomaly scores come back: and . Using the usual cutoff , which point is the anomaly, and which one was easier to isolate (shorter path)?

Recall Solution

First, what is ? Each point is dropped down every tree in the forest and we record its path length in each tree separately — say tree-lengths Because random splits make any single tree noisy, we average those raw path lengths across all trees to get ; that averaging is exactly why we write the bar. A stable small (short in tree after tree) is the fingerprint of an anomaly. Now the score direction. From : when is small, the ratio is close to , the exponent is close to , so . Hence short average path ⇒ score near 1.

  • anomaly, and higher score ⇒ shorter ⇒ easier to isolate.
  • → normal. Answer: A is the anomaly and was easier to isolate.

L1.3

For a One-Class SVM, a new point gives decision value . Normal or anomaly?

Recall Solution

The rule: ⇒ the point is on the origin side, outside the learned normal region ⇒ anomaly. (Equality means the point sits on the boundary and is treated as normal by our strict convention.) Here . Answer: ANOMALY.


Level 2 — Application

L2.1

1-D Gaussian. Normal data has , variance . Compute the Mahalanobis distance squared for the point .

Recall Solution

In 1-D the Mahalanobis distance squared is (the matrix becomes ). Answer: (equivalently a Mahalanobis distance of , i.e. "3 standard deviations out").

L2.2

Same Gaussian (). Compute the density at .

Recall Solution

Normalizer: . Exponent: , and . Answer: .

L2.3

2-D. Given and (diagonal — features independent). Compute the Mahalanobis distance squared of .

Recall Solution

For a diagonal covariance, , and the quadratic form simplifies to a sum: Answer: . Notice each feature is judged in its own spread — the deviation of 4 is only "2 units" of its std, the deviation of 3 is "1 unit" of its std.

L2.4

Isolation Forest. A point has average path length over the trees, and the dataset has points. The exact normalizer is Compute , then the anomaly score .

Recall Solution

How to get without adding 255 fractions. The harmonic number obeys a well-known, extremely accurate approximation The part is the leading behaviour; the term is a small correction, and the error after it is only about — for that error is under , i.e. negligible for our 4-digit answer. So a student can compute on any calculator, no summing required: which rounds to the true within the accuracy we need. Now : This is where the comes from — the harmonic term minus the correction , not the crude shortcut. Now the score. Exponent: . Answer: and . Since , this point would be flagged.


Level 3 — Analysis

L3.1

Full (non-diagonal) covariance , . Compute the Mahalanobis distance squared of . (This mirrors the parent's server example — verify it.)

Recall Solution

Step 1 — center: . Step 2 — determinant: . Step 3 — inverse: . Step 4 — apply. First : Then dot with : Answer: . A Mahalanobis distance of — enormously far, hence the near-zero density in the parent note.

Read the figure below carefully — it is the geometry of the algebra you just did.

  • The two axes are the raw features: horizontal = CPU usage in %, vertical = memory in %. The scales are the everyday units of the data (0–100%), not rescaled — the rescaling is what the ellipses encode.
  • The black dot is , the center of normal.
  • Each coloured ellipse is a contour of constant Mahalanobis distance (green = distance 1, blue = 2, gray = 3). They are tilted and elongated because the off-diagonal in correlates and : normal points lean up-and-to-the-right. Walking from to the green ellipse costs exactly "1 unit" of Mahalanobis distance in every direction — even though that is a different raw distance along the long axis than the short axis. That is the visual meaning of "distance measured in units of the data's own spread."
  • The orange arrow is the vector you computed in Step 1. Follow it: the red (the server point ) lands far outside even the gray distance-3 ellipse. Our algebra said its Mahalanobis distance is — roughly ten ellipses out. The picture and the number tell the same story.

L3.2

Consider two ways to leave the mean by the same raw (Euclidean) step length: one move along the correlation direction, one move across it. Show numerically that the across-correlation move is more anomalous per unit of raw distance — i.e. has a larger ratio (Mahalanobis distance squared) / (Euclidean distance squared).

Recall Solution

The off-diagonal means CPU () and memory () tend to rise together, so "normal" lies along a tilted ellipse leaning up-and-to-the-right. To make the comparison fair, we normalize each move by its squared Euclidean displacement , which is what "per unit of raw distance" means. Move A — along correlation: (equal rise in both, the natural direction).

  • Euclidean squared: .
  • Mahalanobis: ; form .
  • Ratio . Move B — across correlation: (CPU up, memory down — breaks the pattern), same raw length.
  • Euclidean squared: (identical raw distance ✓).
  • Mahalanobis: ; form .
  • Ratio . Answer: for the same raw step (both length ), the across-correlation move B has almost double the Mahalanobis cost ( vs ), so its anomaly-per-unit-raw-distance ratio ( vs ) is larger. Breaking the correlation is disproportionately suspicious.

L3.3

Isolation Forest with . Using the exact , compute , then the scores for point P () and point Q (), and decide which is anomalous (cutoff ).

Recall Solution

Using the same harmonic approximation as L2.4, (true value — the correction terms make it dead-on). Now the scores: . . Answers: (>0.6 ⇒ anomaly), (just >0.6 ⇒ anomaly, barely). Key correction: the parent's box says "", which would give not the stated there (that number is simply wrong; ). And even is only the crude asymptotic; the exact value is . Always use the exact harmonic formula for real scoring.


Level 4 — Synthesis

L4.1

A stream of transactions is 99.5% normal, 0.5% fraud. You must pick between (a) Gaussian density estimation and (b) Isolation Forest. Feature space is 40-dimensional, features are heavily correlated and non-Gaussian (multi-modal clusters of legitimate behaviour). Which do you choose and why? Give the failure mode of the loser.

Recall Solution

Choose (b) Isolation Forest.

  • Gaussian density estimation assumes normal data is a single unimodal blob described by one and one . With multi-modal legit behaviour (e.g. two clusters: online micro-payments and in-store large payments), the single Gaussian smears a fat blob covering the empty valley between clusters — assigning high to the sparse middle. A fraud point landing there escapes detection. That is the Gaussian's failure mode: false negatives in inter-cluster gaps.
  • Isolation Forest makes no distributional assumption; it just measures how quickly random splits isolate a point, so multiple clusters are fine and correlated non-Gaussian features are handled.
  • Caveat: if you insisted on Gaussian, you'd upgrade to a Mixture of Gaussians (one blob per cluster) — but plain single-Gaussian loses here.

L4.2

You have a 1-D feature that is right-skewed: most values near 0, a long tail to +∞ (e.g. transaction amount). Gaussian anomaly detection over-flags large-but-legitimate values. Propose a fix consistent with the Gaussian method, and justify.

Recall Solution

Fix: transform the feature to be more Gaussian before fitting — e.g. use (a log or Box-Cox transform). Why it works: the Gaussian density decays symmetrically around . A skewed feature has a fat right tail of legit values; the symmetric bell can't model that, so it treats big legit values as far-from- anomalies. Log-compressing the tail pulls large values inward, making the transformed distribution roughly bell-shaped, so and describe it faithfully. The decision rule is then meaningful. Sanity: maps (spread 999) to (spread 3) — the tail is tamed while ordering is preserved.

L4.3

Combine methods: You run BOTH a Gaussian detector () and an Isolation Forest () and want to only alert when BOTH agree, to cut false alarms. A point has , , and . Does the combined "AND" rule fire?

Recall Solution

Evaluate each detector separately, then combine.

  • Gaussian says anomaly? Compare against . Since , we have ✓ — Gaussian fires (calls it anomaly).
  • Isolation Forest says anomaly? Rule is . Here , and , so the condition is false — Isolation Forest does not fire (calls it normal).
  • Combine with AND. The "AND" rule alerts only when both detectors say anomaly. Truth table: (True AND False) False. Answer: the combined rule does NOT fire — no alert. Interpretation: the "AND" strategy trades recall for precision — you get far fewer false alarms (both must agree), but this borderline point, which the density detector flagged, slips through because the forest disagreed. If missing frauds is costlier than false alarms, prefer an "OR" rule (fire if either agrees) instead.

Level 5 — Mastery

L5.1

Derive the equivalent Mahalanobis threshold. The parent claims: is equivalent to Mahalanobis distance with . Derive this. Then for , , , compute and state whether the server point (Mahalanobis distance ) exceeds it.

Recall Solution

Derivation. Start from with : Multiply both sides by the positive normalizer (positive ⇒ direction of unchanged): Take (increasing, preserves the inequality): Multiply by (negative ⇒ flip the inequality): So with . ∎

Numeric (, , ). Here and . Inside the log: . . Then , so Comparison. The server point has Mahalanobis distance . Since , the point exceeds the threshold ⇒ ANOMALY. This is fully consistent with the parent's : the two views (density vs distance) agree. ✓

L5.2

Design a threshold from a target false-positive rate (1-D). You want at most 1% of normal points flagged. Normal is . Using the fact that in 1-D the Mahalanobis distance equals for a standard normal , and that , find the Mahalanobis-distance cutoff. Then, for , give the two raw values at the boundary.

Recall Solution

In 1-D, is standard normal, and Mahalanobis distance . We want . From the standard-normal table, , so the cutoff is . Raw boundary values: . Answer: cutoff Mahalanobis distance ; boundaries at and . Points with or are flagged, giving false-positive rate on genuinely normal data.

L5.3

Prove the monotonicity that makes Isolation Forest scores interpretable. Show that is a strictly decreasing function of the average path length (so shorter path ⇒ higher score ⇒ more anomalous), and state the limits as and .

Recall Solution

Write with fixed. Then . Differentiate w.r.t. : because , , and the exponential is always positive. A negative derivative everywhere ⇒ strictly decreasing. So larger (harder to isolate, normal) gives smaller ; smaller (easy to isolate, anomaly) gives larger . ∎ Limits: as , (maximal anomaly). As , (maximally normal). Thus , and the special value gives — the "as expected for average data" reference point.

L5.4

Boundary case for One-Class SVM. A test point lands exactly on the learned boundary, so . (i) Under our page convention, normal or anomaly? (ii) What is special about the training points whose , and what happens to the of the interior (deeply-normal) training points? (iii) Why is a point sitting exactly at fragile in practice?

Recall Solution

(i) Classification. Our strict convention flags anomaly only if . Here is not , so the point is treated as normal — it sits on the boundary, the very edge of the accepted region. (ii) What the mean. Solving the dual gives one multiplier per training point, and the decision function is built only from points with — these are the support vectors, the points lying on or outside the boundary that actually pin it down. Deeply-interior "obviously normal" points have : they satisfy the margin constraint with room to spare, contribute nothing to the sum , and could be deleted without changing the boundary at all. So a test point at is, by construction, right at the level set carved out by the support vectors. (Sanity check on the role from the parent: the fraction of points that end up as support vectors — those with — is bounded below by , and upper-bounds the training-outlier fraction.) (iii) Why fragile. is a measure-zero knife-edge. A microscopic change in , in the kernel width , or in the solved tips to a small or , flipping the label. In deployment you therefore never trust the exact boundary: you add a small margin band