Skip to main content

Mixtures and density

Examples

Gaussian mixture models

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans, DBSCAN
from sklearn.mixture import GaussianMixture

rng = np.random.default_rng(11)

means = [[0, 0], [3, 1.8], [-2.4, 3]]
covs = [[[1, 0.6], [0.6, 1]], [[1, -0.5], [-0.5, 1]], [[1, 0], [0, 1]]]
X = np.vstack([rng.multivariate_normal(m, c, 150) for m, c in zip(means, covs)])

gmm = GaussianMixture(n_components=3, n_init=5, random_state=0).fit(X)
proba = gmm.predict_proba(X)
lab = proba.argmax(axis=1)
conf = proba.max(axis=1)
print("points with confidence below 0.9:", int((conf < 0.9).sum()))
1
n_init=5 fits from five starting points and keeps the one with the highest likelihood.
2
One row per point, one column per component: the probability that the point comes from that component.
points with confidence below 0.9: 44
Code
fig, ax = plt.subplots(figsize=(4.6, 4.2))
for j in range(3):
    sel = lab == j
    ax.scatter(X[sel, 0], X[sel, 1], s=14, alpha=conf[sel] ** 3)
ax.set(xticks=[], yticks=[], aspect="equal")
plt.show()
Figure 59.1: The colour is the most likely component and the opacity the confidence. Points between two components are almost transparent.
Code
from sklearn.metrics import adjusted_rand_score

cov = [[4.0, 3.6], [3.6, 4.0]]
E = np.vstack([rng.multivariate_normal([0, 0], cov, 200),
               rng.multivariate_normal([2.5, -2.5], cov, 200)])
truth = np.repeat([0, 1], 200)
fits = {"k-means": KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(E),
        "Gaussian mixture": GaussianMixture(n_components=2, random_state=0).fit_predict(E)}

fig, axes = plt.subplots(1, 2, figsize=(6.6, 3.4))
for ax, (name, lab_) in zip(axes, fits.items()):
    for j in range(2):
        ax.plot(E[lab_ == j, 0], E[lab_ == j, 1], "o", ms=3)
    ax.set_title(f"{name}, ARI {adjusted_rand_score(truth, lab_):.2f}", fontsize=9)
    ax.set(xticks=[], yticks=[], aspect="equal")
plt.show()
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_split

rng4 = np.random.default_rng(4)
X2 = np.vstack([rng4.multivariate_normal(m, c, 400) for m, c in zip(means, covs)])
X_fit, X_val = train_test_split(X2, test_size=0.5, random_state=0)
for k in range(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.

  1. A core point has at least min_samples points within \(\varepsilon\), counting itself.
  2. Core points within \(\varepsilon\) of each other are in the same cluster, and chains of them grow the cluster.
  3. 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.
  4. 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_] = True
for xi, c, l in zip(x[:, 0], core, db.labels_):
    kind = "core" if c else ("noise" if l == -1 else "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 AgglomerativeClustering

srng = np.random.default_rng(1)


def sample(inside, n, box):
    out = []
    while len(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 < 8 and 0.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_) in zip(axes, labels.items()):
    col = ["#bbbbbb" if l == -1 else f"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).

Choosing \(\varepsilon\)

t = rng.uniform(0, np.pi, 200)
moons = np.vstack([
    np.column_stack([np.cos(t), np.sin(t)]) + rng.normal(0, 0.07, (200, 2)),
    np.column_stack([1 - np.cos(t), 0.5 - np.sin(t)]) + rng.normal(0, 0.07, (200, 2))])

for eps in [0.05, 0.15, 0.6]:
    lab_ = DBSCAN(eps=eps, min_samples=5).fit_predict(moons)
    n_clusters = len(set(lab_)) - (1 if -1 in lab_ else 0)
    print(f"eps = {eps:4}   clusters = {n_clusters}   noise = {(lab_ == -1).sum()}")
1
Two interleaving half circles.
eps = 0.05   clusters = 19   noise = 258
eps = 0.15   clusters = 2   noise = 3
eps =  0.6   clusters = 1   noise = 0

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 NearestNeighbors

dist, _ = 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.

Which method

assumes number of clusters outliers
k-means round, similar size given forced into a cluster
Gaussian mixture elliptical chosen on validation data soft assignment
hierarchical depends on linkage chosen from the tree forced into a cluster
DBSCAN dense regions comes out labelled as noise