DBSCAN (Density-Based Spatial Clustering) › Formula

Michael BrenndoerferUpdated December 18, 202526 min read
Machine Learning from ScratchAll chapters
Part 7 of 9Unsupervised Learning
Chapter 55DBSCAN (Density-Based Spatial Clustering) › Formula
Reading section 2 of 8 · Formula · 26 minSection 2 of 8 · 26 min

Book contents

Section 2 of 8 · 26 min read

DBSCAN (Density-Based Spatial Clustering) › FormulaOne section · Sections in this chapter2 / 8 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Traditional clustering algorithms like k-means operate under a comforting but often false assumption: that clusters are roughly spherical and similar in size. These methods place cluster centers and assign each point to the nearest center, drawing clean circular boundaries around groups of data. But real-world data rarely cooperates with such geometric idealism.

Consider the challenge of identifying neighborhoods in a city. Some neighborhoods wind along riverbanks. Others sprawl across irregular terrain. A few cluster tightly around transit hubs while others stretch along major roads. No amount of circular boundaries will capture these organic shapes. We need a fundamentally different approach.one that asks not "where are the centers?" but rather "where are the crowds?"

This shift in perspective, from centers to density, is the foundational insight behind DBSCAN. Instead of imposing geometric constraints, we let the data reveal its own structure by following the natural concentrations of points.

From City Streets to Mathematical Rigor

Imagine wandering through a sprawling city at night, trying to identify distinct neighborhoods based on where people naturally congregate. You notice some areas buzzing with activity: crowded bars, street performers, food trucks. Others remain quiet and sparsely populated. Traditional approaches might simply draw circles around the busiest intersections and call those "neighborhoods," but this misses something fundamental about how real communities form.

What if, instead of assuming neighborhoods are perfectly circular regions around central points, we asked: "Where do people gather, and how can we follow the natural paths of activity from one lively spot to another?" This density-based perspective allows us to discover neighborhoods of many shapes, including winding streets, irregular blocks, and sprawling districts, by tracing the flow of human activity.

DBSCAN embodies this intuition mathematically. It doesn't impose artificial geometric constraints on clusters. Instead, it asks the data: "Where are the natural gathering places, and how do they connect?" This approach reveals clusters that match reality rather than forcing reality to fit our preconceptions.

The mathematical framework we're about to construct maps this intuitive city-walking metaphor into rigorous, executable definitions. We'll build it systematically through four progressive layers:

LayerQuestion AnsweredMathematical Tool
ProximityWhich points are close to each other?The ε-neighborhood
DensityWhich regions are crowded enough to matter?Core point criterion
ReachabilityHow do dense regions connect?Density-reachability chains
ConnectivityWhich points belong to the same cluster?Density-connectivity

This progression mirrors how we naturally understand neighborhoods: we start with proximity, then consider density and connection before deciding which points belong together.

The Epsilon-Neighborhood: Defining "Nearby"

Every clustering algorithm must answer a fundamental question: how do we determine which points are "close enough" to potentially belong together? In our city exploration metaphor, this is equivalent to deciding how far you need to walk to consider two locations part of the same neighborhood. The challenge is that "close" means different things in different contexts: a block in Manhattan feels very different from a block in rural Kansas.

DBSCAN's solution is elegantly simple: draw a circle around each point with a fixed radius called eps (epsilon), and consider all points within that circle as "neighbors." This creates a consistent, scale-invariant definition of proximity that works across different datasets and dimensions.

Why a Circle?

The circular neighborhood captures our intuitive understanding that proximity should be symmetric: if point A is close to point B, then point B should automatically be close to point A. The circle also creates a smooth, continuous definition of closeness that doesn't introduce artificial boundaries or corners. In our city metaphor, it's like asking "who lives within walking distance?" rather than "who lives within these rigid geometric boundaries?"

For any point pp in our dataset DD, we define its epsilon-neighborhood as the set of all points within distance eps:

Neps(p)={q∈D:d(p,q)≤eps}N_{eps}(p) = \{q \in D : d(p,q) \leq eps\}

