AI Wiki中文/EN

Local outlier factor: density compared with neighbors

局部离群因子

Trace exact neighborhood radii, reachability densities and LOF scores, including ties, duplicate points and a changing reference dataset.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Intuition: unusual compared with whom?

An archive receives requests from two workstations. One produces timestamps close together; the other works at twice that spacing. A rule that flags every large neighbor distance can treat the second workstation’s ordinary rhythm as suspicious. Local outlier factor (LOF) asks whether a record occupies a much sparser neighborhood than its own neighbors do.

Use seven invented coordinates: 0, 1, 2, 20, 22, 24, 60. They are just positions on a line, with no assigned anomaly labels. At two-neighbor scale, the first three and the next three form two separated groups with different spacing. LOF gives both triplets the same pattern: 7/8, 4/3, 7/8. The last record scores 259/24, about 10.79. Its neighbors are relatively close to each other but far from it. Neither 4/3 nor 10.79 is a probability that a request is harmful.

The construction uses nearest-neighbor geometry, then compares local scales. It does not need cluster assignments. Breunig, Kriegel, Ng and Sander introduced LOF at SIGMOD 2000 to express local isolation as a degree rather than only a binary label. Original paper

Definition: use the neighbor’s radius

Take a finite set of record identities, each with a coordinate, and a distance function. Distinct records may share coordinates. For a record pp, choose an integer 1≤k<n1\le k<n and let rk(p)r_k(p) be the distance of rank kk in ascending order to another record. Include every tie at that radius:

Nk(p)={o:o≠p, d(p,o)≤rk(p)},reach⁡k(p,o)=max⁡{rk(o),d(p,o)}.N_k(p)=\{o:o\ne p,\ d(p,o)\le r_k(p)\},\qquad \operatorname{reach}_k(p,o)=\max\{r_k(o),d(p,o)\}.

The neighborhood can contain more than kk records. With coordinates 0, 1, -1, 4 and k=1k=1, the record at zero has both 1 and -1 as neighbors. Removing one by row order would change this definition. Also notice rk(o)r_k(o), the neighbor’s radius. Reachability distance can be asymmetric even when the underlying distance is symmetric. On 0, 1, 2 with k=2k=2, reachability from zero to one is 1, but from one to zero is 2. The radius prevents a tiny pairwise gap from making every nearby comparison arbitrarily dense. These are the original paper’s Definitions 3–5. Definitions

Average these adjusted distances, invert, then compare the neighbors’ densities with the record’s own density:

mk(p)=1∣Nk(p)∣∑o∈Nk(p)reach⁡k(p,o),lrd⁡k(p)=1mk(p),LOF⁡k(p)=1∣Nk(p)∣∑o∈Nk(p)lrd⁡k(o)lrd⁡k(p).m_k(p)=\frac{1}{|N_k(p)|}\sum_{o\in N_k(p)}\operatorname{reach}_k(p,o),\qquad \operatorname{lrd}_k(p)=\frac{1}{m_k(p)},\qquad \operatorname{LOF}_k(p)=\frac{1}{|N_k(p)|}\sum_{o\in N_k(p)}\frac{\operatorname{lrd}_k(o)}{\operatorname{lrd}_k(p)}.

Here assume every density used in the ratio is finite and positive. Local reachability density has inverse-distance units; it is not a normalized probability density. LOF is dimensionless. A value above one means the neighbors’ average density is higher, not that every neighbor is denser. Its interpretation is relative to this dataset, metric and kk.

For the record at 60, the neighbors are 22 and 24. Their radii are 2 and 4; the actual distances 38 and 36 dominate. The average reach is 37, so its density is 1/37. The two neighbors have densities 1/4 and 1/3. Thus its score is 37 × (1/4 + 1/3) / 2 = 259/24. This traces every ingredient of the large score.

Two useful checks follow directly from the ratio average. First, it cannot lie outside its component ratios:

min⁡o∈Nk(p)lrd⁡k(o)lrd⁡k(p)≤LOF⁡k(p)≤max⁡o∈Nk(p)lrd⁡k(o)lrd⁡k(p).\min_{o\in N_k(p)}\frac{\operatorname{lrd}_k(o)}{\operatorname{lrd}_k(p)} \le \operatorname{LOF}_k(p)\le \max_{o\in N_k(p)}\frac{\operatorname{lrd}_k(o)}{\operatorname{lrd}_k(p)}.

Second, in this scalar model a common change of units and origin preserves LOF. For x′=ax+bx'=ax+b with a≠0a\ne0, all distances, radii and mean reaches multiply by ∣a∣|a|, the neighborhoods stay the same, and:

