Sub topic 1
What Anomaly Detection Is and Why It Is Hard
Prerequisites
This chapter assumes you know basic Python and NumPy, and that you have seen decision trees and ensembles of trees. You should understand feature matrices, meaning a table with one row per example and one column per feature. You should also know the difference between training and test data. Later chapters also use basic probability and logarithms.
What anomaly detection is
Anomaly detection is the task of finding observations that differ from most of the data. These observations are also called outliers. Typical cases are fraudulent card payments, a failing sensor in a factory, or an unusual burst of network traffic.
Two properties define an anomaly in this tutorial:
- Anomalies are rare. They make up a small share of the data.
- Anomalies are different. Their feature values lie far from where most points sit.
The task is usually unsupervised. That means you have a feature matrix but no labels saying which rows are anomalies. The detector has to learn what normal looks like from the data and flag whatever does not fit.
Three common setups
The setup depends on what data you have for training.
| Setup | Training data | Typical use |
|---|---|---|
| Supervised | Rows labeled normal or anomalous | Fraud, when confirmed cases exist |
| Semi-supervised (novelty detection) | Only clean, normal rows | Monitoring a machine that is known to be healthy |
| Unsupervised (outlier detection) | Unlabeled rows that may contain anomalies | Exploring data and cleaning it |
Isolation Forest works in the unsupervised setting. It can also be used for novelty detection by fitting it on clean data and scoring new rows.
Why it is hard
Anomaly detection looks like classification, but several problems make it harder.
- Labels are scarce or missing. Anomalies are rare, so few labeled examples exist. Labeling them often needs an expert.
- Class imbalance. If 1 row in 1,000 is anomalous, a model that always says "normal" is 99.9% accurate and useless. Accuracy is the wrong metric here. Later chapters use ROC AUC and average precision instead.
- "Normal" is not one thing. Normal data may form several clusters, change over time, or depend on context. A temperature of 30 °C is normal in July and strange in January.
- Anomalies are not all alike. New kinds of anomaly can appear that never showed up before, so a detector cannot just memorize known bad patterns.
- There is no single definition of "far". Distance depends on feature scales, on dimension, and on how dense the surrounding data is.
- Contamination. When the training data itself contains anomalies, they can distort what the model thinks is normal.
The usual approach and its cost
Many classic detectors first build a profile of normal data. They then mark points that deviate from the profile. Examples include distance to the nearest neighbors, density estimates, and fitted statistical distributions.
This approach has two costs. Distance and density methods compare many pairs of points, so they get slow on large data sets. And the methods are tuned to describe normal points well, so finding anomalies is a side effect rather than the goal.
The diagram below shows the general flow of a profile-based detector.
A small example
The code below makes a cluster of normal points and a few distant ones. It then applies a simple z-score rule, which flags points more than 3 standard deviations from the mean.
import numpy as np
rng = np.random.RandomState(1)
normal = rng.normal(loc=50.0, scale=5.0, size=200)
outliers = np.array([80.0, 15.0, 95.0])
x = np.concatenate([normal, outliers])
z = (x - x.mean()) / x.std()
flagged = np.abs(z) > 3
print("Rows flagged:", flagged.sum())
print("Flagged values:", np.round(x[flagged], 1))This rule works for one feature with one cluster. It fails when the data has several clusters or many features, and extreme points also inflate the mean and standard deviation, which weakens the rule. These weaknesses motivate the next chapter, which asks a different question: instead of describing normal data, how easily can each point be separated from the rest?
Exercise
A data set has 10,000 transactions and 20 are fraudulent. A model labels every transaction as normal. What is its accuracy, and why does that make accuracy a poor metric here?
Show answer
Accuracy is 9,980 / 10,000 = 99.8%. The model finds none of the fraud, yet the score looks excellent, because the rare class barely affects accuracy. Metrics such as ROC AUC or average precision measure how well anomalies are ranked above normal points.