Let's unpack each component of this definition:

  • Neps(p)N_{eps}(p) is the neighborhood of point pp with radius eps.essentially pp's "personal space" in the data. The subscript reminds us that this neighborhood depends on our choice of eps.
  • DD is our complete dataset of points, the universe from which we're selecting neighbors.
  • q∈Dq \in D represents any candidate point we're testing for membership. The notation means "for each point qq in the dataset DD."
  • d(p,q)≤epsd(p,q) \leq eps is our proximity test: the distance between pp and qq must not exceed eps.
  • {...}\{...\} denotes set notation.we're collecting all points that pass the proximity test into a single set.

The distance function d(p,q)d(p,q) measures how far apart two points are. While DBSCAN works with any valid distance metric, the most common choice is Euclidean distance:

d(p,q)=(x2−x1)2+(y2−y1)2d(p,q) = \sqrt{(x_2-x_1)^2 + (y_2-y_1)^2}

This is simply the Pythagorean theorem applied to two-dimensional coordinates: the straight-line distance between points (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2). In higher dimensions, we sum the squared differences across all coordinates before taking the square root.

The eps parameter becomes our first design choice. A larger eps creates bigger neighborhoods, making it easier for points to connect and form larger clusters. A smaller eps creates more selective neighborhoods, leading to tighter, more distinct clusters. This parameter fundamentally controls how "generous" our definition of "nearby" will be in the clustering process.

Here's an important distinction between proximity and clustering: just because two points are neighbors doesn't mean they belong to the same cluster. You could stand next to someone on a crowded subway platform during rush hour, but you're not part of the same social group or community. We need a mechanism to distinguish between coincidental proximity and community membership.

This distinction leads us to the core innovation of DBSCAN: density.

Core Points: Identifying Dense Regions

Proximity alone isn't enough. Now we face a second fundamental question: what distinguishes a "crowded area" from "just a few random points that happen to be nearby"? This distinction matters because not every group of nearby points deserves to be called a cluster.

Let's return to our city metaphor. Imagine walking through the city at night and passing through different areas:

  • A quiet street corner: Just you and one other person waiting for a bus. This isn't a neighborhood gathering; it's just coincidental proximity.
  • A busy restaurant district: Dozens of people at outdoor tables, street performers, pedestrians moving between venues. This feels like a vibrant community hub where activity naturally concentrates.

The difference isn't about counting people. It's about density, the concentration of activity in a specific area that creates a social space. The restaurant district has enough people packed together that it becomes a destination in itself. The bus stop? That's just two people who happen to be waiting at the same time.

DBSCAN formalizes this intuition through the concept of a core point: a point that sits at the heart of a sufficiently dense region. Core points become the anchor points around which clusters form, much like popular restaurants or bars that draw crowds and ultimately define neighborhood boundaries.

Core Point

A core point is a data point that has at least min_samples neighbors (including itself) within its eps-neighborhood. Core points form the "backbone" of clusters.the dense regions from which cluster membership propagates outward.

The "sufficiently dense" criterion is controlled by our second parameter, min_samples. A point becomes a core point if it has at least min_samples neighbors (including itself) within its eps-neighborhood. Think of min_samples as our "crowded enough" threshold, the minimum population needed before we consider an area a social hub rather than random coincidence.

The mathematical definition captures this with elegant simplicity:

∣Neps(p)∣≥min_samples|N_{eps}(p)| \geq min\_samples

This inequality asks a single, decisive question: "Does point pp have enough neighbors to be considered part of a dense region?" Let's break down each term:

  • ∣Neps(p)∣|N_{eps}(p)| is the cardinality (count) of the neighborhood. The vertical bars denote "size of," so this gives us the total number of points within eps distance of pp, including pp itself. If pp has three neighbors plus itself, this equals 4.
  • min_samplesmin\_samples is our density threshold parameter.the minimum population required.
  • ≥\geq is the inequality test. If the neighborhood size meets or exceeds our threshold, pp qualifies as a core point.