lrd⁡k′(p)=lrd⁡k(p)∣a∣,LOF⁡k′(p)=LOF⁡k(p).\operatorname{lrd}'_k(p)=\frac{\operatorname{lrd}_k(p)}{|a|},\qquad \operatorname{LOF}'_k(p)=\operatorname{LOF}_k(p).

Changing different features by different factors in a multidimensional model need not preserve neighborhoods. A unit-invariant scalar example does not justify ignoring feature scaling in general.

A complete, inspectable training calculation

The following Python 3.10+ program uses only the standard library. It accepts a list or tuple of at least two int or Fraction coordinates and rejects booleans, floats and invalid kk. Record identity is the input index; identical coordinates are kept as separate records. Every calculation is rational and exact.

The returned report includes radii, neighbor indices in input order, aligned reachability distances, average reaches, densities, scores and status. There is no binary threshold or new-query method. Adding records means fitting a different dataset.

If an average reach is zero, its reciprocal would be infinite. The report uses None for that density. A score is also None when its own density or any required neighbor density is nonfinite: zero-own-reach takes precedence over zero-neighbor-reach. This is an explicit finite-density calculation policy, not extended arithmetic with infinities. In particular, a missing score is neither zero nor a declaration that the record is ordinary. The original paper flags the duplicate issue after Definition 6 and excludes it from its subsequent analysis. Duplicate qualification

from fractions import Fraction as F


def fit_lof(values, k):
    """Training LOF, including every tie at the kth-neighbor radius."""
    if not isinstance(values, (tuple, list)) or len(values) < 2:
        raise ValueError('values must be a list/tuple of at least two records')
    if any(type(x) not in (int, F) for x in values):
        raise ValueError('coordinates must be int or Fraction, not bool/float')
    n = len(values)
    if type(k) is not int or not 1 <= k < n:
        raise ValueError('k must be an integer with 1 <= k < n')
    xs = tuple(F(x) for x in values)
    distances = tuple(tuple(abs(x - y) for y in xs) for x in xs)
    radius = tuple(sorted(distances[i][j] for j in range(n) if j != i)[k - 1]
                   for i in range(n))
    neighbors = tuple(tuple(j for j in range(n)
                            if j != i and distances[i][j] <= radius[i])
                      for i in range(n))
    reach = tuple(tuple(max(radius[j], distances[i][j]) for j in neighbors[i])
                  for i in range(n))
    mean_reach = tuple(sum(row, F(0)) / len(row) for row in reach)
    density = tuple(F(1) / r if r else None for r in mean_reach)
    scores, statuses = [], []
    for i, ns in enumerate(neighbors):
        if density[i] is None:
            scores.append(None)
            statuses.append('zero-own-reach')
        elif any(density[j] is None for j in ns):
            scores.append(None)
            statuses.append('zero-neighbor-reach')
        else:
            scores.append(sum((density[j] for j in ns), F(0))
                          / len(ns) / density[i])
            statuses.append('finite')
    return {'values': xs, 'k': k, 'radius': radius, 'neighbors': neighbors,
            'reach': reach, 'mean_reach': mean_reach, 'density': density,
            'lof': tuple(scores), 'status': tuple(statuses)}


if __name__ == '__main__':
    r = fit_lof((0, 1, 2, 20, 22, 24, 60), 2)
    print('density:', tuple(str(v) for v in r['density']))
    print('LOF:', tuple(str(v) for v in r['lof']))
    print('last neighbors:', r['neighbors'][-1], 'mean reach:', r['mean_reach'][-1])
    print('tie neighbors:', fit_lof((0, 1, -1, 4), 1)['neighbors'][0])
    dup = fit_lof((0, 0, 5), 1)
    print('duplicate statuses:', dup['status'])
    print('duplicate LOF:', dup['lof'])
    before = fit_lof((0, 1, 2, 8), 2)['lof'][3]
    after = fit_lof((0, 1, 2, 8, 9), 2)['lof'][3]
    print('record 8 after refit:', before, '->', after)

Run the file to obtain:

density: ('2/3', '1/2', '2/3', '1/3', '1/4', '1/3', '1/37')
LOF: ('7/8', '4/3', '7/8', '7/8', '4/3', '7/8', '259/24')
last neighbors: (4, 5) mean reach: 37
tie neighbors: (1, 2)
duplicate statuses: ('zero-own-reach', 'zero-own-reach', 'zero-neighbor-reach')
duplicate LOF: (None, None, None)
record 8 after refit: 91/24 -> 8/3

