Algorithm Search⌘K

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.

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
Properties
deterministicexactofflineiterative
Origin
Sridhar Ramaswamy, Rajeev Rastogi, Kyuseok Shim, 2000

k-nearest-neighbor outlier detection gives each point the score Dk(x)D^k(x), the distance from xx to its kk-th nearest other point, and reports the mm points with the largest scores. It is the simplest score for the anomaly detection problem: a point is strange when even its kk-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 mm-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 kk-th. The distance to the kk-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 x1,…,xn∈Rdx_1, \ldots, x_n \in \mathbb{R}^d with the Euclidean distance dist\mathrm{dist}, an integer kk with 1≤k≤n−11 \le k \le n - 1, and an integer mm with 0≤m≤n0 \le m \le n. For each ii, let Dk(xi)D^k(x_i) be the kk-th smallest of the n−1n - 1 distances dist(xi,xj)\mathrm{dist}(x_i, x_j), j≠ij \ne i. Order the points by the key (Dk(xi),−i)(D^k(x_i), -i), from high to low: the larger score first, and for equal scores the smaller index first. The output is the first mm points in this order, with their scores. This is the DnkD^k_n outlier problem of Ramaswamy et al., with mm in place of their nn.

The algorithm

  1. KNN-OUTLIERS(x[1..n], k, m)
  2. 1T ← empty min-heap of keys (score, -i) ▷ the best m points so far
  3. 2for i ← 1 to n do
  4. 3N ← empty max-heap ▷ the k smallest distances from x_i seen so far
  5. 4pruned ← false
  6. 5for j ← 1 to n with j ≠ i do
  7. 6add dist(x_i, x_j) to N; if |N| > k then remove the largest
  8. 7if |N| = k and |T| = m and max N < (the smallest score in T) then
  9. 8pruned ← true; leave the loop of L5 ▷ D^k(x_i) ≤ max N
  10. 9if not pruned then
  11. 10add the key (max N, -i) to T; if |T| > m then remove the smallest key
  12. 11return the points of T, from the largest key to the smallest

The heap NN holds the kk smallest distances seen so far, so max⁡N\max N is the kk-th smallest distance among the points scanned. More points can only add smaller distances, so max⁡N\max N only goes down, and it is always at least Dk(xi)D^k(x_i). Line L7 compares this upper bound with the threshold, the smallest score in TT. If the bound is already smaller, xix_i cannot enter TT now, and it cannot enter later either, because the threshold never goes down. A point that is not pruned has scanned all others, so max⁡N=Dk(xi)\max N = D^k(x_i) exactly at line L10.

Example

Take k=2k = 2, m=2m = 2 and the eight points (8,0)(8,0), (4,4)(4,4), (0,0)(0,0), (1,0)(1,0), (4,5)(4,5), (0,1)(0,1), (1,1)(1,1), (0.5,0.5)(0.5,0.5), numbered 1 to 8. The last column is the threshold after the step.

ii point scanned result TT (index: score) threshold
1 (8, 0) 7 D2=41=6.4031D^2 = \sqrt{41} = 6.4031 1: 6.4031 none
2 (4, 4) 7 D2=18=4.2426D^2 = \sqrt{18} = 4.2426 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 D2=5.0D^2 = 5.0 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 k=1k = 1 instead, the pair (4,4)(4,4) and (4,5)(4,5) hide each other: each has a neighbor at distance 1, and the output is point 1 (score 32=5.6569\sqrt{32} = 5.6569) 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 1,…,i1, \ldots, i, the heap TT holds the min⁡(m,i)\min(m, i) largest keys among the points 1,…,i1, \ldots, i, 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 TT from then on. At the end, TT holds the mm 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 ii, let Di=Dk(xi)D_i = D^k(x_i) be the kk-th smallest of the distances dist(xi,xj)\mathrm{dist}(x_i, x_j), j≠ij \ne i, and let its key be κi=(Di,−i)\kappa_i = (D_i, -i), ordered lexicographically. All keys are distinct, because the second parts are distinct. The claim is that line L11 returns the mm points of largest key, in decreasing order of key, each with its score DiD_i. We assume 1≤k≤n−11 \le k \le n - 1 and 1≤m≤n1 \le m \le n; for m=0m = 0 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 n(n−1)n(n - 1) steps of the inner loop.

Lemma 1 (the bound in NN). During the scan of point ii, after the distances to a set SS of other points have been added, NN holds the min⁡(k,∣S∣)\min(k, |S|) smallest of them. When ∣S∣≥k|S| \ge k, max⁡N\max N is the kk-th smallest distance from xix_i to the points of SS, and max⁡N≥Di\max N \ge D_i. If SS is the set of all n−1n - 1 other points, max⁡N=Di\max N = D_i.