This threshold prevents any two nearby points from forming a cluster and creating meaningless micro-communities everywhere. With min_samples, we ensure that only dense regions can spawn clusters. This leads to a three-way classification:

Point TypeCriterionRole in Clustering
Core point∥Neps(p)∥≥min_samples\|N_{eps}(p)\| \geq min\_samplesForms the dense backbone of clusters
Border pointHas fewer than min_samples neighbors but lies within a core point's neighborhoodBelongs to a cluster but can't expand it
Noise pointToo few neighbors AND not reachable from any core pointDoesn't belong to any cluster

The interplay of parameters. The eps and min_samples parameters work together like dance partners.changing one affects what the other can accomplish:

ScenarioEffect on Clustering
Large eps, low min_samplesLarger, more inclusive clusters; may merge distinct groups
Large eps, high min_samplesModerate clusters; requires dense regions
Small eps, low min_samplesMany small, tight clusters; sensitive to local structure
Small eps, high min_samplesVery restrictive; most points become noise

Together, these parameters define what we mean by local density: "A region is dense if it contains at least min_samples points within eps distance." This local approach.rather than relying on global statistics.allows DBSCAN to discover clusters even when different regions of the data have different natural densities.

Visualizing Neighborhoods and Core Points

The mathematical definitions become clearer when we see them geometrically. Let's visualize how DBSCAN classifies points based on their neighborhoods:

Out[3]:
Visualization
DBSCAN point classification diagram showing four points with epsilon neighborhoods, identifying core points (blue), border points (orange), and noise points (red) based on neighborhood density.
Geometric illustration of DBSCAN''s fundamental concepts: ε-neighborhoods, core points, border points, and noise. Each point is surrounded by a circle of radius ε (shown as dashed circles). Point A is a core point because it has ≥3 neighbors within its ε-neighborhood (including itself). Point B is also a core point with 4 neighbors. Point C is a border point: it has fewer than 3 neighbors in its own neighborhood, but it lies within the neighborhood of core point A, making it reachable. Point D is classified as noise because it has too few neighbors and isn''t reachable from any core point. This visualization demonstrates how the mathematical conditions |N_ε(p)| ≥ min_samples translate into geometric regions of density.

The dashed circles represent the ε-neighborhood Neps(p)N_{eps}(p) for each point. Core points (blue circles) have neighborhoods containing at least min_samples points, satisfying ∣Neps(p)∣≥min_samples|N_{eps}(p)| \geq min\_samples. Border points (orange square) don't meet this threshold themselves but fall within a core point's neighborhood. Noise points (red X) satisfy neither condition.they're isolated in sparse regions of the data space.

Density-Reachability: Connecting Dense Regions

We now have core points that mark dense regions, but we face the algorithm's most elegant challenge: how do we connect these dense regions into cohesive clusters? Real communities don't exist in isolation.they link together through chains of activity and movement that create larger social networks.

Imagine our city has several vibrant districts, each with its own core of activity. But these districts aren't separate islands; people naturally flow between them, creating pathways that connect different neighborhoods. A coffee shop in one district might draw people from a nearby restaurant in another district. These connections create larger community networks that transcend individual gathering spots.

If we only connected points that are directly within each other's neighborhoods, we'd create isolated pockets.separate islands of density with no way to merge them. But real communities flow and merge. Two distant points might legitimately belong to the same larger neighborhood if they're connected through a chain of busy areas, even if they're not directly adjacent.

Think of following the natural flow of people through a crowded city. You can reach any destination by stepping from one busy area to the next, as long as each step takes you to a sufficiently crowded spot. The path doesn't need to be straight; it can curve around parks, follow winding streets, or zigzag through alleyways. This organic movement, rather than rigid geometric rules, defines the true boundaries of neighborhoods.

DBSCAN formalizes this intuition through density-reachability: the principle that you can reach one point from another by following a chain of core points, where each step stays within someone's eps-neighborhood.

