Algorithmcore
k-nearest-neighbor outlier detection
Also called kNN distance outlier score, k-th nearest neighbor distance outlier.
Scores each point by the distance to its k-th nearest neighbor and reports the m points with the largest scores, with a pruning rule that stops the scan of a point that cannot reach the top m.
- Solves
- Anomaly detection
- Time
- O(n^2 (d + log k) + n log m) worst
- Space
- O(k + m) extra
- Where
- d = the dimension; k = the rank of the neighbor; m = the number of outliers reported; n = the number of points
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Sridhar Ramaswamy, Rajeev Rastogi, Kyuseok Shim, 2000
k-nearest-neighbor outlier detection gives each point the score , the distance from to its -th nearest other point, and reports the points with the largest scores. It is the simplest score for the anomaly detection problem: a point is strange when even its -th closest neighbor is far away. Ramaswamy, Rastogi and Shim (2000) defined this ranking. The nested loop below is exact and uses their pruning rule: the scan of a point stops as soon as its score is sure to be below the -th best score found so far.
In plain words
Think of each point as a house on a map. For each house, walk to the nearest neighbors and count them off: first, second, up to the -th. The distance to the -th one is the score of the house. A house in a town has many neighbors close by, so its score is small. A lonely farm far from town has a large score.
To report the loneliest few houses, you do not need every exact score. Keep a short list of the loneliest houses so far. While you measure a new house, its score so far can only go down as you find closer neighbors. Once it is already below the last house on your list, stop: this house cannot get on the list.
The problem
The input is a list of points with the Euclidean distance , an integer with , and an integer with . For each , let be the -th smallest of the distances , . Order the points by the key , from high to low: the larger score first, and for equal scores the smaller index first. The output is the first points in this order, with their scores. This is the outlier problem of Ramaswamy et al., with in place of their .
The algorithm
KNN-OUTLIERS(x[1..n], k, m)- 1
T ← empty min-heap of keys (score, -i) ▷ the best m points so far - 2
for i ← 1 to n do - 3
N ← empty max-heap ▷ the k smallest distances from x_i seen so far - 4
pruned ← false - 5
for j ← 1 to n with j ≠ i do - 6
add dist(x_i, x_j) to N; if |N| > k then remove the largest - 7
if |N| = k and |T| = m and max N < (the smallest score in T) then - 8
pruned ← true; leave the loop of L5 ▷ D^k(x_i) ≤ max N - 9
if not pruned then - 10
add the key (max N, -i) to T; if |T| > m then remove the smallest key - 11
return the points of T, from the largest key to the smallest
The heap holds the smallest distances seen so far, so is the -th smallest distance among the points scanned. More points can only add smaller distances, so only goes down, and it is always at least . Line L7 compares this upper bound with the threshold, the smallest score in . If the bound is already smaller, cannot enter now, and it cannot enter later either, because the threshold never goes down. A point that is not pruned has scanned all others, so exactly at line L10.
Example
Take , and the eight points , , , , , , , , numbered 1 to 8. The last column is the threshold after the step.
| point | scanned | result | (index: score) | threshold | |
|---|---|---|---|---|---|
| 1 | (8, 0) | 7 | 1: 6.4031 | none | |
| 2 | (4, 4) | 7 | 1: 6.4031, 2: 4.2426 | 4.2426 | |
| 3 | (0, 0) | 5 | pruned, bound 1.0 | same | 4.2426 |
| 4 | (1, 0) | 5 | pruned, bound 1.4142 | same | 4.2426 |
| 5 | (4, 5) | 7 | 1: 6.4031, 5: 5.0 | 5.0 | |
| 6 | (0, 1) | 4 | pruned, bound 1.4142 | same | 5.0 |
| 7 | (1, 1) | 3 | pruned, bound 4.2426 | same | 5.0 |
| 8 | (0.5, 0.5) | 3 | pruned, bound 4.9497 | same | 5.0 |
The output is point 1 with score 6.4031 and point 5 with score 5.0. The scan does 41 distance computations instead of 56. With instead, the pair and hide each other: each has a neighbor at distance 1, and the output is point 1 (score ) and point 2 (score 1.0, a tie with point 5 that the smaller index wins).
Correctness
The invariant of the loop of line L2 is: after the points , the heap holds the largest keys among the points , with their exact scores. A pruned point has a score below the threshold at the time, and the threshold never goes down, so the point is below every key of from then on. At the end, holds the largest keys of all points, which line L11 returns in order. The full proof is in the proofs section below.
Proof: The pruned nested loop returns the m points with the largest k-th neighbor distancefull
Notation. For a point , let be the -th smallest of the distances , , and let its key be , ordered lexicographically. All keys are distinct, because the second parts are distinct. The claim is that line L11 returns the points of largest key, in decreasing order of key, each with its score . We assume and ; for the code returns the empty list at once.
Termination. Each loop of lines L2 and L5 runs over a finite range and the body does a bounded number of heap operations. So the procedure stops after at most steps of the inner loop.
Lemma 1 (the bound in ). During the scan of point , after the distances to a set of other points have been added, holds the smallest of them. When , is the -th smallest distance from to the points of , and . If is the set of all other points, .
Proof. By induction on . At the start is empty. Line L6 adds the new distance and, if then has items, removes the largest. The smallest of are the smallest of the values made of the old and the new distance, because every value of that is not in is at least each value of the old . So the statement holds for . The -th smallest of a subset of a set of numbers is at least the -th smallest of the whole set, since the whole set has at least as many values below each level. So , with equality when is all the others.
Lemma 2 (the threshold never goes down). Let be the smallest key in when . Each later change to replaces the smallest key by a larger key, so does not decrease.
Proof. When , line L10 inserts a key and then removes the smallest of the keys. The new smallest key is the smallest of the keys that remain, and each of them is at least the old .
Invariant. After the iteration of the loop of line L2, the heap holds exactly the largest keys among , and the first part of each key is the exact score.
Initialization. Before the first iteration, is empty, which is the set of the largest keys of no points.
Maintenance. Assume the invariant after . Two cases.
- Point is pruned. Then at line L7, , and $\max N < $ the score of , the smallest key of . By Lemma 1, , so is strictly smaller than the score of and . Since holds the largest keys of and is below all of them, the largest keys of are the same set. is not changed, so the invariant holds.
- Point is not pruned. Then the loop of line L5 scanned all other points, and by Lemma 1 the key added at line L10 is , with the exact score. If before the step, then , and holds all keys of ; adding gives all keys. If , line L10 adds and removes the smallest of the keys, which leaves the largest keys of .
Termination of the loop. After , holds the largest keys among all points, with exact scores. Line L11 sorts them from the largest key to the smallest, which is the order of the problem: larger score first, and for equal scores the smaller index first.
Lemma 2 is what makes the pruning safe for the later points: the threshold that rejected point is a lower bound on every later threshold, so no later state of would have admitted . The maintenance step above uses only the threshold at the time of the test, and the invariant then carries the claim to the end.
Complexity
The cost is in the real-RAM model, with one unit for each arithmetic operation and comparison on reals.
- Worst case. Each of the points scans up to others. Each scan step computes a distance in time and does one heap operation on in time. Each point does at most one operation on in time. The total is . It is reached when no point is pruned, for example when all points are equal.
- Best case. A point can be pruned after distances, when the first neighbors it scans are close. The first points cannot be pruned, because is not full, and each scans all others. If every later point is pruned after steps, the time is .
- Space. The heaps take extra space. The points are read in place.
- In practice. Bay and Schwabacher (2003) measured close to linear time on large data sets when the points are scanned in a random order: most points are in dense regions and are pruned after few distances. This is a measurement on their data, not a bound. On data with no outliers, or in high dimension where all distances are close, the pruning does little.
Properties
- Exact. The pruning never removes a point of the true answer; the output equals the brute force ranking.
- Global. The score is an absolute distance. One threshold serves all regions of the space, so a point at the edge of a sparse cluster can score higher than a point near a dense cluster that is clearly odd. The local outlier factor corrects this.
- Scale dependent. The score depends on the units of each feature. Features need the same scale before the distances mean anything.
- Order dependent cost, not result. The scan order changes how much is pruned, and never which points are reported.
Variants and improvements
- Score by the mean of the distances. Use the mean of the distances to the nearest neighbors instead of the -th one. The score changes less from one to the next. The same pruning works, because the mean of the smallest distances seen so far also only goes down.
- DB(p, D) outliers. Knorr and Ng (1998) call a point an outlier when at least a fraction of the data lies farther than from it. This needs two parameters with units and gives a set, not a ranking.
- Random order. Shuffle the points before the scan of line L5. The threshold then rises fast, and the expected scan of a typical point is short (Bay and Schwabacher 2003).
- Index and partition methods. A k-d tree or another index answers the neighbor queries of each point in sublinear time in low dimension. Ramaswamy et al. also bound the scores of whole partitions of the data and skip partitions that cannot hold an outlier.
- Novelty detection. Score new points against a fixed training set: is the -th smallest distance from to the training points. A threshold at a high quantile of the training scores sets the false alarm rate on normal data.
When to use it
Use it on numeric data of low or moderate dimension, when outliers are isolated points far from all others and the clusters of normal data have similar density. It needs no training and no model, and the score is easy to explain: "the third closest record is this far away". Use the local outlier factor when the clusters have different densities, and the isolation forest when is large and a quadratic scan is too slow.
Pitfalls
- Counting the point itself. If line L5 does not skip , the distance 0 enters and the score becomes . The loop must skip the point itself, and must be at most .
- Pruning with and the wrong tie rule. If line L7 prunes when threshold, a point whose score ties with the threshold is dropped. That is right only when ties go to the earlier point, as with the key of line L10. With another tie rule, prune only on a strict .
- A small hides small groups. A group of points far from the rest gets small scores when , because each point has close neighbors in its own group. The example shows this for and a pair. Choose larger than the size of the groups to be found.
- Duplicates. Many equal points give for each of them, even when the group is far from the rest. Remove or count duplicates before scoring.
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/knn-outlier-detection/. The authors are listed in prov/TYY18A.jsonl.
import heapq
import math
from typing import Sequence
Point = Sequence[float]
def knn_outliers(x: Sequence[Point], k: int, m: int) -> list[tuple[int, float]]:
"""Return the m points with the largest distance to their k-th nearest neighbor.
The score of point i is D^k(i), the k-th smallest Euclidean distance from
x[i] to the other points. The result is a list of (index, score), from the
highest score to the lowest; equal scores go to the smaller index. This is
the nested loop of Ramaswamy, Rastogi and Shim with the pruning rule: stop
the scan of a point as soon as its score cannot reach the top m.
Precondition: 1 <= k <= len(x) - 1 and 0 <= m <= len(x), all points of one
dimension d. Cost: O(n^2 (d + log k) + n log m) time in the worst case,
O(k + m) extra space.
"""
n = len(x)
if not 1 <= k <= n - 1 or not 0 <= m <= n:
raise ValueError("need 1 <= k <= n - 1 and 0 <= m <= n")
if m == 0:
return []
top: list[tuple[float, int]] = [] # @line L1 min-heap of (score, -index)
for i in range(n): # @line L2
near: list[float] = [] # @line L3 max-heap of the k smallest distances, negated
pruned = False # @line L4
for j in range(n): # @line L5
if j == i:
continue
dist = math.dist(x[i], x[j])
if len(near) < k: # @line L6
heapq.heappush(near, -dist)
elif dist < -near[0]:
heapq.heapreplace(near, -dist)
if len(near) == k and len(top) == m and -near[0] < top[0][0]: # @line L7
pruned = True # @line L8
break
if not pruned: # @line L9
key = (-near[0], -i)
if len(top) < m: # @line L10
heapq.heappush(top, key)
elif key > top[0]:
heapq.heapreplace(top, key)
best = sorted(top, reverse=True) # @line L11
return [(-neg_i, score) for score, neg_i in best]
test_knn_outlier_detection.py 80 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/knn-outlier-detection/. The authors are listed in prov/TYY18A.jsonl.
import math
import random
import pytest
from knn_outlier_detection import knn_outliers
EXAMPLE = [(8, 0), (4, 4), (0, 0), (1, 0), (4, 5), (0, 1), (1, 1), (0.5, 0.5)]
def oracle(x, k, m):
"""Brute force: all pairwise distances, sort, take the k-th, rank all points."""
n = len(x)
scores = []
for i in range(n):
d = sorted(math.dist(x[i], x[j]) for j in range(n) if j != i)
scores.append((d[k - 1], i))
scores.sort(key=lambda t: (-t[0], t[1]))
return [(i, s) for s, i in scores[:m]]
def same(a, b):
assert [i for i, _ in a] == [i for i, _ in b]
for (_, s), (_, t) in zip(a, b):
assert math.isclose(s, t, rel_tol=1e-12, abs_tol=1e-12)
def test_example() -> None:
got = knn_outliers(EXAMPLE, 2, 2)
assert [i for i, _ in got] == [0, 4]
assert math.isclose(got[0][1], math.sqrt(41))
assert math.isclose(got[1][1], 5.0)
def test_k_one_hides_a_pair() -> None:
got = knn_outliers(EXAMPLE, 1, 2)
assert [i for i, _ in got] == [0, 1]
assert math.isclose(got[1][1], 1.0)
def test_edges() -> None:
assert knn_outliers([(0.0,), (1.0,)], 1, 0) == []
assert knn_outliers([(0.0,), (1.0,)], 1, 2) == [(0, 1.0), (1, 1.0)]
same(knn_outliers([(2.0, 2.0)] * 5, 3, 2), [(0, 0.0), (1, 0.0)])
line = [(float(v),) for v in (1.0, 1.5, 2.0, 2.5, 3.0, 9.0)]
same(knn_outliers(line, 2, 6), oracle(line, 2, 6))
for k, m in ((0, 1), (2, 1), (1, 3)):
with pytest.raises(ValueError):
knn_outliers([(0.0,), (1.0,)], k, m)
def test_random_against_brute_force() -> None:
rng = random.Random(1801)
for _ in range(600):
n = rng.randint(2, 14)
d = rng.randint(1, 3)
x = [tuple(float(rng.randint(-4, 4)) for _ in range(d)) for _ in range(n)]
k = rng.randint(1, n - 1)
m = rng.randint(0, n)
same(knn_outliers(x, k, m), oracle(x, k, m))
def test_planted_outliers_are_found() -> None:
rng = random.Random(77)
hits = 0
trials = 40
for _ in range(trials):
x = [(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(40)]
planted = set()
for _ in range(3):
angle = rng.uniform(0, 2 * math.pi)
planted.add(len(x))
x.append((8 * math.cos(angle), 8 * math.sin(angle)))
found = {i for i, _ in knn_outliers(x, 3, 3)}
hits += len(found & planted)
# Points at radius 8 against a unit Gaussian blob: expect a detection rate of at least 0.95.
assert hits / (3 * trials) >= 0.95
History
Knorr and Ng (1998) gave the first distance-based definition of an outlier that does not assume a distribution. Ramaswamy, Rastogi and Shim (2000) replaced their two parameters by the ranking on the distance to the -th nearest neighbor, and gave the nested loop, index and partition algorithms with the pruning by the current -th score. Bay and Schwabacher (2003) showed that the simple nested loop with a random order and the same cutoff runs in close to linear time on many real data sets. The survey of Chandola, Banerjee and Kumar (2009) puts this score at the base of the nearest neighbor family of anomaly detectors.
References
- Sridhar Ramaswamy, Rajeev Rastogi and Kyuseok Shim, Efficient algorithms for mining outliers from large data sets, ACM SIGMOD 2000, pages 427 to 438, the definition of the D^k_n outliers, the nested loop and index based algorithms with the pruning by the current n-th largest score, and the partition based algorithm
- Edwin M. Knorr and Raymond T. Ng, Algorithms for mining distance-based outliers in large datasets, VLDB 1998, pages 392 to 403, the DB(p, D) outliers (a point with at least a fraction p of the data farther than D) and the nested loop and cell based algorithms
- Stephen D. Bay and Mark Schwabacher, Mining distance-based outliers in near linear time with randomization and a simple pruning rule, ACM SIGKDD 2003, pages 29 to 38, the nested loop with the cutoff rule on data in random order, and the measured near linear running time
- 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), Section 5.1 (the distance to the k-th nearest neighbor as a score)
Where this leads
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 TYY18A Edit this page History Report an error Markdown