AI Wiki中文/EN

DBSCAN: why a border point cannot bridge two crowds

DBSCAN

Compute core components, preserve shared border memberships and see how one new record can change a density partition.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two crowds and one person between them

Imagine two groups of people standing a few steps apart. One person stands between the groups, close enough to greet someone on either side. Should that person turn the two groups into one? A rule that joins every nearby pair says yes. DBSCAN asks an extra question: is there enough company around each point to let a connection continue through it?

That distinction is useful when groups bend around empty space, and when some records belong to no group at the chosen scale. Unlike k-means, the method does not start by specifying a number of centers. It starts with a distance scale and a required local count. The count and scale express a modeling decision; they do not discover what the word “group” means for your application.

Ester, Kriegel, Sander and Xu introduced DBSCAN in their 1996 KDD paper on spatial databases. Its construction distinguishes core points, border points and noise, and permits expansion only from core points. Original paper, §§3–4

We will build a ten-record example in which the middle record touches both crowds, yet cannot merge them. Then we will change one parameter and watch that conclusion reverse.

A connection needs a core point to continue

Let x_i be a record in a dataset of n records, d a chosen distance, epsilon a nonnegative radius, and m a positive integer. Define a closed neighborhood and the set of core indices:

Nε(i)={j:d(xi,xj)≤ε},C={i:∣Nε(i)∣≥m}.N_\varepsilon(i)=\{j:d(x_i,x_j)\leq\varepsilon\},\qquad C=\{i:|N_\varepsilon(i)|\geq m\}.

The record itself counts. Two rows with identical coordinates also remain two records; silently removing duplicates changes the local count. The fixed scikit-learn API explicitly includes the point itself in min_samples. Our exact teaching program additionally accepts radius zero, so that this duplicate case can be inspected directly. DBSCAN API: neighborhood and count

Direct density reachability points from an expanding core record to one of its neighbors:

i⟶j⟺i∈C and j∈Nε(i).i\longrightarrow j\quad\Longleftrightarrow\quad i\in C\ \text{and}\ j\in N_\varepsilon(i).

A chain of these arrows defines density reachability. Its direction matters. A core point can reach a neighboring border point, but a non-core border point cannot continue the chain. Density connectivity means that some record can reach both endpoints. The original definitions and its expansion algorithm make this core condition explicit. Original paper, definitions 2–4 and ExpandCluster

Turn the definition into a graph calculation

Join two core indices when their distance is at most epsilon. Call the connected components of this undirected graph C_0, C_1, and so on. For every non-core index i, record the core components it touches:

B(i)={k:Nε(i)∩Ck≠∅},i∉C.B(i)=\{k:N_\varepsilon(i)\cap C_k\ne\varnothing\},\qquad i\notin C.

If B(i) is empty, i is noise. If it has one member, i is an unambiguous border point. If it has several members, the point lies on more than one cluster’s border. It does not join their core components.

Why does this graph construction work? Along a chain ending at a core point, every intermediate point is also core, because it must emit the next arrow. Thus two core points are mutually reachable exactly when they share a core component. A non-core endpoint can only be the final step, so its possible cluster memberships are precisely B(i). This gives us a direct correctness argument for the program below.

Hard cluster labels require a convention at a shared border. We number core components by their smallest input index and choose the first component in B(i). We also return the whole set of choices. The library guide documents how encounter order can change border assignments even though core membership is unchanged. Fixed guide: ordering

Numeric cluster names have no intrinsic meaning. After a row permutation, compare the actual sets of original core indices, not whether a group is still named zero. A shared border point can genuinely move from one hard-assigned set to another.

Keep the ambiguous membership instead of hiding it

Save this complete Python 3 program and run it without additional packages. It accepts a list or tuple of two-dimensional integer or Fraction coordinates, a nonnegative rational radius and a positive integer min_samples. An empty dataset returns an empty report; floats, booleans, malformed rows and invalid parameters raise ValueError. Input rows are copied rather than modified.