Direct Density-Reachability

A point qq is directly density-reachable from point pp if two conditions hold: (1) qq is within pp's eps-neighborhood, and (2) pp is a core point. This asymmetric relationship forms the building blocks of cluster connectivity.

The mathematical formulation captures both requirements in a single statement:

q is directly density-reachable from p⇔q∈Neps(p)∧∣Neps(p)∣≥min_samplesq \text{ is directly density-reachable from } p \Leftrightarrow q \in N_{eps}(p) \land |N_{eps}(p)| \geq min\_samples

Let's unpack this formula:

  • q∈Neps(p)q \in N_{eps}(p) is the proximity requirement: point qq must lie within eps distance of point pp. This is the "within walking distance" part.
  • ∣Neps(p)∣≥min_samples|N_{eps}(p)| \geq min\_samples is the density anchor requirement: pp must be a core point. You can only "step from" a busy area.
  • ∧\land is the logical AND operator, requiring both conditions to be true simultaneously.
  • ⇔\Leftrightarrow means "if and only if".the relationship holds exactly when both conditions are met.

Why require a core point anchor? Without this restriction, you could "jump" across sparse areas using border points as stepping stones. This would artificially connect separate communities through their outskirts, like claiming two distant suburbs are the same neighborhood just because their borders happen to touch. By requiring steps to originate from dense core regions, we ensure that cluster connections follow real pathways of activity.

From single steps to full paths. Direct density-reachability gives us single steps; we extend this to full paths through density-reachability. A point qq is density-reachable from pp if there exists a chain of points p=p1,p2,…,pn=qp = p_1, p_2, \ldots, p_n = q where each pi+1p_{i+1} is directly density-reachable from pip_i:

p1→p2→⋯→pnp_1 \to p_2 \to \cdots \to p_n

This transitivity is what allows clusters to curve and bend naturally, following the organic contours of the data. A crescent moon-shaped cluster becomes possible because you can walk along its curved edge, stepping from one core point to the next. Traditional clustering would try to fit a circle or sphere around such data; DBSCAN traces the winding path that defines the true boundary.

Density-Connectivity: When Points Belong Together

