Sub topic 1
What Anomaly Detection Is and Why It Is Hard
Prerequisites
This chapter assumes the following:
- Basic Python and NumPy, including arrays, boolean masks and
np.quantile. - A working idea of a feature matrix (rows are samples, columns are features) and of train/test splits.
- Familiarity with decision trees and tree ensembles. You need them from the next chapter on.
- Basic probability, including mean, standard deviation and what a logarithm does.
No Isolation Forest knowledge is needed. This chapter sets up the problem the algorithm solves and explains why the problem resists simple solutions.
What anomaly detection is
Anomaly detection is the task of finding observations that do not conform to the pattern of most of the data. The same task appears under several names: outlier detection, novelty detection, fraud detection and fault detection. Typical uses:
- Flagging a card transaction that looks unlike the cardholder's history.
- Spotting a server whose CPU and memory readings drift away from its peers.
- Finding a sensor reading that signals a failing machine.
- Catching corrupted rows before they reach a model.
Two properties define an anomaly in practice:
- Anomalies are rare. They make up a small fraction of the data, often well under 5%.
- Anomalies are different. Their feature values differ from the bulk of the data, in a way that matters to you.
An anomaly is not automatically an error or a fraud case. It is a point the data says is unusual. Whether it is worth acting on is a domain decision.
Kinds of anomalies
The kind of anomaly you expect determines which method fits.
| Kind | Description | Example |
|---|---|---|
| Point anomaly | A single observation is far from the rest in feature space. | A purchase of 40,000 when typical purchases are under 200. |
| Contextual anomaly | A value is normal in general but abnormal in its context, such as time or location. | 30 °C in a January temperature series. |
| Collective anomaly | Each point looks fine, but a group of points together is unusual. | A flat line of identical sensor readings for ten minutes. |
Isolation Forest, the subject of this tutorial, targets point anomalies in a feature matrix. Contextual and collective anomalies usually need feature engineering first. For example, you can add the hour of day, or compute rolling statistics, so that the context becomes part of each row.
Three learning settings
How you build a detector depends on what labels you have. Mixing these settings up is a common source of mistakes.
- Supervised. You have labels for both normal and anomalous examples. This is ordinary classification with severe class imbalance. It works only when the anomalies you will see resemble the ones you labeled.
- Semi-supervised (novelty detection). You have a training set believed to be clean, and you want to flag new points that differ from it. You fit on normal data only.
- Unsupervised (outlier detection). You have unlabeled data that may already contain anomalies, and you want to find them in that same data. Isolation Forest is normally used this way.
In scikit-learn, the distinction shows up in method names. IsolationForest supports both uses, but whether it is novelty or outlier detection depends on what data you fit on and what data you score. Fitting on contaminated data and scoring the same data is outlier detection. Fitting on clean data and scoring new data is novelty detection.
Why it is hard
The task sounds easy: find the weird points. Several properties of the problem make it difficult in practice.
Anomalies are rare and labels are scarce
With 0.1% positives, a classifier that always predicts "normal" has 99.9% accuracy and finds nothing. Even when you have labels, they are usually incomplete. Many anomalies are never noticed, so some points labeled "normal" are in fact anomalous. Accuracy is therefore a misleading metric here. Later chapters use ROC AUC and average precision instead.
"Anomalous" is not a precise definition
There is no universal rule for how different is different enough. A point can be unusual in one feature, or only in a combination of features, such as a normal height and a normal weight that are implausible together. Different algorithms encode different ideas of abnormal: distance from the center, low local density, or ease of separation. They can disagree on the same data.
Anomalies do not look alike
Normal data tends to form a few coherent clusters. Anomalies can be anywhere else, and each can be unusual in its own way. You cannot learn "what an anomaly looks like" from a few examples, because the next one may look different. That is why detectors usually model normal behavior and treat deviation as the signal.
Anomalies can hide themselves
Anomalies in the training data can corrupt the model used to find them. Two named failure modes:
- Masking. Many anomalies together make each other look normal. They inflate estimates such as the mean and standard deviation, or form a small dense cluster that looks like a legitimate group.
- Swamping. Normal points that sit near anomalies get wrongly flagged, because the anomalies have distorted the model's picture of the normal region.
The next code example shows masking with the simplest detector, a z-score rule.
import numpy as np
rng = np.random.RandomState(0)
normal = rng.normal(loc=0.0, scale=1.0, size=200)
outliers = np.array([8.0, 9.0, 10.0, 12.0, 15.0, 20.0, 25.0, 30.0])
x = np.concatenate([normal, outliers])
# Classic z-score: uses the mean and std of data that includes the outliers
z = (x - x.mean()) / x.std()
flagged_z = np.abs(z) > 3
# Robust version: median and MAD are barely moved by the outliers
median = np.median(x)
mad = np.median(np.abs(x - median))
robust_z = (x - median) / (1.4826 * mad)
flagged_robust = np.abs(robust_z) > 3
print("true outliers:", len(outliers))
print("z-score flagged among outliers:", flagged_z[-len(outliers):].sum())
print("robust flagged among outliers:", flagged_robust[-len(outliers):].sum())
print("robust false alarms among normals:", flagged_robust[:200].sum())The outliers raise the standard deviation to about 3.6, so the smaller ones (8, 9 and 10) have a z-score under 3 and slip through. That is masking. The robust version uses statistics that outliers barely affect, and it catches all eight. It may also flag a few normal points near the edge of the bulk, since a 3-MAD cutoff is tighter than a 3-standard-deviation cutoff on clean Gaussian data.
High dimensions blur the picture
As the number of features grows, distances between points concentrate. The nearest and farthest neighbors end up at similar distances, so distance-based detectors lose contrast. An anomaly may also be unusual in only 2 of 50 features, and the 48 irrelevant features add noise that hides it. Later chapters return to this when discussing max_features and limitations.
Normal changes over time
Customer behavior, sensor calibration and traffic patterns drift. A detector trained last quarter can flag the new normal as anomalous, or accept a new anomaly as routine. Without retraining and monitoring, detectors decay silently.
Thresholds and cost are business decisions
Most detectors produce a continuous score, not a verdict. Converting it into "anomaly or not" requires a threshold. A missed fraud and a false alarm cost very different amounts, and the right trade-off depends on who reviews the alerts and how many they can handle. No algorithm can pick this for you.
Common errors
- Reporting accuracy. On imbalanced data it hides failure. Use ranking metrics or precision and recall at a chosen alert volume.
- Fitting scalers or models on test data. Fit preprocessing on training data only, as with any model, or evaluation will look better than reality.
- Assuming the contamination rate. Setting an expected anomaly fraction without evidence forces the detector to flag exactly that fraction, whether or not real anomalies exist.
- Treating flagged points as ground truth. A flag means "unusual". Review a sample before acting automatically.
- Using one method for every anomaly type. A point-anomaly detector will not find a collective anomaly unless you engineer features that expose it.
- Ignoring feature scale and meaning. Some detectors are sensitive to units, and irrelevant features dilute the signal.
How this leads to Isolation Forest
Most classical detectors first build a profile of normal data (a distribution, a distance, a density) and then measure how far each point lies from that profile. This costs computation, and the profile can be distorted by the anomalies themselves, as the masking example shows.
Isolation Forest takes a different route. It does not model normal behavior. It asks how easy it is to separate each point from the others using random cuts. Because anomalies are few and different, they are separated quickly. The next chapter develops this idea.
Exercise
A fraud dataset has 10,000 transactions and 20 known frauds (0.2%). A model predicts "not fraud" for every transaction. Report its accuracy and explain why accuracy is a poor metric here. Name one metric better suited to this problem.
Show answer
Accuracy is 9,980 / 10,000 = 99.8%, even though the model finds no fraud. Accuracy is dominated by the majority class, so it cannot show a failure to detect the rare class. Average precision (area under the precision-recall curve) or ROC AUC is better, because they evaluate how well the scores rank the 20 frauds above the normal transactions.
Exercise
In the masking example, why does the z-score rule miss the outliers at 8, 9 and 10 while the median/MAD rule catches them? What does this suggest about building a detector from data that already contains anomalies?
Show answer
The outliers themselves raise the mean and, especially, the standard deviation (to about 3.6), so a value of 8 to 10 lands under 3 standard deviations from the mean. The median and MAD barely change when a few extreme values are added, so the robust score still shows these points as far from the bulk. The lesson is that statistics estimated from contaminated data can be distorted by the anomalies you want to find. Prefer robust methods, or methods like Isolation Forest that do not depend on a fitted profile of normal data.