Proof. By induction on ∣S∣|S|. At the start NN is empty. Line L6 adds the new distance and, if NN then has k+1k + 1 items, removes the largest. The kk smallest of S∪{j}S \cup \{j\} are the kk smallest of the k+1k + 1 values made of the old NN and the new distance, because every value of SS that is not in NN is at least each value of the old NN. So the statement holds for S∪{j}S \cup \{j\}. The kk-th smallest of a subset of a set of numbers is at least the kk-th smallest of the whole set, since the whole set has at least as many values below each level. So max⁡N≥Di\max N \ge D_i, with equality when SS is all the others. □\square

Lemma 2 (the threshold never goes down). Let θ\theta be the smallest key in TT when ∣T∣=m|T| = m. Each later change to TT replaces the smallest key by a larger key, so θ\theta does not decrease.

Proof. When ∣T∣=m|T| = m, line L10 inserts a key and then removes the smallest of the m+1m + 1 keys. The new smallest key is the smallest of the mm keys that remain, and each of them is at least the old θ\theta. □\square

Invariant. After the iteration ii of the loop of line L2, the heap TT holds exactly the min⁡(m,i)\min(m, i) largest keys among κ1,…,κi\kappa_1, \ldots, \kappa_i, and the first part of each key is the exact score.

Initialization. Before the first iteration, TT is empty, which is the set of the 00 largest keys of no points.

Maintenance. Assume the invariant after i−1i - 1. Two cases.

  • Point ii is pruned. Then at line L7, ∣N∣=k|N| = k, ∣T∣=m|T| = m and $\max N < $ the score of θ\theta, the smallest key of TT. By Lemma 1, Di≤max⁡ND_i \le \max N, so DiD_i is strictly smaller than the score of θ\theta and κi<θ\kappa_i < \theta. Since TT holds the mm largest keys of 1,…,i−11, \ldots, i - 1 and κi\kappa_i is below all of them, the mm largest keys of 1,…,i1, \ldots, i are the same set. TT is not changed, so the invariant holds.
  • Point ii is not pruned. Then the loop of line L5 scanned all n−1n - 1 other points, and by Lemma 1 the key added at line L10 is (Di,−i)=κi(D_i, -i) = \kappa_i, with the exact score. If ∣T∣<m|T| < m before the step, then i−1<mi - 1 < m, and TT holds all keys of 1,…,i−11, \ldots, i - 1; adding κi\kappa_i gives all i≤mi \le m keys. If ∣T∣=m|T| = m, line L10 adds κi\kappa_i and removes the smallest of the m+1m + 1 keys, which leaves the mm largest keys of 1,…,i1, \ldots, i.

Termination of the loop. After i=ni = n, TT holds the mm 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 ii is a lower bound on every later threshold, so no later state of TT would have admitted κi\kappa_i. The maintenance step above uses only the threshold at the time of the test, and the invariant then carries the claim to the end. ■\blacksquare

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 nn points scans up to n−1n - 1 others. Each scan step computes a distance in Θ(d)\Theta(d) time and does one heap operation on NN in O(log⁡k)O(\log k) time. Each point does at most one operation on TT in O(log⁡m)O(\log m) time. The total is O(n2(d+log⁡k)+nlog⁡m)O(n^2 (d + \log k) + n \log m). It is reached when no point is pruned, for example when all points are equal.
  • Best case. A point can be pruned after kk distances, when the first kk neighbors it scans are close. The first mm points cannot be pruned, because TT is not full, and each scans all n−1n - 1 others. If every later point is pruned after kk steps, the time is O((mn+nk)(d+log⁡k)+nlog⁡m)O\big((m n + n k)(d + \log k) + n \log m\big).
  • Space. The heaps take O(k+m)O(k + m) 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 kk distances. Use the mean of the distances to the kk nearest neighbors instead of the kk-th one. The score changes less from one kk to the next. The same pruning works, because the mean of the kk 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 pp of the data lies farther than DD 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: Dk(z)D^k(z) is the kk-th smallest distance from zz 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 nn is large and a quadratic scan is too slow.

Pitfalls

  • Counting the point itself. If line L5 does not skip j=ij = i, the distance 0 enters NN and the score becomes Dk−1D^{k-1}. The loop must skip the point itself, and kk must be at most n−1n - 1.
  • Pruning with ≤\le and the wrong tie rule. If line L7 prunes when max⁡N≤\max N \le 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 (score,−i)(score, -i) of line L10. With another tie rule, prune only on a strict <<.
  • A small kk hides small groups. A group of g≤kg \le k points far from the rest gets small scores when k<gk < g, because each point has close neighbors in its own group. The example shows this for k=1k = 1 and a pair. Choose kk larger than the size of the groups to be found.
  • Duplicates. Many equal points give Dk=0D^k = 0 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.

knn_outlier_detection.pyI0RawGitHub
# 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 kk-th nearest neighbor, and gave the nested loop, index and partition algorithms with the pruning by the current mm-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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example