The last line matters operationally. Appending 9 changes the score of the existing record at 8 from 91/24 to 8/3. A reference dataset is part of the calculation. Refitting with new records is different from scoring unseen queries against a frozen reference.

Correctness follows stage by stage: sorting other-record distances obtains the radius at rank kk; the inclusive filter constructs exactly its radius neighborhood; the aligned rows use each neighbor’s radius; the final two reductions implement the displayed averages. The status branches prevent division by a zero average or use of an unsupported infinite density. No approximate neighbor index or rounded tie comparison intervenes.

For nn records, building the distance matrix takes O(n2)O(n^2) rational operations. Sorting each row costs O(n2log⁡(n+1))O(n^2\log(n+1)) comparisons overall; the remaining scans take O(n2)O(n^2). The matrix and worst-case tied neighborhoods require O(n2)O(n^2) storage, including the returned audit arrays. These are arithmetic-operation and stored-number counts, not constant-cost claims about large integer numerators and denominators.

What a high score does and does not establish

Neighborhood scale changes the question. Small kk can emphasize tiny fluctuations or duplicates. Large kk can connect different groups and erase a local comparison. Inspect which records actually enter a neighborhood, and compare several justified scales. The main example deliberately has ordinary-looking group centers above one, so “LOF greater than one means an anomaly” is already false as a semantic rule for this toy story. Without external labels, the story itself supplies no verified anomaly ground truth.

Duplicates need a declared policy. On 0, 0, 5 with k=1k=1, both zeros have zero average reach. The distant record has finite density but depends on those nonfinite neighbor densities, so all three scores are missing under this program’s policy. At k=2k=2, all required average reaches are positive. Raising kk changes the model; it is not a neutral numerical repair. Deduplication can also change the meaning of repeated legitimate events. If a library adds smoothing or resolves ties differently, record that convention before comparing outputs.

Detection and novelty scoring use different information. In scikit-learn’s fixed 1.7 documentation, negative_outlier_factor_ stores the opposite of training LOF: more negative means more isolated. score_samples and predict require novelty=True and are intended for unseen data; applying them back to the training set can differ from ordinary training LOF. Keep the sign and the reference protocol explicit. API conventions

For deployment, investigate high-ranked records with domain evidence, choose a review threshold using the relevant costs and available validation labels, and retain unscorable records separately. Feature selection, transformations and kk should be decided without peeking at the final evaluation labels. If future behavior is the target, use a reference/evaluation split that respects time or shared entities. A compact unusual group, a poor distance metric or a changed operating regime can all mislead a purely geometric score.

Exercises with worked answers

1. Why are there two neighbors when k is one?

Answer: In 0, 1, -1, 4, the radius of the zero record is 1. Both records at distance 1 satisfy the inclusive condition. Its neighborhood contains indices (1, 2); the record itself is excluded. Keeping just one of the tied records would implement a different neighborhood convention.

2. Reconstruct the score of the record at 60.

Answer: Its two neighbors are 22 and 24, with adjusted distances 38 and 36. The mean is 37, giving density 1/37. The neighbors’ mean density is (1/4 + 1/3)/2 = 7/24. Divide by 1/37 to get 259/24. Reversing the density ratio would give 24/259 and reverse the intended comparison.

3. What should None mean on the duplicate example?

Answer: For 0, 0, 5 at k=1, the first two mean reaches are zero, so their densities are outside the finite-density contract. The third density is 1/5, but its score uses the other two densities. It is marked zero-neighbor-reach. All scores are None; none is a verified inlier. At k=2 this particular dataset has finite scores, but it now asks a different neighborhood question.

4. Should converting units or adding a new record preserve the scores?

Answer: Replacing every coordinate by 100x + 1000 preserves all scores: neighborhoods are unchanged and the common density factor cancels. Adding 9 to 0, 1, 2, 8 does not preserve the old score at 8: the executed refit changes it from 91/24 to 8/3. A new dataset and a common change of units are different operations.

Where the method fits

The original LOF paper develops neighborhood-density comparisons and bounds relating scores to nearby reachability scales. Those bounds help explain why a locally uniform region can have scores near one; they do not attach a universal behavioral meaning to a threshold. Its local perspective is useful alongside Isolation Forest, which scores ease of isolation, and one-class SVM, which learns a regularized separating function. LOF paper

DBSCAN constructs density-connected groups and a noise label; LOF can rank records without first constructing those groups. For practical experiments, the fixed scikit-learn API is a useful next step because it exposes neighbor-search choices and separates training detection from novelty scoring. Compare the reference protocol, tie policy, numerical policy and score direction before comparing numerical outputs.

