Unit 6 of 8 · about 4 hours · explain, measure
DBSCAN, 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.
You'll be able to
- 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
Read
In this order, only the parts listed
0 of 2 done
DBSCANcontrast and agglomerative exampleHands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learningBook 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 onSkim 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 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.
Common mistakes · 3
- 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.
Try it yourself
Closed-book, before checking anything
DBSCAN with eps=2.0 and min_samples=2 on : two core groups with no noise. Then move one point to and show it becomes -1.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.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?AnswerThe radius is too small for the sampling density. A core needs
min_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.2.Single linkage gives and complete gives on . Which is right?Answer
Both follow their definitions: single chains through small gaps, complete caps the largest within-cluster distance. The task decides which grouping is useful.
3.On the notebook moons,
KMeans(2)scores silhouette 0.49 and the true moon labels score 0.33. Which clustering is better?AnswerThe 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.
4.Two DBSCAN runs with close eps values disagree on 5 percent of labels. What do you report?Answer
The disagreement rate and which points flip, usually borders. Stability is evidence; one label vector is not.
Practice
- Deep-ML 259: Implement DBSCAN Clustering Algorithm
Problem 259: implement
dbscan(X, eps, min_samples)with Euclidean distance and-1noise labelsTest one checks
[0 0 0 1 1 1]on two triplets; test two checks the far point becomes-1. Count the point itself towardmin_samples, as scikit-learn does; withmin_samples=2test two needs that, or the pair , turns into noise. Expand clusters from core points only.
You're done 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.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 6 more in the section
- Hands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learningAurelien Geron (O'Reilly, 2025) · primary
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 detectionscikit-learn · reference
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 LearningJames, Witten, Hastie, Tibshirani and Taylor · required
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 problemsDeep-ML · support
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 datascikit-learn · reference
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 estimatorsscikit-learn · reference
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 valuesscikit-learn · reference
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 parametersMcInnes, Healy and the UMAP contributors · reference
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.