Local Outlier Factor and One-Class SVM
In Lesson 2, the isolation forest scored every charge on one global question: how few random cuts fence this point off from the whole dataset? That works beautifully for a point sitting far out on its own. But some outliers are not far from everything, they are only far from their own neighbourhood, and a global score walks right past them. That is exactly how a fraudulent $130 charge on Maya's card slips through: it is a touch bigger than her everyday $22 coffees but nowhere near her hundreds-of-dollars big purchases, so nothing global flags it.
This lesson catches those. First the Local Outlier Factor (LOF), which scores each point against the density of its own neighbours. Then the one-class SVM, which learns a boundary around the normal region so you can wave any new point at it and ask, inside or out?
By the end of this lesson you will be able to:
- Explain why a single global cutoff both misses a locally-sparse outlier and false-alarms on legitimate spread-out points
- Define LOF as a local density ratio (k-distance, reachability distance, local density, the LOF ratio) and read LOF near 1 versus LOF well above 1
- Compute LOF from scratch in R and interpret the scores
- Fit a one-class SVM on normal data, tune its two knobs, and flag new points that fall outside the learned boundary
Prerequisites: you can run R and read base R (matrix, data.frame, scale, dist, sapply, small functions), and you have done Lesson 1: What Is an Anomaly? (global vs local outliers, distance vs density) and Lesson 2: Isolation Forest (a global detector). No SVM background is needed; the margin idea is built up here.
A global cutoff misses a local outlier
Let us keep working with Maya's card, but look at the shape of her spending more carefully. It has two natural clusters. A big, tight crowd of everyday charges: coffee, groceries, a few dollars, a few miles from home. And a small, loose scatter of legitimate big purchases: a laptop, a flight, hundreds of dollars, sometimes far away. Now a fraudulent $130 charge lands, 9 miles out. It is a bit bigger than her everyday spend, but nowhere near her big-purchase range.
Watch what a global rule does with it. First build the card (each lesson runs in a fresh R session, so we create the data here, run this once):
The obvious global rule (and the natural next step from Lesson 1's z-score) is: how far does each charge sit from the center of Maya's spending? Rank by that distance and look at the top of the list.
The 12 charges a global cutoff screams about are all 12 of Maya's legitimate big purchases, pure false alarms. And the actual fraud? It ranks 22nd of 73, buried in the crowd of ordinary charges. By distance-from-center, the fraud looks completely normal.