neighbors includes each record itself. core_components contains only core records. border and noise list non-core indices, while memberships retains each record’s possible component identifiers. Labels use −1 for noise. The core graph traversal is intentionally separate from border attachment.

from fractions import Fraction as F


def number(value):
    if type(value) is not int and not isinstance(value,F):
        raise ValueError('use integers or Fraction values')
    return F(value)


def dbscan(points, radius, min_samples):
    if type(points) not in (list,tuple):
        raise ValueError('expected a list or tuple of points')
    if any(type(p) not in (list,tuple) or len(p)!=2 for p in points):
        raise ValueError('each point must have two coordinates')
    X=tuple(tuple(number(v) for v in p) for p in points)
    radius=number(radius)
    if radius<0 or type(min_samples) is not int or min_samples<1:
        raise ValueError('nonnegative radius and positive integer min_samples required')
    n=len(X);r2=radius*radius
    neighbors=tuple(tuple(j for j,q in enumerate(X)
                    if sum((a-b)**2 for a,b in zip(p,q))<=r2) for p in X)
    core=tuple(len(row)>=min_samples for row in neighbors)
    labels=[-1]*n;components=[]
    for i in range(n):
        if not core[i] or labels[i]!=-1:continue
        label=len(components);labels[i]=label;stack=[i];members=[]
        while stack:
            v=stack.pop();members.append(v)
            for u in neighbors[v]:
                if core[u] and labels[u]==-1:
                    labels[u]=label;stack.append(u)
        components.append(tuple(sorted(members)))
    choices=[];border=[];noise=[]
    for i in range(n):
        if core[i]:choices.append((labels[i],));continue
        adjacent=tuple(sorted({labels[j] for j in neighbors[i] if core[j]}))
        choices.append(adjacent)
        if adjacent:
            labels[i]=adjacent[0];border.append(i)
        else:noise.append(i)
    return {'labels':tuple(labels),'core':tuple(i for i in range(n) if core[i]),
            'core_components':tuple(components),'border':tuple(border),'noise':tuple(noise),
            'memberships':tuple(choices),'neighbors':neighbors}


if __name__=='__main__':
    points=((-1,0),(F(-3,2),0),(F(-3,2),F(1,4)),(F(-3,2),F(-1,4)),
            (1,0),(F(3,2),0),(F(3,2),F(1,4)),(F(3,2),F(-1,4)),(0,0),(4,4))
    report=dbscan(points,1,4)
    print('core components:',report['core_components'])
    print('labels:',report['labels'])
    print('border / noise:',report['border'],report['noise'])
    print('central memberships:',report['memberships'][8])
    print('min_samples=3:',dbscan(points,1,3)['core_components'])
    print('one extra central record:',dbscan(points+((0,0),),1,4)['core_components'])
    print('duplicates at radius zero:',dbscan(((2,2),)*4,0,4)['core'])

For nonempty, fixed two-dimensional data, the program compares every pair and stores all neighborhoods. It therefore uses O(n²) distance operations and O(n²) worst-case storage. Empty input takes constant time and space. Exact fraction arithmetic has an additional bit-length cost. Sorting members does not exceed this quadratic bound. Spatial indexes can help with sparse, suitable neighborhoods, but there is no unconditional O(n log n) promise here. The fixed API also documents quadratic worst-case memory for its bulk-neighborhood implementation. DBSCAN API: memory notes

Make the middle point explain the result

The first four records form a left crowd and the next four a right crowd. Record 8 is at the origin; record 9 is far away. With radius 1 and minimum count 4, the program prints:

core components: ((0, 1, 2, 3), (4, 5, 6, 7))
labels: (0, 0, 0, 0, 1, 1, 1, 1, 0, -1)
border / noise: (8,) (9,)
central memberships: (0, 1)
min_samples=3: ((0, 1, 2, 3, 4, 5, 6, 7, 8),)
one extra central record: ((0, 1, 2, 3, 4, 5, 6, 7, 8, 10),)
duplicates at radius zero: (0, 1, 2, 3)