Make a prediction, then check

For record 60, mean reach is 37 and the two neighbor densities are 1/4 and 1/3. What is its LOF?

Choose one answer

Learning objectives

  • Reconstruct inclusive neighbor radii, directed reachability and the correct density-ratio orientation.
  • Explain local scale, unit invariance and why a score is not an anomaly probability.
  • Audit duplicate-point statuses and distinguish refitting from frozen-reference novelty scoring.

Prerequisites & connections

Explore related knowledge →

References

  1. LOF: Identifying Density-Based Local Outliers
    Markus M. Breunig; Hans-Peter Kriegel; Raymond T. Ng; Jörg Sander · 2000
  2. scikit-learn 1.7 LocalOutlierFactor API
    scikit-learn developers · 2025

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Eight tests pass. An independent interval-count reference finds radii without selecting kth sorted record distances, then integrates survival counts across distance/radius breakpoints to derive mean reach without summing pairwise maxima. Directed edge density transport gives the final ratios. Eight small datasets and their selected distinct neighborhood sizes produce 20 comparisons of radius, neighbors, mean reach, density, LOF and status fields, covering all-neighbor and tied cases. Reachability rows are additionally checked by their sums and neighborhood lengths; that author reference does not separately check every reach entry.
  • Checked the seven-record exact scores, direction-sensitive reachability, ratio bounds, duplicate finite-density statuses, two-record LOF equal to one, global positive and negative rescaling, translation, row permutation, dataset-refit score changes and input/report preservation. Nine invalid data forms and seven invalid k values are rejected. All computations are standard-library Fraction arithmetic; bit complexity is qualified.
  • Complete bilingual original text contains identical runnable Python, seven actual stdout lines, four displayed formulas, six stable anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML pass; corresponding mathematics and literal emphasis are checked. Pinned Humanizer prose review completed. All cross-topic routes use existing stable catalogue IDs.
  • Review remains written with AI author checks only. This exact scalar training calculation implements inclusive ties and an explicit finite-density policy, not extended infinity arithmetic, novelty queries or the entire sklearn API. No human review, anomaly ground truth, production benchmark, browser acceptance or whole-site build is claimed.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • LOF: Identifying Density-Based Local Outliers · Actually read the 12-page university PDF: page 1 title/authors and SIGMOD 2000 identification; section 3, physical pages 2–3, for local versus global motivation; definitions 3–5 on physical page 3 for self exclusion, all kth-radius ties and the neighbor-radius maximum; definitions 6–7 on physical page 4 for inverse mean reach, neighbor/own density ratio and the explicit assumption excluding duplicate coordinates; Lemma 1 on page 4 for the two-hop neighborhood and positive reach-scale conditions behind near-one scores. Extracted formula lines 301–314 confirm ratio direction. A web screenshot attempt for page 4 returned Internal Error; no successful visual PDF check is claimed. The official SIGMOD Record page was also opened to confirm title/authors/year; its 7 June 2000 posting date is not presented as the conference day. No source code or figure was copied.
  • scikit-learn 1.7 LocalOutlierFactor API · Actually read fixed 1.7 API rendered 1.7.2: lines 620–625 overview; 679–680 novelty flag and new-data restriction; 690–702 opposite training scores and separate offset; 759–762 and 960–987 query protocol and score direction; 802–806 training fit_predict. Did not assert that the original paper prescribes a universal 1.5 threshold, adopt library examples, run sklearn, or claim tie/numerical parity. GitHub source was opened at its header only; no source implementation reading is claimed.
  • LOF: Identifying Density-Based Local Outliers · Actually read the university-hosted 12-page original PDF: page 1 title/authors and SIGMOD 2000 identification; section 3 pages 2–3 on local isolation; page 3 definitions 3–5 on other-record identity, all kth-distance ties and the neighbor radius in directed reachability; page 4 definitions 6–7 and duplicate exclusion, with extracted formula lines 301–314 confirming neighbor-density divided by own-density. Read Lemma 1 conditions on two-hop membership and positive reach scales, rather than claiming every cluster point scores one. Text review only, no visual scan or experimental reproduction.
  • scikit-learn 1.7 LocalOutlierFactor API · Actually read fixed /1.7 API rendered 1.7.2: novelty setting lines 679–680, training-score sign and separate offset 690–702, predict 960–964 and score_samples 981–987. Confirmed unseen-query restrictions and why training re-query results can differ. Did not adopt a universal original-paper 1.5 cutoff, run sklearn, or claim tie/smoothing parity.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.