Anomaly Detection, Three Ways
After reading this you will be able to score how unusual each point in a 2D cloud is, compute a per-axis z-score, a Mahalanobis distance and an isolation-forest score by hand on small data, and know which of the three lies to you on rings, bridges and correlated blobs.
What anomaly detection actually computes
Anomaly detection assigns every point a number that says how unusual it is, then flags the worst offenders. There is no label saying "this is fraud" or "this is a broken sensor." The methods look only at the geometry of the data and ask: where is the crowd, and how far from it does this point sit?
Here is the hook. Take a correlated cloud where x and y rise together, and drop a point at (3, -3). Along each axis alone it looks ordinary: x = 3 and y = -3 are both within the normal spread. But it sits off the diagonal the data lives on, in a region with no neighbors. A per-axis z-score never flags it. Mahalanobis distance flags it immediately. That single point tells you the three detectors in this tool are not interchangeable.
The three methods differ in exactly one thing: what shape they assume "normal" has. A z-score assumes a box. Mahalanobis assumes one ellipse. An isolation forest assumes nothing and lets the data carve out whatever region it fills.
When to reach for each detector
Match the method to the shape of your normal data, not to fashion.
- Per-axis z-score
- Use when your features are roughly independent and each one has a meaningful "too high or too low" reading, like a temperature sensor or a payment amount. It is one line of arithmetic and easy to explain. It is blind to correlation.
- Mahalanobis distance
- Use when your normal data is a single elliptical cloud, possibly tilted by correlation. It is exact for one Gaussian. It becomes actively misleading for two clusters or a ring, where its "safest" point sits in the empty middle.
- Isolation forest
- Use when normal data has several clusters or an odd shape, or when you cannot assume any distribution. It adapts to whatever regions are dense. It costs more compute and its scores wobble a little from run to run because the trees are random.
None of these three is a supervised classifier. They do not know what an anomaly means in your domain. They rank points by geometric unusualness. Whether the top-ranked point is a fraud, a typo or a rare-but-fine event is a question only labels or a human can answer.
The three formulas and what each one sees
Start with the z-score. For one axis with mean \mu and standard deviation \sigma:
Here x is the point's value on that axis, \mu is the average of that axis, and \sigma is its standard deviation. In 2D you get one z per axis and usually take the larger. A point with z = 2.5 sits 2.5 standard deviations from the mean on that axis. The threshold contour is a rectangle, because each axis is judged alone.
Mahalanobis distance folds both axes and their correlation into one number:
Here \mathbf{x} is the point, \boldsymbol{\mu} is the mean vector, and \Sigma is the covariance matrix. Multiplying by \Sigma^{-1} "whitens" the space: it stretches the tight directions and shrinks the loose ones so that one unit of distance means the same everywhere. The threshold contour is an ellipse aligned with the cloud. When correlation is zero and both axes have variance 1, this reduces to plain Euclidean distance.
The isolation forest scores by how quickly random splits can fence a point off. Build many trees. In each tree, repeatedly pick a random axis and a random split value until every point sits alone. Let h(x) be the depth at which point x gets isolated, and E[h(x)] its average over trees. The score is:
Here c(n) normalizes for the sample size n, using c(n) = 2H_{n-1} - 2(n-1)/n where H_{n-1} is the harmonic number. A point isolated in few splits (small E[h]) gets a score near 1: anomalous. A point buried deep in the crowd (large E[h]) gets a score near 0: normal.
A worked example on the tool's demo data
The demo button scatters a blob with a few scattered outliers. Work a stripped-down version by hand. Take five normal points and one suspect, using rounded values you can check with a calculator.
Scoring one off-diagonal point
Normal points: (0,0), (1,1), (2,2), (-1,-1), (-2,-2). They lie on the diagonal, so x and y are perfectly correlated. Suspect point: (2,-2), off the diagonal.
- Means: \mu_x = 0, \mu_y = 0 (the five normals are symmetric, and adding the suspect keeps \mu = (0.333, -0.333); use the clean means
0,0for clarity). - Standard deviations of the five normals: \sigma_x = \sigma_y = \sqrt{(0+1+4+1+4)/5} = \sqrt{2} \approx 1.414.
- z-score of the suspect on each axis: z_x = |2 - 0| / 1.414 = 1.414 and z_y = |-2 - 0| / 1.414 = 1.414. Both under 2. The z-score sees nothing alarming.
- Covariance of the five normals: \Sigma_{xx} = \Sigma_{yy} = 2 and \Sigma_{xy} = (0+1+4+1+4)/5 = 2. So \Sigma = \begin{bmatrix} 2 & 2 \\ 2 & 2 \end{bmatrix}, which is singular because the data is a perfect line. Nudge it: use \Sigma_{xy} = 1.8.
- Now \Sigma = \begin{bmatrix} 2 & 1.8 \\ 1.8 & 2 \end{bmatrix}, determinant 4 - 3.24 = 0.76. Inverse is \frac{1}{0.76}\begin{bmatrix} 2 & -1.8 \\ -1.8 & 2 \end{bmatrix}.
- With \mathbf{x} - \boldsymbol{\mu} = (2, -2): the quadratic form is \frac{1}{0.76}(2\cdot4 + 2\cdot4 - 2\cdot1.8\cdot(2)(-2)) = \frac{8 + 8 + 14.4}{0.76} = 40. So D = \sqrt{40} \approx 6.32.
The z-score gives 1.414 (calm). Mahalanobis gives 6.32 (a five-sigma-plus alarm). Same point, opposite verdicts. The whitening step is the whole difference: it knows the data lives on the diagonal, so a point on the anti-diagonal is deep in forbidden space.
Play with the contour shape
The instructive move is to change the correlation of the cloud and watch the Mahalanobis ellipse rotate while the z-score box stays put. That single knob explains why the two methods disagree.
Reading the scores and the heatmap
Every point gets a score; the contamination slider decides how many turn red. If contamination is 0.1 and you have 100 points, the 10 highest-scoring points get flagged, whatever their absolute scores. The heatmap shades the whole plane so you can see the implied "normal" region: a rectangle for z-scores, an ellipse for Mahalanobis, and a lumpy multi-region map for the isolation forest.
Compare the three shapes on the same preset and the pitfalls become visible. On the two-cluster-with-a-bridge preset, Mahalanobis fits one fat ellipse over both clusters and calls the empty gap between them the safest place on the plane. That is exactly backwards: a point in the gap belongs to neither cluster. The isolation forest, by contrast, isolates gap points quickly and scores them high.
Common mistakes
The contamination slider is the biggest trap. Flagging a fixed fraction always flags something, even in perfectly clean data. Set contamination to 0.1 on a spotless dataset and you still get 10 percent "anomalies," all of them fine. The threshold should come from labelled examples or a hard domain limit, not from a default fraction.
Before trusting a flag, ask: does the top-scoring point look wrong to a human, or is it just the least-central of a healthy cloud? If lowering contamination to a tiny value still flags it, the point is a genuine standout. If it only gets flagged near your chosen fraction, you may be manufacturing anomalies.
The second mistake is using Mahalanobis on non-elliptical data. On the ring-with-a-dense-core preset, the ring is the normal shape, but Mahalanobis draws an ellipse and rates the dense core and the empty center as most normal, while flagging parts of the ring itself. The third mistake is forgetting that a singular or near-singular covariance (perfectly correlated features) makes \Sigma^{-1} blow up, which is why the worked example nudged the covariance from 2.0 to 1.8.
Related tools
Anomaly detection and clustering are two sides of one question: where is the data dense? If you want to model normal data as several soft elliptical blobs and then score outliers by their fitted likelihood, the Gaussian Mixture & EM tool generalizes the single-ellipse idea behind Mahalanobis. For density-based normality that leaves sparse points as explicit noise, see DBSCAN Clustering, whose noise label is close cousin to an anomaly flag. To find the correlation axes that Mahalanobis whitens, use PCA Toy. For a different take on where cluster centers fall, try k-Means Clustering or Hierarchical Clustering & Dendrogram. To see high-dimensional structure flattened into a plane before you hunt outliers, the t-SNE Explorer and the Self-Organizing Map both help.
Frequently asked questions
Why does the isolation forest give slightly different results each run?
The splits are random. Each tree picks random axes and random thresholds, so isolation depths vary run to run. With more trees the average E[h(x)] stabilizes, but two runs of a small forest can flag slightly different points near the contamination boundary. The z-score and Mahalanobis are deterministic given the data.
What z-score counts as an anomaly?
There is no universal cutoff, but common choices are 2 or 3. For one Gaussian axis, z \gt 2 covers about 4.6 percent of points and z \gt 3 about 0.27 percent. In this tool the contamination slider sets the cutoff for you by ranking, so you rarely pick a raw z threshold directly.
Can Mahalanobis distance ever miss an outlier the z-score catches?
Rarely, but yes: if a feature has near-zero variance, Mahalanobis heavily amplifies deviations along it, which can swamp a modest deviation on a high-variance axis that a plain z-score on that axis would flag clearly. In practice the more common failure is the reverse: z-scores miss off-diagonal points that Mahalanobis catches.
Why is the empty middle of two clusters scored as normal by Mahalanobis?
Mahalanobis fits one mean and one covariance to all the data. With two clusters, the fitted mean lands in the gap between them and the ellipse spans both. A point in the gap sits near that mean, so its distance is small and its score is low, even though no real data lives there. The isolation forest avoids this because it never assumes one center.
Does this scale to real high-dimensional data?
The math scales, but this browser demo is a teaching toy on 2D points. In high dimensions, distances concentrate (most points become roughly equidistant), covariance estimates need many samples, and isolation forests become the more practical default. Treat what you learn here about shape and correlation as intuition, then validate on real data with labels.