The central record’s neighborhood is exactly indices 0, 4 and 8. Three records are insufficient for it to be core. It touches core components zero and one, so it receives label zero by our explicit ordering rule while retaining both choices. The distant record has no neighboring core point and receives −1.

Lower the minimum count to three. The central record now becomes core, so it provides a valid bridge between the two crowds. Alternatively, keep the minimum at four and add another record at the origin. Both central records become core, again joining the crowds. A single new row can change the partition of old rows.

This is why attaching a new query to a frozen group and rerunning DBSCAN with that query included are different operations. Our program provides the latter only. A product that needs stable assignment of future records must specify that extra prediction rule and evaluate it separately.

As another check, uniformly rescale all coordinates and the radius by the same positive factor a. Neighborhoods remain identical because

∥axi−axj∥22≤(aε)2⟺∥xi−xj∥22≤ε2,a>0.\|a x_i-a x_j\|_2^2\leq(a\varepsilon)^2\quad\Longleftrightarrow\quad\|x_i-x_j\|_2^2\leq\varepsilon^2,\qquad a>0.

Changing just one coordinate’s unit is different: that changes the relative contributions to Euclidean distance. Record the feature scaling with the clustering parameters so another person can reproduce the neighborhood decisions.

Choose the density question before choosing its parameters

One global radius can be too small for a sparse group and too large for a dense one. In the example, a parameter change deliberately alters which bridge is allowed. In a real application, inspect that change against the purpose of grouping: separating delivery zones, identifying repeated sensor patterns and grouping document embeddings need not reward the same partition.

Noise is a result under a distance and two parameters, not a finding that a record is fraudulent, faulty or unimportant. Likewise, a cluster is not automatically a class with a useful name. Begin with unsupervised learning if you need to distinguish a fitted structure from an externally meaningful interpretation.

For a useful experiment log, save preprocessing, distance, parameters, row ordering, cluster sizes, noise fraction and the count of shared border points. Inspect nearby parameter settings and several actual records from each group. Where external labels exist, reserve them for the evaluation design you intended; where they do not, report stability and domain checks rather than calling a visually pleasing plot “accuracy.”

Four checks before trusting a cluster map

1. Can a chain of non-core points connect two core components?

Answer: No. The first non-core point stops density expansion. Connecting every edge of the full neighborhood graph would implement a different rule and wrongly merge the two crowds in our example.

2. What happens to four identical records at radius zero and minimum count four?

Answer: Every record sees all four rows, including itself. All are core and form one component. Replacing the four rows by one unweighted row makes it noise under the same minimum count. Duplicate handling is part of the model.

3. Reorder the example so the right crowd comes first. What can change?

Answer: After mapping indices back, the two core sets remain the same. Their numeric labels switch, and the shared central border is assigned to the right crowd under the first-component convention. The distant record stays noise.

4. Does radius one mean every pair inside a cluster is at most one unit apart?

Answer: No. It bounds a local neighborhood step. A long chain of core points can span a much larger distance. For three collinear records at 0, 1 and 2 with radius one and minimum count two, all are core and connected, although the endpoints are two units apart.

From a fixed radius to a density hierarchy

The next question is how to describe groups across several distance scales. Hierarchical clustering builds a nested sequence; HDBSCAN uses a density-based hierarchy and a cluster-selection rule. A hierarchy gives more structure to inspect, but still requires decisions about what should count as a useful cluster.

Make a prediction, then check

A non-core point touches two different core components. Must it merge them?

Choose one answer

Learning objectives

  • Translate density reachability into core components and border memberships.
  • Run an exact example where a border cannot bridge clusters but an added record can.
  • Separate local radius, cluster extent and rules for future records.

Prerequisites & connections

Explore related knowledge →

