Find dense clusters and noise points with DBSCAN

DBSCAN finds clusters of any shape and labels sparse points as noise, without being told how many clusters exist. It is a common first pass for deduplicating embeddings or finding outliers in logs.

Write dbscan(X, eps, min_samples). X has shape (n, d). Definitions:
- The neighbours of point p are all points q with Euclidean distance(p, q) <= eps, including p itself.
- p is a core point if it has at least min_samples neighbours.

Algorithm (follow it exactly, so ties are deterministic):
1. All labels start at -1. Next cluster id is 0.
2. For i = 0, 1, ..., n - 1: skip i if it already has a label or is not core. Otherwise give i the next cluster id and expand: use a first-in first-out queue starting with i. Pop p; if p is core, visit its neighbours in increasing index order and give every still unlabelled one the current id and push it. Non-core points get a label but are never expanded.
3. Points still at -1 are noise.

Return the list of n int labels.

Signaturedef dbscan(X, eps, min_samples)

Example

X = [[0], [1], [2], [10]], eps = 1.0, min_samples = 2 gives [0, 0, 0, -1].

Understand the idea

DBSCAN finds clusters as dense regions and labels isolated points as noise, without being told how many clusters exist. A point's neighbours are all points within eps, including itself. A core point has at least min_samples neighbours. Clusters grow only through core points; a border point near a core point joins the cluster but does not extend it. Like a rumour that spreads only through people with many close friends. Worked example: X = [[0], [0.5], [1.5], [5]], eps = 1, min_samples = 3. Neighbours: point 0 has {0, 1}, 2 points, not core. Point 1 has {0, 1, 2} (1.5 - 0.5 = 1.0 counts), core. Point 2 has {1, 2}, not core. Point 3 has {3}. Scan i = 0: not core, skip. i = 1: core, new cluster 0; queue expands point 1 and labels 0 and 2 with 0; they are border points, so they are not expanded. Point 3 stays -1. Result [0, 0, 0, -1]. Rule: follow the scan order and FIFO expansion exactly; only core points expand. It is used to deduplicate embeddings and flag outliers.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampledbscan([[0], [1], [2], [10]], 1.0, 2)
  • Sample 2: two blobs and noisedbscan(_X, 0.8, 3)