Figure 59.2: Two elongated clusters. k-means cuts across them, the mixture follows them.
The adjusted Rand index (ARI) compares a clustering with the true groups: 1 is perfect agreement, 0 is what random labels get.
How many components
from sklearn.model_selection import train_test_splitrng4 = np.random.default_rng(4)X2 = np.vstack([rng4.multivariate_normal(m, c, 400) for m, c inzip(means, covs)])X_fit, X_val = train_test_split(X2, test_size=0.5, random_state=0)for k inrange(1, 9): m = GaussianMixture(n_components=k, n_init=5, random_state=0).fit(X_fit)print(f"k = {k} training {m.score(X_fit):6.3f} validation {m.score(X_val):6.3f}")
1
A larger sample from the same three components.
2
score is the mean log-likelihood per point.
k = 1 training -4.137 validation -4.171
k = 2 training -3.870 validation -3.905
k = 3 training -3.712 validation -3.718
k = 4 training -3.706 validation -3.732
k = 5 training -3.704 validation -3.736
k = 6 training -3.704 validation -3.737
k = 7 training -3.700 validation -3.740
k = 8 training -3.687 validation -3.760
The training log-likelihood grows with every component. The validation log-likelihood stops improving after three components, the number the data was generated with.
DBSCAN
DBSCAN has two parameters, a radius \(\varepsilon\) and a count min_samples.
A core point has at least min_samples points within \(\varepsilon\), counting itself.
Core points within \(\varepsilon\) of each other are in the same cluster, and chains of them grow the cluster.
A border point is not a core point but lies within \(\varepsilon\) of one. It joins that cluster, but the chain does not continue through it.
Everything else is noise.
Eight points on a line, with \(\varepsilon = 1.2\) and min_samples\(= 3\):
x = np.array([0, 1, 2, 3, 6, 7, 8, 11]).reshape(-1, 1)db = DBSCAN(eps=1.2, min_samples=3).fit(x)core = np.zeros(len(x), dtype=bool)core[db.core_sample_indices_] =Truefor xi, c, l inzip(x[:, 0], core, db.labels_): kind ="core"if c else ("noise"if l ==-1else"border")print(f"x = {xi:2d}{kind:6s} cluster {l}")
1
labels_ is the cluster of each point, \(-1\) for noise. core_sample_indices_ lists the core points.
x = 0 border cluster 0
x = 1 core cluster 0
x = 2 core cluster 0
x = 3 border cluster 0
x = 6 border cluster 1
x = 7 core cluster 1
x = 8 border cluster 1
x = 11 noise cluster -1
The points 0, 3, 6 and 8 have one neighbour each, too few to be core points, but each lies next to a core point. The point 11 has no neighbour at all.
A face, with 60 points scattered around it.
Code
from sklearn.cluster import AgglomerativeClusteringsrng = np.random.default_rng(1)def sample(inside, n, box): out = []whilelen(out) < n: p = srng.uniform(-box, box, 2)if inside(*p): out.append(p)return np.array(out)ring = sample(lambda x, y: 81< x**2+ y**2<100, 500, 10)eyes = np.vstack([sample(lambda x, y: (x - s)**2+ (y -4)**2<1, 60, 10) for s in (-4, 4)])mouth = sample(lambda x, y: -8< x <8and0.15* x**2-6< y < (0.15-6/64) * x**2-4,180, 10)S = np.vstack([ring, eyes, mouth, srng.uniform(-11, 11, (60, 2))])labels = {"k-means, k = 4": KMeans(4, n_init=10, random_state=0).fit_predict(S),"mixture, 4 components": GaussianMixture(4, n_init=5, random_state=0).fit_predict(S),"single linkage, 4": AgglomerativeClustering(4, linkage="single").fit_predict(S),"DBSCAN": DBSCAN(eps=1, min_samples=10).fit_predict(S)}fig, axes = plt.subplots(1, 4, figsize=(10, 2.8))for ax, (name, lab_) inzip(axes, labels.items()): col = ["#bbbbbb"if l ==-1elsef"C{l %6}"for l in lab_] ax.scatter(S[:, 0], S[:, 1], s=3, c=col) ax.set_title(name, fontsize=9) ax.set(xticks=[], yticks=[], aspect="equal")plt.show()
Figure 59.3: k-means and the mixture cut the face into pieces. Single linkage joins everything through the scattered points. DBSCAN finds the face, the eyes and the mouth, and labels the scattered points as noise (grey).
Too small an \(\varepsilon\) and almost everything is noise. Too large and everything is one cluster.
The radius and the minimum count decide everything. On the moons there is a window of ε where it finds exactly two clusters. On data with no structure it labels almost everything noise.
A starting value for \(\varepsilon\) comes from the distance of every point to its min_samples-th nearest neighbour (itself included). Sorted, these distances are small inside the clusters and jump up for the noise.
Code
from sklearn.neighbors import NearestNeighborsdist, _ = NearestNeighbors(n_neighbors=5).fit(moons).kneighbors(moons)fig, ax = plt.subplots(figsize=(4.6, 2.8))ax.plot(np.sort(dist[:, -1]))ax.set(xlabel="points, sorted", ylabel="distance to 5th neighbour")plt.show()
1
kneighbors on the fitted points counts each point as its own first neighbour, as min_samples does.
Figure 59.4: Sorted distances to the fifth nearest neighbour on the moons. The bend suggests an ε around 0.1 to 0.15.