Unit 4.6 · about 4 h
157 / 324DBSCAN, agglomerative clustering and cluster validation
Real groups are rarely spheres. Density and merge views find moons and hierarchies that k-means smears, but their knobs decide the answer.
- explain
- measure
You can now
- Explain
DBSCANcore, border and noise labels fromepsandmin_samplesand linkage choices in agglomerative clustering. - Measure
epssensitivity, linkage disagreement and seed and sample stability on one dataset. - State what silhouette and Rand indices can and cannot justify for non-convex clusters.
Covers
- DBSCAN and agglomerative clustering geometry
- Cluster stability, usefulness and internal-metric limits
Study, in this order
2 steps
- `DBSCAN` contrast and agglomerative exampleHands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learning
Book Chapter 8: DBSCAN and Other Clustering Algorithms (printed pp. 265-269). Notebook 08 cells:
DBSCAN:make_moons(1000, noise=0.05)ateps=0.05(7 clusters, many points labeled-1) versuseps=0.2(two clusters, no noise),core_sample_indices_,components_, and KNN on the cores with a 0.2 distance cutoff to label new points; Other Clustering Algorithms:AgglomerativeClusteringwith complete linkage on \(\left[\begin{smallmatrix}0&2&5&8.5\end{smallmatrix}\right]\)Depth · Skim the Spectral Clustering bonus code; keep the
epscontrast and the linkage example. - Density, linkage and metric limitsscikit-learn - decomposition, clustering and outlier detection
2.3.7
DBSCAN: dense definition fromepsandmin_samples, core, border and outlier rules, the eps-must-be-tuned warning with all-noise and merged-cluster failures; 2.3.6 hierarchical clustering: Ward, complete, average and single linkage with the uneven-size guidance; 2.3.11 metrics: silhouette formula with its convex-cluster bias and the adjusted Rand index correcting for chance
Focus on
epssets the neighborhood radius andmin_samplesthe density floor. On the notebook moons,eps=0.05breaks the two moons into 7 clusters and labels 7.7 percent as noise, while 0.2 finds the two moons with no noise; always sweepeps.- Linkage defines merge distance: single follows chains, complete compacts, Ward prefers equal-variance merges. On \(\left[\begin{smallmatrix}0&2&5&8.5\end{smallmatrix}\right]\) single splits off 8.5 while complete pairs neighbors.
DBSCANlabels new points only by extra machinery: the notebook trains KNN on cores. The clusterer itself has nopredict.- Silhouette rewards dense convex separation and can punish correct density shapes. Pair it with stability and downstream checks.
Reproduce closed-book
DBSCAN with eps=2.0 and min_samples=2 on \(\left[\begin{smallmatrix}1&1\\1.5&1.5\\2&1\\8&8\\8.5&8.5\\9&8\end{smallmatrix}\right]\): two core groups \(\left[\begin{smallmatrix}0&0&0&1&1&1\end{smallmatrix}\right]\) with no noise. Then move one point to \(\left[\begin{smallmatrix}100&100\end{smallmatrix}\right]\) and show it becomes -1.Traps
- Leaving
epsat 0.5 on unscaled features.epslives in feature units; scale first or the radius is meaningless. - Calling
-1a detected anomaly set. It means not dense enough under thiseps; nearbyepsvalues relabel it. - Reporting silhouette alone on moons. On the notebook moons a k-means split scores 0.49 and the true moon labels 0.33; the docs warn that silhouette favors convex clusters.
Practice
Deep-ML 259: Implement DBSCAN Clustering Algorithm
Problem 259: implement dbscan(X, eps, min_samples) with Euclidean distance and -1 noise labels
Test one checks [0 0 0 1 1 1] on two triplets; test two checks the far point becomes -1. Count the point itself toward min_samples, as scikit-learn does; with min_samples=2 test two needs that, or the pair \(\left[\begin{smallmatrix}8&8\end{smallmatrix}\right]\), \(\left[\begin{smallmatrix}8.5&8.5\end{smallmatrix}\right]\) turns into noise. Expand clusters from core points only.
Self-test
-
On the notebook moons,
eps=0.05gives 7 clusters and 7.7 percent noise, whileeps=0.2gives two clean moons. What went wrong at 0.05, and what does the-1label mean?The radius is too small for the sampling density. A core needsmin_samplespoints withineps, counting itself, so sparse stretches of each moon lose their cores and the moons fragment. A-1point is withinepsof no core: not dense enough under these settings, which is not the same as anomalous. -
Single linkage gives \(\left[\begin{smallmatrix}0&0&0&1\end{smallmatrix}\right]\) and complete gives \(\left[\begin{smallmatrix}1&1&0&0\end{smallmatrix}\right]\) on \(\left[\begin{smallmatrix}0&2&5&8.5\end{smallmatrix}\right]\). Which is right?
Both follow their definitions: single chains through small gaps, complete caps the largest within-cluster distance. The task decides which grouping is useful. -
On the notebook moons,
KMeans(2)scores silhouette 0.49 and the true moon labels score 0.33. Which clustering is better?The true moons. Silhouette rewards compact convex groups, so it ranks the wrong spherical split higher. Use stability, adjusted Rand against any known structure, and downstream checks. -
Two DBSCAN runs with close eps values disagree on 5 percent of labels. What do you report?
The disagreement rate and which points flip, usually borders. Stability is evidence; one label vector is not.
Completion criterion
Stop when
Your implementation matches both Deep-ML label vectors, your eps sweep on moons shows the noise-to-merged transition, and two linkages disagree on record with reasons.
Leads to
- 4.7 Outlier and novelty detection, thresholds and representation Treat DBSCAN noise labels as candidates, not verdicts, with a scored threshold.
- 4.8 t-SNE and UMAP as guarded exploratory views Overlay cluster labels on an honest embedding to inspect shape.
Comes after
- 4.4 k-means: objective, initialization, empty clusters and instabilityContrast partition geometry with density and merge geometry.
- 4.5 Gaussian mixtures and EMCompare soft parametric groups with density and merge structure.
- 4.8 t-SNE and UMAP as guarded exploratory viewsCheck density labels against the same guarded view.
Resources for this unit
- Hands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learning Read Chapters 7 and 8 and run notebooks 07 and 08 for PCA, k-means, DBSCAN, agglomerative clustering, Gaussian mixtures and anomaly detection. Stop before extended semi-supervised and face-data projects.
- scikit-learn - decomposition, clustering and outlier detection Check decomposition orientation and solver behavior, cluster API semantics, and the distinction between novelty and outlier detection after the independent tests pass.
Also in this section
- ISLP - Unsupervised Learning Use Chapter 12 and its Python lab for the PCA derivations (12.2, including the low-rank approximation view and proportion of variance explained) and k-means (12.4.1), plus stability and interpretation limits, beside the notebook route.
- Deep-ML - unsupervised problems Use 17 K-Means Clustering, 19 PCA, 341 Gaussian Mixture Model with EM, 259 DBSCAN and 367 Isolation Forest as unit checks after the local implementation passes. Their tests were read in review; each card states what they pin, including the 367 path-length convention.
- scikit-learn - preprocessing data Read 8.3.1 standardization with the sparse
with_mean=Falserule, 8.3.1.3 scaling data with outliers, and 8.3.4 categorical encoding withhandle_unknown, infrequent andsparse_outputbehavior. Apply after the HOML notebook build works. - scikit-learn - pipelines and composite estimators Read 8.1.1
Pipelinechaining with the no-leakage rule and transformer caching, and 8.1.4ColumnTransformerfor heterogeneous columns withremainderand fitted-state behavior. Use it to assemble and serialize the feature-selection pipeline. - scikit-learn - imputation of missing values Read 8.4.2 univariate median and
most_frequentstrategies, 8.4.6 Marking imputed values withMissingIndicatororadd_indicator=Truefor missingness flags, and 8.4.7 estimators that acceptNaNdirectly. Decide impute-only versus impute-plus-indicator per column. - UMAP - basic usage and parameters Work the Penguin scaling and
fit_transformsection and the Digitsfitandtransformsection, then read the parameters page for then_neighborslocal-global tradeoff andmin_distpacking. Stay in 2D exploratory views with fixed seeds.