References

  1. A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise
    Martin Ester; Hans-Peter Kriegel; Jörg Sander; Xiaowei Xu · 1996
  2. scikit-learn 1.7 — DBSCAN API
    scikit-learn developers
  3. scikit-learn 1.7 — Clustering, DBSCAN section
    scikit-learn developers

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.

  • Six tests pass. Independent Gram-polarized distances and Boolean transitive closure of directed density reachability match every report field in 24 fits across eight datasets and three parameter pairs; no core-graph traversal in the reference.
  • Verified central ambiguity, parameter and added-record bridges, permutation with mapped core sets and changed border, and two exact rational similarity transforms. Tested 3–4–5 radius boundary, duplicates, empty data, invalid tails and input preservation.
  • Core sets are monotone across five increasing radii and five decreasing minimum counts. Main example and seven stdout lines execute as printed. No numeric label invariance assumed under permutation.
  • Bilingual articles share four displays, six anchors, four answered exercises and identical full Python. Strict MDX/KaTeX and actual React HTML pass with the shared fatal guard. Concrete original prose follows established Humanizer editing; access details stay in metadata. Written pending independent peer review.
  • All six final author tests pass. Independently identified core components through the exact nullspace of the core graph Laplacian: equality of basis-coordinate fingerprints, with no graph traversal or Boolean reachability closure. All seven return fields agree on 18 reports and 62 Laplacian rows, including two shared-border cases, added-record and lowered-count bridges, mapped row reversal, duplicates, zero radius, empty input, m>n and a 3–4–5 boundary.
  • Fully reread both articles, code, four formulas, four answers and metadata. Verified closed neighborhoods, self inclusion, unweighted record counts, core-only expansion, all possible border memberships and the explicit minimum-component hard-label convention. Non-core points do not become graph bridges. Strict MDX/KaTeX/React HTML independently passes four corresponding display formulas, six standard anchors and four answers, including actual MathML and emphasis checks.
  • 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:

  • A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise · Actually read PDF text: title and 1996 KDD footer p.1; §3 definitions 1–4 lines 145–189, lemmas lines 218–243; §4 global parameters lines 244–264; ExpandCluster lines 298–328, indexed complexity assumptions 329–340, shared border 348–352, parameter heuristics opening 353–375. Definition OCR loses an equality bar; explicit pseudocode result.size >= MinPts and seeds.size < MinPts establish the adopted convention. No complete-paper/figure inspection, automatic parameter guarantee or benchmark replication.
  • scikit-learn 1.7 — DBSCAN API · Actually read fixed /1.7/ page displaying 1.7.2: lines 623–637, quadratic memory, local radius and self-inclusive min_samples; 679–680 noise label; 702–707 bulk neighborhoods and duplicate weighting. Teaching integer/Fraction, empty-input and radius-zero contracts are explicitly our own, not a drop-in API claim.
  • scikit-learn 1.7 — Clustering, DBSCAN section · Actually read fixed guide lines 352–358 for density framing and 367–368 for order, core memberships and first-cluster shared-border assignment. Its informal “other samples” differs from API’s explicit self inclusion; article follows API and original algorithm. No global efficiency or natural-cluster guarantee.
  • A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise · Independently opened the six-page original-paper mirror and read title/authors, §3 definitions 1–4 (lines 145–189), §4 ExpandCluster (298–328), and shared-border/order discussion (348–352). OCR gives > in definition 2, but explicit pseudocode result.size >= MinPts and seeds.size < MinPts support the adopted non-strict threshold. Text extraction only; no figure inspection, benchmark replication or unconditional indexed-time claim.
  • scikit-learn 1.7 — DBSCAN API · Independently read fixed 1.7 API displayed as 1.7.2, lines 623–637, 679–680 and 702–704: self-inclusive count, local radius, noise labels and bulk-neighborhood memory. Empty/radius-zero exact teaching contracts are not presented as the library contract.
  • scikit-learn 1.7 — Clustering, DBSCAN section · Independently read fixed guide lines 352–359 and 367–369: density framing, core connectivity and ambiguous-border assignment. The guide’s informal other-samples wording is not used to override explicit API self inclusion. No general natural-cluster or density interpretation guarantee inferred.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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