What Is an Anomaly?
Picture Maya's debit card: dozens of small $20 charges at the same two coffee shops, then one Tuesday a $2,400 charge from an electronics store 300 miles from home. Your eye jumps to that last one before any model runs. Turning that "does not fit" feeling into a number is the whole job of anomaly detection, and it is what this course teaches.
One of the dots in the picture below behaves the same way. It is not like the others, not because someone labelled it, but because it sits alone in a sparse pocket while the rest crowd together.
Before we can catch anomalies with isolation forests, density scores or autoencoders, we need to pin down what an anomaly actually is, and why it is so easy to fool yourself into thinking you have caught them.
By the end of this lesson you will be able to:
- Say what makes a data point an anomaly (and why unusual is not the same as bad)
- Score "unusual" two ways, by distance and by density, and see why distance alone misses some outliers
- Tell global, local and contextual outliers apart
- Explain the base-rate trap: why a 99%-accurate detector of rare events can still be almost useless, and what to measure instead
Prerequisites: you can run R and read base R (vectors, data.frame, table, mean, sd). No prior anomaly-detection knowledge is assumed.
An anomaly is a point that breaks the pattern
Back to Maya's card. Her everyday charges tell a steady story: most days she spends $3 to $60 at cafes and the grocery store a few miles from home. The $2,400 charge from the cover breaks that story, and you did not need a model to feel it. That feeling has a definition.
An anomaly (or outlier) is a data point that does not fit the pattern of the rest of the data. Formally, you build a model of what "normal" looks like, then an anomaly is any point that model assigns a low probability, or a high "distance from normal" score. Everything in this course is a different way to build that model of normal.
So the question becomes concrete: how do we measure "does not fit the pattern"? There are two classic answers, and the difference between them matters.
Distance: how far from the middle?
The simplest measure of "unusual" is distance from the center. For a single number like a charge amount, the z-score tells you how many standard deviations a value sits from the mean:
\( z = \dfrac{x - \mu}{\sigma} \)
where \(x\) is one charge, \(\mu\) is the mean of Maya's charges, and \(\sigma\) is their standard deviation (the typical spread). A common rule of thumb flags anything with \(|z| > 3\), meaning more than three standard deviations from the middle.
Let us build Maya's card as a small labelled dataset and try it. Each lesson runs in a fresh R session, so we create the data right here (run this once):
Now score every charge by its z, and look at the most extreme:
The $2,400 charge screams (z = 7.2). But watch what a strict global cutoff actually catches:
Only the $2,400 charge clears \(|z| > 3\). The $950 and $380 charges are odd for Maya, yet a single global threshold lets them straight through.
Density: how alone is the point?
A global distance cutoff asks "how far from the overall center?" Density asks a smarter question: "how crowded is this point compared to its own neighbours?" A point deep inside a cluster is as crowded as everyone around it. A point in a sparse pocket, whose few neighbours are themselves packed tight, is far lonelier than its surroundings, even if it is not the farthest from the center.
Slide k below (the number of neighbours each point looks at) and read the Local Outlier Factor off each dot's colour. The highlighted point never has the largest distance from the middle, yet it lights up, because it is locally sparse. That is exactly the outlier a global cutoff misses.
This is why "distance from the middle" and "density in the neighbourhood" are two genuinely different lenses. Maya's $380 charge is unremarkable in size, but it is sparse among her dozens of $20 coffees, so density flags it while distance shrugs.
Global, local and contextual outliers
Those two lenses map onto the three kinds of outlier you will meet again and again. Grounding each on Maya's card:
| Kind | What makes it odd | On Maya's card |
|---|---|---|
| Global | far from every normal point | a $2,400 laptop charge, 300 miles from home |
| Local | ordinary overall, but sparse for its own neighbourhood | a $380 charge sitting among dozens of $20 coffees |
| Contextual | normal in one setting, odd in another | $300 is routine in December, but odd in mid-July |
The takeaway: "anomaly" is not one thing. Which method you reach for depends on which kind you expect.
What makes an outlier local?
A point can be an anomaly even when it is not the farthest from the center of the data. What makes it a local outlier?
The base-rate trap
Here is the trap that catches almost everyone. Zoom out from Maya's card to her whole bank. Anomalies are, by definition, rare: suppose 0.5% of the bank's transactions are truly fraud. Screen 10,000 of them:
Read that second number again. A lazy model that flags nothing is already 99.49% accurate, because almost nothing is fraud. So "99% accurate" can mean "did literally no work." Now run a genuinely useful detector, one that catches 90% of fraud but false-alarms on 5% of clean charges:
The detector caught 47 of 51 frauds (great), but it also raised 489 false alarms. Score it three ways, where \(TP\) is true positives (fraud caught), \(FP\) false positives (false alarms), \(FN\) false negatives (fraud missed), and \(TN\) true negatives:
\( \text{accuracy} = \dfrac{TP+TN}{TP+TN+FP+FN}, \quad \text{precision} = \dfrac{TP}{TP+FP}, \quad \text{recall} = \dfrac{TP}{TP+FN} \)
The reason is Bayes' rule. The chance a flagged charge is really fraud is
\( P(\text{fraud} \mid \text{flag}) = \dfrac{P(\text{flag} \mid \text{fraud})\,P(\text{fraud})}{P(\text{flag})} \)
and when the base rate \(P(\text{fraud})\) is tiny, the denominator is swamped by false alarms from the huge clean majority. No amount of recall rescues precision if the base rate is low enough.
Precision and recall trade off
Precision and recall are not fixed; they slide against each other as you move the threshold, the score above which you raise an alert. Lower the threshold to catch more fraud (recall up) and you also flag more clean charges (precision down). There is no free lunch, only a choice.
Drag the threshold below. Watch the confusion matrix re-count, the precision and recall numbers move, and the operating point slide along the ROC curve, which shows every threshold at once. Accuracy would collapse this whole picture into one misleading number.
Where you set the dial depends on the cost of a miss versus the cost of a false alarm. Blocking a real customer is expensive; so is letting fraud through. That trade-off is a business decision the single "accuracy" number hides completely.
"99% accurate, so it is great?"
A vendor demos a fraud detector: 99% accurate on 10,000 transactions where 0.5% are fraud. Your manager is thrilled. Why might it still be nearly useless?
Measure precision yourself
Precision answers the question that matters to an analyst buried in alerts: of the transactions we flagged, what fraction were actually fraud? Here is one week of alerts, each later confirmed by a human. Fill in the blank so precision is the share of alerts that were truly fraud.
Show answer
confirmed <- c(1, 0, 0, 1, 0, 0, 0, 1, 0, 0)
precision <- sum(confirmed) / length(confirmed)
precision
#> [1] 0.3References
A few authoritative places to take this further:
- Chandola, Banerjee and Kumar (2009), Anomaly Detection: A Survey, ACM Computing Surveys - the map of the whole field: definitions, outlier types, and method families.
- Breunig, Kriegel, Ng and Sander (2000), LOF: Identifying Density-Based Local Outliers, SIGMOD - the paper behind the density lens you used, and the idea of a local outlier.
- Liu, Ting and Zhou (2008), Isolation Forest, IEEE ICDM - the method Lesson 2 builds, isolating anomalies instead of modelling normal.
- Aggarwal (2017), Outlier Analysis, 2nd ed. (Springer) - the standard book-length treatment, from distances to high-dimensional detection.
Lesson 1 complete
You now have the two things every anomaly method needs: a clear idea of what "does not fit" means (distance versus density, global versus local versus contextual), and an honest way to score a detector (precision and recall, never accuracy alone, when anomalies are rare).
Next, Lesson 2: Isolation Forests. Instead of modelling what normal looks like, you will isolate the odd points directly, with random splits that fence off an anomaly in far fewer cuts than a crowded point, and turn that path length into an anomaly score.