CS 460G Midterm Hub / Notebooks / Clustering
Python notebook · Copy of Clustering.ipynb

Clustering

k-means, DBSCAN, agglomerative, dendrograms, image segmentation

practice nbQ6 material

The shortest notebook in the course (14 cells) and the clearest demonstration of why clustering algorithm choice matters.

The data

from sklearn.datasets import make_moons
X, y = make_moons(n_samples=1000, noise=0.05, random_state=0)
plt.scatter(X[:,0], X[:,1])

Two interleaving crescents, 1000 points, low noise. This dataset exists to break k-means — it is the standard non-convex counterexample, and the notebook runs three algorithms on exactly the same points so the comparison is controlled.

Note that y (the true labels) is returned but never used. That is the definition of unsupervised learning: the labels exist only because make_moons generated them, not because the algorithm may see them.

k-means

from sklearn.cluster import KMeans
km = KMeans(n_clusters=2)
y_km = km.fit_predict(X)
plt.scatter(X[:,0], X[:,1], c=y_km)

Result: each crescent gets cut in half. The two halves of the top crescent end up in different clusters.

Why, precisely: k-means minimises $\sum_k\sum_{x\in C_k}\|x-\mu_k\|^2$, which is equivalent to carving the plane into Voronoi cells around two centroids. Voronoi cells are convex. A crescent is not convex. So no pair of centroids can separate them — the algorithm is solving the wrong geometry, not converging badly.

fit_predict returns the cluster label per point (0 or 1), which is why it is used instead of fit + predict.

Note the API details: n_clusters=2 must be supplied. There is no way for k-means to discover $K$.

DBSCAN

from sklearn.cluster import DBSCAN
db = DBSCAN(eps=0.2, min_samples=50, metric='euclidean')
y_db = db.fit_predict(X)

Result: both crescents recovered correctly.

Why: DBSCAN does not partition by distance-to-centre; it grows clusters through density connectivity. Within a crescent, every point has far more than 50 neighbours inside a 0.2 radius, so they form one connected component of core points. The gap between the crescents has low density, so the two components never join.

Parameter sensitivity — worth saying out loud:

  • min_samples=50 on 1000 points is 5% of the data — quite large. Lower it and noise starts forming spurious clusters; raise it and thin regions become noise.
  • eps=0.2 must be on the scale of the inter-point spacing. Too small → everything is noise; too large → the two crescents merge.

fit_predict returns −1 for noise points, which is why the plot has a third colour even though you asked for two clusters. That is a feature, not a bug.

Agglomerative

from sklearn.cluster import AgglomerativeClustering
h_cluster = AgglomerativeClustering(metric='euclidean', linkage='complete')
y_agg = h_cluster.fit_predict(X)

Result: also recovers the crescents. Complete linkage merges the two clusters whose most dissimilar members are closest, which resists the chaining that single linkage would suffer on a crescent.

Note: n_clusters defaults to 2 here, so $K$ is still being supplied — hierarchical clustering can infer $K$ from a dendrogram cut, but this call does not.

Dendrogram

from scipy.cluster.hierarchy import dendrogram, linkage
linkage_matrix = linkage(X[:10], method='centroid', metric='euclidean')
dendrogram(linkage_matrix)
plt.xlabel('Data points'); plt.ylabel('Distance'); plt.title('Centroid Linkage')

Only the first 10 points — a real dendrogram of 1000 leaves is unreadable. The y-axis is the merge distance: leaves that join low down are similar, branches that join near the top are different.

Reading it: each U-shape is a merge. The height of the horizontal bar is how dissimilar the two merged groups were. Cutting the tree at a chosen height gives you a flat clustering with that many clusters — which is how hierarchical clustering answers "how many clusters?" without being told.

On method='centroid': centroid linkage can produce inversions (a merge lower than one of its children's) because the centroid distance is not monotone. Average or complete linkage avoid this. Worth one sentence if asked to compare linkages.

Image segmentation

Superpixels

from skimage import data
img = data.astronaut()
from skimage.segmentation import slic
segments = slic(img, n_segments=20)     # k-means
plt.imshow(segments, 'jet')

slic is a k-means variant run in colour + position space. The comment #k-means is the point: segmentation is clustering where the samples are pixels and the features are RGB (plus coordinates).

Plain k-means on intensities

img_X = data.coins()          # (303, 384) grayscale
img_X = img_X.reshape(-1, 1)  # (116352, 1) — each pixel is a 1-D sample
km = KMeans(n_clusters=3)
y_seg = km.fit_predict(img_X)
plt.imshow(y_seg.reshape(303, 384), 'jet')

This is the cleanest illustration in the course. A grayscale image flattens to 116,352 samples in 1-D; k-means with $K=3$ becomes three-level thresholding. The reshaped result is a posterised image.

Explain the reshape dance: (303,384) → (-1,1) because scikit-learn wants (n_samples, n_features); then (116352,) → (303,384) to display it. Forgetting the second reshape gives a 1-D scatter instead of an image.

The comparison to memorise

k-meansDBSCANAgglomerative
Choose $K$?requiredinferredoptional (cut the tree)
Shapeconvex onlyarbitrarydepends on linkage
Outliersabsorbedlabelled noise (−1)absorbed
Parameters$K$$\epsilon$, minPtslinkage, metric
On make_moonsfailsworksworks
Costfastneeds spatial index$O(n^2)$ memory

"You ran k-means and DBSCAN on the same data and got different answers. Which is right?" Neither is "right" without a criterion — clustering is unsupervised, so there is no ground truth to compare against. The defensible argument is structural: if the true clusters are non-convex (crescents, rings, nested shapes), k-means is incapable of finding them because it can only produce convex Voronoi cells, so DBSCAN's answer is the more plausible one. If the clusters are compact and roughly spherical, k-means is faster and more stable. State the assumption each method makes, and judge the result against it.