Algorithmcore
Local outlier factor
Also called LOF.
Scores each point by the mean local reachability density of its k nearest neighbors divided by its own, so a point in a sparser place than its neighbors scores well above 1.
- Solves
- Anomaly detection
- Time
- O(n^2 (d + log n)) worst
- Space
- O(n^2) extra
- Where
- d = the dimension; k = the number of neighbors; n = the number of points
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Markus M. Breunig, Hans Peter Kriegel, Raymond T. Ng, Jörg Sander, 2000
The local outlier factor compares how crowded the place around a point is with how crowded the places around its nearest neighbors are. A value near 1 means is as dense as its neighbors. A value well above 1 means sits in a sparser place than they do, which makes it a local outlier. Breunig, Kriegel, Ng and Sander (2000) defined it for the anomaly detection problem because a single global distance threshold, as in kNN outlier detection, fails when the clusters of normal data have different densities.
In plain words
Picture a city with a crowded center and quiet suburbs. A house in the suburbs is far from its neighbors, but so are all the other suburb houses, so it is normal there. A house just outside the crowded center, at a distance that would be small in the suburbs, is odd: its neighbors are in the center and they are much closer to each other than to it.
LOF measures this. For each point, estimate how dense its own neighborhood is. Then divide the average density of its neighbors by its own density. Points that are as dense as their neighbors get about 1. Points that are much less dense than their neighbors get a large number.
The problem
The input is a list of pairwise distinct points with the Euclidean distance , and an integer with . In the paper is called MinPts. The definitions are these.
- The -distance is the -th smallest of the distances from to the other points.
- The -distance neighborhood is the set of other points with . It holds at least points, and more when distances tie.
- The reachability distance of from is .
- The local reachability density is , the inverse of the mean reachability distance.
- The local outlier factor is .
The output is for every . Ranking the points by this value, or flagging those above a threshold, is a separate step; the threshold is a heuristic choice.
The algorithm
LOCAL-OUTLIER-FACTOR(x[1..n], k)- 1
for p ← 1 to n do - 2
R ← the pairs (dist(x_p, x_o), o) for all o ≠ p, sorted by distance - 3
kd[p] ← the distance of the k-th pair of R - 4
N[p] ← the pairs of R with distance ≤ kd[p] - 5
for p ← 1 to n do - 6
s ← the sum over (o, δ) in N[p] of max(kd[o], δ) - 7
lrd[p] ← |N[p]| / s - 8
for p ← 1 to n do - 9
lof[p] ← (the sum over (o, δ) in N[p] of lrd[o]) / (|N[p]| · lrd[p]) - 10
return lof
The first pass, lines L1 to L4, finds the -distance and the neighborhood of every point. The neighborhood keeps all points tied at the -distance, so it can have more than members. The second pass needs the -distance of every neighbor, which is why it is a separate loop: line L6 sums the reachability distances and line L7 inverts their mean. The third pass needs the density of every neighbor, so it also waits until the second pass is done. Line L9 divides the mean density of the neighbors by the density of the point.
The reachability distance smooths the density. For a neighbor , all points closer to than count as being at distance , so small changes in a dense cluster do not change much.
Example
Take and the nine points on a line. The points to form a dense cluster with gaps of 1. The points to form a sparse cluster with gaps of 10. The point is 4 away from the dense cluster.
| point | kd | reach distances | lrd | LOF | |
|---|---|---|---|---|---|
| 0 | 2 | 1, 2 | 1, 2 | 2/3 | 1.0 |
| 1 | 1 | 0, 2 | 2, 1 | 2/3 | 1.0 |
| 2 | 1 | 1, 3 | 1, 2 | 2/3 | 1.0 |
| 3 | 2 | 1, 2 | 2, 1 | 2/3 | 1.0 |
| 7 | 5 | 2, 3 | 5, 4 | 2/9 = 0.2222 | 3.0 |
| 20 | 13 | 7, 30 | 13, 10 | 2/23 = 0.0870 | 1.7778 |
| 30 | 10 | 20, 40 | 13, 10 | 2/23 = 0.0870 | 0.8833 |
| 40 | 10 | 30, 50 | 10, 20 | 1/15 = 0.0667 | 1.1522 |
| 50 | 20 | 30, 40 | 20, 10 | 1/15 = 0.0667 | 1.1522 |
The point 1 has two neighbors at distance 1, so its -distance is 1. For the point 7, the reachability distance from the point 2 is and from the point 3 it is , so . Its neighbors have density , three times larger, so , the largest value. The kNN score ranks the point 7 (score 5) below all the points of the sparse cluster (scores 10 to 20). LOF ranks it first, and the sparse points stay near 1. The point 20 gets 1.78 because one of its two neighbors is the point 7.
Correctness
Each pass computes one of the definitions for all points, and each pass reads only values that an earlier pass finished. Line L3 is the -distance because the row is sorted, and line L4 keeps exactly the points within it. Line L6 adds the reachability distances, because is final for every after the first pass. Line L9 is the definition of LOF, because every is final after the second pass. The denominators are positive when the points are distinct: every reachability distance is at least .
Breunig et al. also prove bounds on the value (Theorem 1). Let direct_min and direct_max be the smallest and the largest of over , and indirect_min and indirect_max the same over for and . Then direct_min / indirect_max direct_max / indirect_min. The proof and the bound are in the proofs section below.
Proof: The three passes compute LOF as defined, and LOF lies between the direct and indirect boundsfull
Setting. The points are pairwise distinct and . We write , , , and for the quantities of the problem statement.
Termination. Each of the three loops runs over . Each body does a finite amount of work: a sort of pairs, and sums over a list of at most pairs. So the procedure stops.
Claim 1 (first pass). After the loop of lines L1 to L4, and is the list of pairs for , for every .
Proof. Line L2 lists the distances from to all other points in increasing order. Since , the -th pair exists, and its distance is the -th smallest distance, which is by definition. Line L4 keeps exactly the pairs with distance at most , which is the definition of . The value for is not changed later in the loop.
Claim 2 (second pass). After the loop of lines L5 to L7, for every , and every value is positive and finite.
Proof. By Claim 1, when the second loop starts, is final for every and is with the distances. So line L6 computes . Because the points are distinct, for , so each term is positive and . The set has at least members. Line L7 sets , which is the definition of and lies in .
Claim 3 (third pass). After the loop of lines L8 and L9, for every .
Proof. By Claim 2, every is final and positive when the third loop starts. Line L9 computes , which is the definition of , and the denominator is positive. Line L10 returns these values.
Theorem (Breunig et al., Theorem 1). For every point , let
and let and be the smallest and largest of over all and . Then
Proof. The value is the mean of the numbers , . A mean lies between the smallest and the largest of the numbers, so . In the same way, for each , is the mean of over , and each of these numbers is between and . So for each neighbor , and the mean of over satisfies the same bounds. By definition , a product of two positive numbers. The product of the lower bounds gives , and the product of the upper bounds gives .
Corollary (values near 1 in a cluster). If all the numbers and above lie in an interval with , then . This follows from the theorem with and .
By Claims 1 to 3 the procedure returns for every , and the theorem gives the bounds that the tests check on random inputs.
Complexity
The cost is in the real-RAM model.
- Time. Line L2 computes distances in time and sorts them in time, for each of the points. The two later passes take time proportional to the total size of the neighborhoods, which is at most . The total is . A selection of the -th distance instead of a sort brings the first pass to .
- Space. The neighborhoods take space when there are no ties and in the worst case, when many distances are equal.
- With an index. An index for nearest neighbor queries, such as a k-d tree in low dimension, can replace the scan of line L2. Then the first pass costs queries, and the two later passes are linear in the size of the stored neighborhoods.
Properties
- Local. The value compares a point only with its neighbors, so one threshold works across clusters of different densities.
- Near 1 inside a cluster. For a point deep inside a cluster where the reachability distances are all about equal, the value is about 1. Theorem 1 makes this exact: if all the direct and indirect reachability distances are within a factor of each other, the value is within that factor of 1.
- Not a probability. There is no fixed cut that means "outlier". A value of 1.5 can be strong in one data set and weak in another; the threshold is a heuristic.
- Scale invariant, not unit invariant. Multiplying all coordinates by the same factor leaves LOF unchanged, because it is a ratio of distances. Changing the units of one feature does change it.
Variants and improvements
- A range of . The paper studies how LOF changes with MinPts. It suggests computing LOF for a range of values, up to about the size of the smallest group that should still count as normal, and ranking each point by its largest value over the range. This is a heuristic.
- Novelty detection. To score a new point against a fixed training set, compute , the reachability distances and against the training points, and divide the mean of its neighbors by . The training values do not change.
- Approximate neighbors. In high dimension, approximate nearest neighbor search gives the neighborhoods faster, at the cost of exact values.
- Clustering with the same quantities. The -distance and the reachability distance are close to the core distance and the reachability distance of OPTICS, a relative of DBSCAN from the same research group.
When to use it
Use it on numeric data of low or moderate dimension when normal data form clusters of different densities and outliers are points that are sparse compared with their own surroundings. Use kNN outlier detection when the clusters have similar density and only the global top is needed, since its pruning makes it faster. Use the isolation forest for large , since LOF needs the neighbors of every point.
Pitfalls
- Duplicates. If or more other points are equal to , then , and if all the neighbors of a point have -distance 0 and distance 0, the sum of line L6 is 0 and line L7 divides by zero. Remove or count duplicates first, or use larger than the largest number of copies. The code raises an error instead of returning a wrong value.
- Exactly neighbors. If line L4 keeps only the first pairs of the sorted row, ties at the -distance are broken by the order of the input and the result depends on that order. Line L4 must keep every pair with distance .
- Using dist instead of reach. If line L6 sums instead of , the density of points in a dense cluster changes a lot with small moves, and the values inside a cluster scatter around 1.
- Reachability in the wrong direction. The reachability distance of from uses , the -distance of the neighbor, not of . Line L6 must read .
- One pass. Computing inside the first loop reads -distances that are not yet known. The three loops must stay separate.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-outlier-factor/. The authors are listed in prov/45657B.jsonl.
import math
from typing import Sequence
Point = Sequence[float]
def local_outlier_factor(x: Sequence[Point], k: int) -> list[float]:
"""Return the local outlier factor LOF_k of each point, in input order.
The definitions are those of Breunig, Kriegel, Ng and Sander (2000), with
k in the role of MinPts: the k-distance, the k-distance neighborhood (which
holds more than k points when distances tie), the reachability distance,
the local reachability density lrd and LOF. A value near 1 means the point
is as dense as its neighbors; a large value means it is in a sparser place.
Precondition: 1 <= k <= len(x) - 1, the points are pairwise distinct and
have one dimension d. Cost: Theta(n^2 d + n^2 log n) time with a sort of
each row, O(n^2) extra space in the worst case of many ties, O(n k) when
the neighborhoods have size k.
"""
n = len(x)
if not 1 <= k <= n - 1:
raise ValueError("need 1 <= k <= n - 1")
kdist = [0.0] * n
nbrs: list[list[tuple[int, float]]] = []
for p in range(n): # @line L1
row = sorted((math.dist(x[p], x[o]), o) for o in range(n) if o != p) # @line L2
kdist[p] = row[k - 1][0] # @line L3
nbrs.append([(o, dpo) for dpo, o in row if dpo <= kdist[p]]) # @line L4
lrd = [0.0] * n
for p in range(n): # @line L5
total = sum(max(kdist[o], dpo) for o, dpo in nbrs[p]) # @line L6
if total == 0.0:
raise ValueError("duplicate points give an infinite density")
lrd[p] = len(nbrs[p]) / total # @line L7
lof = [0.0] * n
for p in range(n): # @line L8
lof[p] = sum(lrd[o] for o, _ in nbrs[p]) / (len(nbrs[p]) * lrd[p]) # @line L9
return lof # @line L10
test_local_outlier_factor.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-outlier-factor/. The authors are listed in prov/45657B.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from local_outlier_factor import local_outlier_factor
LINE = [0, 1, 2, 3, 7, 20, 30, 40, 50]
def oracle(x, k, dist):
"""LOF from the formulas of Breunig et al., on the full distance matrix."""
n = len(x)
d = [[dist(x[i], x[j]) for j in range(n)] for i in range(n)]
kd = [sorted(d[i][j] for j in range(n) if j != i)[k - 1] for i in range(n)]
nb = [[j for j in range(n) if j != i and d[i][j] <= kd[i]] for i in range(n)]
reach = lambda p, o: max(kd[o], d[p][o])
lrd = [len(nb[p]) / sum(reach(p, o) for o in nb[p]) for p in range(n)]
lof = [sum(lrd[o] for o in nb[p]) / (len(nb[p]) * lrd[p]) for p in range(n)]
return lof, nb, reach
def exact_line(values, k):
pts = [Fraction(v) for v in values]
lof, _, _ = oracle(pts, k, lambda a, b: abs(a - b))
return lof
def test_example() -> None:
got = local_outlier_factor([(float(v),) for v in LINE], 2)
want = exact_line(LINE, 2)
assert want[4] == 3
assert want[:4] == [1, 1, 1, 1]
assert want[5] == Fraction(16, 9)
for g, w in zip(got, want):
assert math.isclose(g, float(w), rel_tol=1e-12)
assert max(range(len(got)), key=lambda i: got[i]) == 4
def test_edges() -> None:
assert local_outlier_factor([(0.0,), (1.0,)], 1) == [1.0, 1.0]
grid = [(float(a), float(b)) for a in range(3) for b in range(3)]
lof = local_outlier_factor(grid, 4)
want, _, _ = oracle(grid, 4, math.dist)
for g, w in zip(lof, want):
assert math.isclose(g, w, rel_tol=1e-12)
with pytest.raises(ValueError):
local_outlier_factor([(0.0,), (1.0,)], 2)
with pytest.raises(ValueError):
local_outlier_factor([(0.0,), (0.0,), (5.0,)], 1)
def test_random_against_formula_and_bounds() -> None:
rng = random.Random(2000)
for trial in range(500):
d = rng.randint(1, 3)
cells = list(itertools.product(range(-3, 4), repeat=d))
n = rng.randint(2, min(12, len(cells)))
x = [tuple(float(c) for c in p) for p in rng.sample(cells, n)]
k = rng.randint(1, n - 1)
got = local_outlier_factor(x, k)
want, nb, reach = oracle(x, k, math.dist)
for p in range(n):
assert math.isclose(got[p], want[p], rel_tol=1e-9)
# Theorem 1 of Breunig et al.: direct_min / indirect_max <= LOF <= direct_max / indirect_min.
direct = [reach(p, q) for q in nb[p]]
indirect = [reach(q, o) for q in nb[p] for o in nb[q]]
assert min(direct) / max(indirect) <= got[p] * (1 + 1e-9)
assert got[p] <= max(direct) / min(indirect) * (1 + 1e-9)
def test_exact_on_integer_lines() -> None:
rng = random.Random(31)
for _ in range(200):
n = rng.randint(2, 10)
values = rng.sample(range(-20, 21), n)
k = rng.randint(1, n - 1)
got = local_outlier_factor([(float(v),) for v in values], k)
for g, w in zip(got, exact_line(values, k)):
assert math.isclose(g, float(w), rel_tol=1e-12)
def test_local_outlier_beats_sparse_cluster() -> None:
rng = random.Random(5)
found = 0
trials = 30
for _ in range(trials):
dense = [(rng.gauss(0, 0.3), rng.gauss(0, 0.3)) for _ in range(30)]
sparse = [(rng.gauss(10, 3), rng.gauss(10, 3)) for _ in range(30)]
planted = (2.5, 0.0)
x = dense + sparse + [planted]
lof = local_outlier_factor(x, 5)
ranked = sorted(range(len(x)), key=lambda i: -lof[i])
found += len(x) - 1 in ranked[:3]
# A point at 8 standard deviations from the dense cluster: expect it in the top 3 in at least 90 percent of runs.
assert found / trials >= 0.9
History
Breunig, Kriegel, Ng and Sander presented the local outlier factor at SIGMOD 2000. Earlier distance-based definitions, such as the DB(p, D) outliers of Knorr and Ng (1998) and the -th neighbor distance of Ramaswamy, Rastogi and Shim (2000), give a yes or no answer or a global score. LOF was the first widely used score that gives each point a degree of outlierness relative to its own neighborhood. It reuses the -distance and the reachability distance of the density based clustering methods of the same group, and many later local scores are variants of it.
References
- Markus M. Breunig, Hans-Peter Kriegel, Raymond T. Ng and Jörg Sander, LOF, identifying density-based local outliers, ACM SIGMOD 2000, pages 93 to 104, the definitions of the k-distance, the k-distance neighborhood, the reachability distance, the local reachability density (Definition 6) and LOF, and Theorem 1 (the bounds on LOF by the direct and indirect reachability distances)
- Varun Chandola, Arindam Banerjee and Vipin Kumar, Anomaly detection, a survey, ACM Computing Surveys 41(3), article 15, 2009, Section 5 (nearest neighbor based techniques), the part on relative density
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 45657B Edit this page History Report an error Markdown