Density-reachability gives us a powerful way to trace paths through dense regions, but it creates an awkward asymmetry. Point A might be reachable from point B, but B might not be reachable from A (if B isn't a core point). For deciding who belongs to which neighborhood, we need a relationship that works both ways.a symmetric definition of belonging.

Consider the problem: if we're building a neighborhood directory, the relationship "lives in the same neighborhood as" should be symmetric by nature. If I live in your neighborhood, then you must live in mine. One-directional relationships create confusion and arbitrary distinctions.

The solution is elegant: two points belong to the same cluster if they share a common anchor point.a "neighborhood center" from which both can be reached through density paths. This creates a symmetric relationship based on shared membership in the same community network, regardless of which point you start from.

Density-Connectivity

Two points pp and qq are density-connected if there exists some core point oo from which both pp and qq are density-reachable. This symmetric relationship defines cluster membership: all points that are density-connected belong to the same cluster.

The mathematical formulation is:

p and q are density-connected⇔∃o:p and q are density-reachable from op \text{ and } q \text{ are density-connected} \Leftrightarrow \exists o : p \text{ and } q \text{ are density-reachable from } o

The expression has three components:

  • ∃o\exists o means "there exists some point oo" that is their common anchor. This is the existential quantifier.we only need to find one such anchor point for the relationship to hold.
  • pp and qq are density-reachable from oo means both points can be reached from oo through chains of directly density-reachable steps.
  • ⇔\Leftrightarrow indicates equivalence: the points are density-connected if and only if such an anchor exists.

This works because cluster membership is based on connectivity through dense regions. Points don't need to be directly connected to each other; they just need to be part of the same network of activity flowing from a common core. The symmetry follows naturally: if both points trace back to the same origin, neither is "more connected" than the other.

Think of each cluster as a tree growing from an anchor point (the trunk). All leaves and branches belong to the same tree because they all connect back to the same trunk, regardless of which leaf you start from. Two leaves on different trees aren't connected, even if those trees grow close together.

The following table summarizes the mathematical relationships we've constructed:

RelationshipDefinitionSymmetric?Purpose
NeighborhoodPoints within eps distanceYesDefine "nearby"
Core pointHas ≥ min_samples neighborsN/AIdentify dense regions
Direct density-reachableIn neighborhood of core pointNoSingle-step connections
Density-reachableChain of direct connectionsNoMulti-step paths
Density-connectedShare common anchorYesCluster membership

Visualizing Density-Reachability and Connectivity

To understand how DBSCAN forms clusters through density-reachability chains, let's visualize the process:

Out[4]:
Visualization
DBSCAN cluster formation diagram with core points P1-P3 forming a chain, border points Q and R connected through density-reachability, showing how elongated clusters emerge from overlapping neighborhoods.
Illustration of density-reachability chains and density-connectivity in DBSCAN. The diagram shows how clusters form through overlapping ε-neighborhoods (dashed circles). Points P₁, P₂, and P₃ are core points (blue circles) that form a chain where each is directly density-reachable from the previous one. Point Q is a border point (orange square) that is directly density-reachable from P₃ but is not itself a core point. Point R is another border point reachable from P₁. The green arrows show direct density-reachability relationships. Critically, points Q and R are density-connected because both are density-reachable from the core point P₂, even though they are not directly reachable from each other. This transitive relationship explains how DBSCAN can form elongated, non-spherical clusters by 'walking' through chains of overlapping dense neighborhoods.

The green arrows show direct density-reachability: point qq is directly density-reachable from core point pp if q∈Neps(p)q \in N_{eps}(p) and ∣Neps(p)∣≥min_samples|N_{eps}(p)| \geq min\_samples. The chain P₁ → P₂ → P₃ shows how core points can be mutually reachable, creating a "path" through dense regions.

The purple dashed line illustrates density-connectivity: points Q and R are density-connected because both are density-reachable from P₂ (Q through P₃, R through P₁). This transitive relationship is what allows DBSCAN to form elongated clusters. Points don't need to be directly reachable from each other; they just need a common anchor from which both are reachable. This mechanism enables DBSCAN to discover non-convex geometries such as moon shapes and spirals.

The Complete Cluster Definition

We now have all the pieces of our neighborhood discovery system:

  1. Proximity circles that define local neighborhoods
  2. Density thresholds that identify crowded areas
  3. Reachability chains that connect dense regions
  4. Connectivity relationships that ensure symmetric belonging

The final step is defining what makes a valid cluster.a complete neighborhood that deserves its own distinct identity. A cluster CC in DBSCAN must satisfy two essential properties:

Property 1: Maximality. If a point belongs to the cluster, then every point reachable from it through dense pathways must also belong:

∀p,q:p∈C∧q is density-reachable from p⇒q∈C\forall p, q : p \in C \land q \text{ is density-reachable from } p \Rightarrow q \in C

Let's parse this carefully:

  • ∀p,q\forall p, q means "for all points pp and qq".we're making a universal claim about every pair of points.
  • p∈Cp \in C means point pp is a member of cluster CC.
  • ∧\land is the logical AND: we're considering cases where pp is in CC AND qq is reachable from pp.
  • ⇒\Rightarrow is logical implication: "if... then..." In this case, if pp is in the cluster and qq is reachable from pp, then qq must also be in the cluster.

This property provides the completeness guarantee: a neighborhood can't have "missing members" who should logically be included based on density connections.

Property 2: Connectivity. Every pair of points in the cluster must be linked through the same dense network:

∀p,q∈C:p and q are density-connected\forall p, q \in C : p \text{ and } q \text{ are density-connected}

This says: for every pair of points both in cluster CC, those points must be density-connected (sharing some common anchor). This provides the unity principle: all members share a common origin in the dense activity network.

The Balance of Properties

Maximality prevents incomplete neighborhoods (ensuring we don't leave out points that should belong), while connectivity prevents artificial mergers (ensuring we don't combine communities that should remain separate). Together, these properties ensure each cluster is fully populated and unified.

What about the leftover points? They become noise.points that fall outside all dense networks, living in the sparse spaces between communities. This honest treatment of outliers, rather than forcing them into artificial clusters, is one of DBSCAN's greatest strengths.

Summary: The Complete Mathematical Framework

We've constructed a system for discovering clusters of any shape by following the flow of density through the data:

ConceptFormulaWhat It Does
ε-NeighborhoodNeps(p)={q:d(p,q)≤eps}N_{eps}(p) = \{q : d(p,q) \leq eps\}Defines "nearby" for each point
Core Point∥Neps(p)∥≥min_samples\|N_{eps}(p)\| \geq min\_samplesIdentifies dense regions
Direct Density-Reachableq∈Neps(p)∧pq \in N_{eps}(p) \land p is coreSingle-step connections from dense areas
Density-ReachableChain: p1→p2→⋯→qp_1 \to p_2 \to \cdots \to qMulti-step paths through core points
Density-Connected∃o:p,q\exists o : p, q reachable from ooSymmetric cluster membership
ClusterMaximal + Connected setComplete, unified neighborhood

Each definition builds on the previous ones, transforming our intuitive city-walking metaphor into rigorous, executable mathematics.

From Mathematics to Algorithm

Our mathematical framework is elegant and complete, but mathematical beauty alone doesn't find clusters in data. Now we must translate these concepts into a systematic procedure. The DBSCAN algorithm maps our density-based intuition into concrete, executable steps.

The algorithm operates in three coordinated phases:

Phase 1: Preparation. Before exploring, we set up our data structures:

  • Initialize all points as "unvisited"
  • Create an empty cluster label array (all points start unlabeled)
  • Set cluster counter to 0
  • Define parameters: eps (neighborhood radius) and min_samples (density threshold)

Phase 2: Systematic Survey. For every unvisited point pp in the dataset, we ask: "Could this be the heart of a new neighborhood?"

For each unvisited point p: 1. Mark p as visited 2. Find N_eps(p) = all points within eps distance of p 3. If |N_eps(p)| < min_samples: Mark p as NOISE (tentatively) 4. Else: Increment cluster counter Expand cluster from p (Phase 3)

The key insight is that noise classification is tentative. A point initially marked as noise might later be absorbed into a cluster if it falls within the eps-neighborhood of a subsequently discovered core point.

Phase 3: Cluster Expansion. When we discover a core point, we expand outward following density-reachability chains:

ExpandCluster(p, neighbors, cluster_id): 1. Add p to cluster cluster_id 2. Create queue Q = neighbors 3. While Q is not empty: a. Remove point q from Q b. If q is unvisited: Mark q as visited Find N_eps(q) If |N_eps(q)| >= min_samples: Add N_eps(q) to Q (q is a core point) c. If q is not yet in any cluster: Add q to cluster cluster_id

This expansion procedure implements our maximality property: we keep growing the cluster until we've absorbed every density-reachable point.

The Ripple Effect

Each core point we discover acts like a seed that sends out explorers to map connected territory. This creates expanding waves of neighborhood discovery. Border points get absorbed but don't propagate the expansion further.

The procedure directly implements our mathematical definitions. By following density-reachability chains, we ensure each cluster is maximally complete (includes all density-reachable points) and cohesive (all members are density-connected).

Computational Complexity

The basic DBSCAN algorithm has time complexity O(n2)O(n^2) in the worst case, where nn is the number of data points.this occurs when every point needs to be compared with every other point. However, with spatial indexing structures like R-trees or k-d trees, the complexity can be reduced to O(nlog⁡n)O(n \log n) for low-dimensional data.

DBSCAN requires O(n)O(n) space to store the dataset and maintain neighborhood information. The algorithm doesn't need to store distance matrices or other quadratic space structures, making it memory-efficient compared to some other clustering algorithms.