Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 25 min · revision 2

Clustering: Centroids, Mixtures, Hierarchies and Density

Run k-means, Gaussian mixtures, hierarchical clustering and DBSCAN on four synthetic shapes to see which assumption fits which data, read soft assignments, merge heights and density parameters, and learn why a silhouette score needs segment profiles and stability checks beside it.

Contentsand lesson path

What you will learn

  • Apply k-means, Gaussian mixture models, hierarchical clustering and DBSCAN, choosing the algorithm and its parameters from the data's shape, and validate clusters with silhouette scores and segment profiles.

01. Why it matters

Clustering groups similar rows when you have no labels to learn from: customer segments for marketing, typical transaction patterns for a fraud team, themes in support tickets. Nobody knows the right answer in advance, so the algorithm's own idea of what a group is decides what you get.

That idea differs between algorithms. k-means looks for round groups around a centre. A Gaussian mixture model looks for ellipses of different sizes and shapes. Hierarchical clustering builds a tree of merges that you cut where you like. DBSCAN follows dense regions of any shape and leaves sparse points out as noise.

This lesson runs all four on synthetic data whose true groups are known, so you can see which assumption fits which shape, then shows how to check clusters on real data, where no answer key exists. The code uses Python 3.12, scikit-learn 1.9 and SciPy 1.18. Every method here depends on distances, so every example standardises its columns first; Similarity and Structure explains why.

02. Centroids and mixtures

shapes.py builds four 2-D datasets of 600 points: three round blobs; three blobs stretched and tilted; a wide cluster of 450 points next to a tight one of 150; and two interleaving half-moons. It scores five models with the adjusted Rand index (ARI), which compares two labellings: 1 means the clusters match the true groups exactly (whatever their numbers), and values near 0 mean chance agreement.

Python · shapes.py
import numpy as np
from sklearn.cluster import DBSCAN, AgglomerativeClustering, KMeans
from sklearn.datasets import make_blobs, make_moons
from sklearn.metrics import adjusted_rand_score
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import StandardScaler


def datasets():
    round_ = make_blobs(600, centers=3, random_state=8)
    X, y = make_blobs(600, centers=3, random_state=170)
    stretched = (X @ np.array([[0.6, -0.64], [-0.41, 0.85]]), y)  # tilt and stretch
    uneven = make_blobs([450, 150], centers=[[0, 0], [5, 0]],
                        cluster_std=[2.0, 0.4], random_state=0)
    moons = make_moons(600, noise=0.06, random_state=0)
    return {"round": round_, "stretched": stretched, "uneven": uneven,
            "moons": moons}


def models(k):
    return {
        "k-means": KMeans(k, n_init=10, random_state=0),
        "GMM, full cov.": GaussianMixture(k, random_state=0),
        "ward linkage": AgglomerativeClustering(k, linkage="ward"),
        "single linkage": AgglomerativeClustering(k, linkage="single"),
        "DBSCAN": DBSCAN(eps=0.2, min_samples=10),
    }


if __name__ == "__main__":
    table = {}
    for name, (X, y) in datasets().items():
        X = StandardScaler().fit_transform(X)
        for algo, model in models(k=len(set(y))).items():
            ari = round(adjusted_rand_score(y, model.fit_predict(X)), 2) + 0
            table.setdefault(algo, []).append(ari)
    print("ARI vs true groups  round  stretched  uneven  moons")
    for algo, scores in table.items():
        print(f"{algo:18}" + "".join(f"{s:>{w}.2f}" for s, w in
                                    zip(scores, [7, 11, 8, 7])))
Terminal
python shapes.py
Expected output
ARI vs true groups  round  stretched  uneven  moons
k-means              1.00       0.56    0.45   0.48
GMM, full cov.       1.00       1.00    0.97   0.49
ward linkage         1.00       0.59    0.97   0.61
single linkage       1.00       0.56    0.00   1.00
DBSCAN               0.99       0.91    0.39   0.99

k-means picks k centres, assigns each point to its nearest centre, moves each centre to the mean of its points, and repeats until nothing changes. This minimises the inertia, the sum of squared distances from points to their centre. The result depends on the starting centres, so n_init=10 keeps the best of ten starts. Squared distance to one centre knows nothing about direction or spread, so k-means suits round groups of similar size and spread: 1.00 on the round blobs, poor elsewhere. On the uneven data (0.45) it moves the boundary into the wide cluster, because halving a spread-out group lowers the inertia more than following the real gap. More starts cannot fix that; the objective itself prefers the wrong answer.

No row is best everywhere. The mixture wins on stretched and uneven blobs, single linkage and DBSCAN follow the moons, and each fails somewhere else. The sections below explain why.

A Gaussian mixture model (GMM) assumes the data comes from k bell-shaped distributions, each with its own mean, weight (share of the points) and covariance matrix, which says how far and in which directions it spreads. Per-component covariance lets it model a tilted ellipse or a tight cluster beside a wide one. It also gives a soft assignment: predict_proba returns the probability that each point came from each component. soft.py probes three points between the two uneven clusters.

Python · soft.py
import numpy as np
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import StandardScaler

from shapes import datasets

X, y = datasets()["uneven"]
X = StandardScaler().fit_transform(X)
gmm = GaussianMixture(2, covariance_type="full", random_state=0).fit(X)
km = KMeans(2, n_init=10, random_state=0).fit(X)
print("GMM means x:", gmm.means_[:, 0].round(2), "weights:", gmm.weights_.round(2))
print("GMM std of x per component:", np.sqrt(gmm.covariances_[:, 0, 0]).round(2))
print("k-means centres x:", np.sort(km.cluster_centers_[:, 0]).round(2))

points = np.array([[0.45, 0.0], [0.98, 0.0], [1.10, 0.0]])
proba = gmm.predict_proba(points)
centre = km.cluster_centers_[km.predict(points), 0]
for p, row, c in zip(points, proba, centre):
    print(f"x = {p[0]:.2f}: GMM P(wide, tight) {row.round(3)}, k-means centre {c:.2f}")

for k in [1, 2, 3, 4]:
    model = GaussianMixture(k, random_state=0).fit(X)
    print(f"components = {k}: BIC {model.bic(X):7.1f}")
Terminal
python soft.py
Expected output
GMM means x: [-0.47  1.38] weights: [0.75 0.25]
GMM std of x per component: [0.69 0.13]
k-means centres x: [-0.7   0.99]
x = 0.45: GMM P(wide, tight) [1. 0.], k-means centre 0.99
x = 0.98: GMM P(wide, tight) [0.541 0.459], k-means centre 0.99
x = 1.10: GMM P(wide, tight) [0.071 0.929], k-means centre 0.99
components = 1: BIC  3437.0
components = 2: BIC  2836.5
components = 3: BIC  2875.4
components = 4: BIC  2908.6

The GMM learned a wide component (75% of points, standard deviation 0.69) and a tight one (25%, 0.13). k-means put its right-hand centre at 0.99, inside the wide cluster, and claims all three probes for it. The GMM gives x = 0.45 firmly to the wide cluster, is unsure at x = 0.98 (0.541 against 0.459) and gives x = 1.10 to the tight one, because the tight component's density falls away fast. Uncertain points are useful: a customer between two segments can get a blend of both campaigns.

covariance_type sets each component's flexibility: "full" (the default) gives each its own ellipse, "diag" axis-aligned ellipses, "spherical" circles, "tied" one shared shape. Fewer parameters fit more reliably on small data. To choose the number of components, compare the Bayesian information criterion (BIC), which rewards fit and penalises parameters; lower is better, and here it bottoms out at the true two.

03. Hierarchies and density

Agglomerative clustering starts with every point alone and repeatedly merges the two closest clusters. The merges form a tree, the dendrogram, which you cut at some height. The linkage defines the distance between clusters. Ward merges the pair that raises within-cluster variance least, so it prefers compact groups. Complete and average use the largest and the mean distance between points. Single uses the smallest, so clusters grow by chaining from neighbour to neighbour: good for curved shapes like the moons, but on the uneven data it split off one stray point and merged the other 599, hence its 0.00.

Python · tree.py
from scipy.cluster.hierarchy import fcluster, linkage
from sklearn.preprocessing import StandardScaler

from shapes import datasets

X, _ = datasets()["round"]
X = StandardScaler().fit_transform(X)
Z = linkage(X, method="ward")          # one row per merge: a, b, height, size
print("last six merge heights:", Z[-6:, 2].round(2))
for t in [1.0, 5.0, 30.0]:
    labels = fcluster(Z, t=t, criterion="distance")
    print(f"cut at height {t:4.1f}: {labels.max():3d} clusters")
Terminal
python tree.py
Expected output
last six merge heights: [ 1.89  2.52  2.58  2.71 15.61 45.86]
cut at height  1.0:  12 clusters
cut at height  5.0:   3 clusters
cut at height 30.0:   2 clusters

Merge heights creep up to 2.71 while small groups combine, then jump to 15.61 and 45.86 when the real blobs are joined. Cut just below the big jump: any height between about 3 and 15 gives three clusters (in scikit-learn, AgglomerativeClustering(n_clusters=None, distance_threshold=5.0)). No k is needed in advance, but the method works with all pairwise distances, so cost grows at least with the square of the row count: thousands of rows, not millions.

DBSCAN defines a cluster as a dense region. A point with at least min_samples points (itself included) within radius eps is a core point. Core points within eps of each other share a cluster, so clusters can take any shape. A non-core point within eps of a core point is a border point and joins it. Everything else is noise, labelled -1. The number of clusters follows from the density. To start eps, look at each point's distance to its min_samples-th neighbour: small inside clusters, large for isolated points.

Python · dbscan_eps.py
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import StandardScaler

from shapes import datasets

X, _ = datasets()["moons"]
X = StandardScaler().fit_transform(X)

# distance from each point to its 10th neighbour (the point itself counts as one)
dist, _ = NearestNeighbors(n_neighbors=10).fit(X).kneighbors(X)
kth = np.sort(dist[:, -1])
print("10th-neighbour distance, percentiles 50/90/99:",
      np.percentile(kth, [50, 90, 99]).round(3))

for eps in [0.05, 0.1, 0.2, 0.6]:
    labels = DBSCAN(eps=eps, min_samples=10).fit_predict(X)
    n_clusters = labels.max() + 1
    print(f"eps = {eps:4.2f}: {n_clusters:2d} clusters, "
          f"{np.mean(labels == -1):6.1%} noise")
Terminal
python dbscan_eps.py
Expected output
10th-neighbour distance, percentiles 50/90/99: [0.13  0.181 0.269]
eps = 0.05:  0 clusters, 100.0% noise
eps = 0.10: 16 clusters,  65.8% noise
eps = 0.20:  2 clusters,   0.3% noise
eps = 0.60:  1 clusters,   0.0% noise

Half the points have their tenth neighbour within 0.13, and 99% within 0.269. At eps 0.05 no point is core, so everything is noise. At 0.10 only dense pockets qualify: 16 fragments and 65.8% noise. At 0.20, just above the 90th percentile, the two moons appear. At 0.60 the radius bridges the moons and merges them. Raising min_samples demands more neighbours and so marks more noise; about twice the number of features is a common start.

One eps applies everywhere, which is DBSCAN's limit. On the uneven data a radius that suits the tight cluster turned 57% of the wide cluster into noise, hence its 0.39. sklearn.cluster.HDBSCAN lets the density threshold vary and is worth trying when densities differ.

04. Validating clusters without labels

Real data has no answer key, so you need internal measures. The silhouette of a point compares a, its mean distance to its own cluster, with b, its mean distance to the nearest other cluster: s = (b − a) / max(a, b). It is near 1 deep inside a well-separated cluster, near 0 on a boundary and negative in the wrong cluster. silhouette_score averages it over points.

Python · silhouette.py
from sklearn.cluster import DBSCAN, KMeans
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.preprocessing import StandardScaler

from shapes import datasets

X, y = datasets()["moons"]
X = StandardScaler().fit_transform(X)
for name, model in [("k-means, k = 2", KMeans(2, n_init=10, random_state=0)),
                    ("DBSCAN", DBSCAN(eps=0.2, min_samples=10))]:
    labels = model.fit_predict(X)
    keep = labels != -1                       # silhouette ignores noise here
    sil = silhouette_score(X[keep], labels[keep])
    ari = adjusted_rand_score(y, labels)
    print(f"{name:15} silhouette {sil:.3f}   ARI vs true moons {ari:.2f}")
Terminal
python silhouette.py
Expected output
k-means, k = 2  silhouette 0.491   ARI vs true moons 0.48
DBSCAN          silhouette 0.392   ARI vs true moons 0.99

k-means wins on silhouette (0.491 against 0.392) while getting the moons wrong (ARI 0.48 against 0.99). Points at the ends of a curved moon are far from the rest of it, which raises a, while two compact halves score well. Silhouette rewards round, well-separated groups; it is one notion of a good cluster, not the truth. Nor is there a universal cut-off such as "above 0.5 means real clusters": typical values depend on the features, the noise and the shapes. Validate with several kinds of evidence:

  • silhouette, compared across k or algorithms on the same scaled data;
  • a segment profile: each cluster's size and the median of every original feature in real units, so you can say what each group is and whether anyone can act on it;
  • stability: refit on bootstrap samples or other seeds and check, for example with ARI, that the same groups return.

The next lesson applies all three to a customer table.

05. Check your understanding

Practice check · 3 questions

Reading the clustering outputs

Answer from the code and the numbers in this lesson.

Q1. In `soft.py` the probe at x = 0.98 is 0.40 from the tight component's mean and 1.45 from the wide one's, yet the GMM gives it 0.541 to the wide component. Why?
Q2. In `dbscan_eps.py`, `eps = 0.10` gives 16 clusters and 65.8% noise on the two moons. Which explanation fits the printed percentiles?
Q3. A colleague reads the output of `silhouette.py` and concludes that k-means clusters the moons better, because 0.491 beats 0.392. What is wrong with that reasoning?
Practice only: not graded, not saved, not evidence.

06. Apply it

Start the skill's practice project on a customer or transaction table of your own, or on the synthetic one from the next lab.

  1. Log-transform skewed features such as spend, standardise, and fit k-means for k = 2 to 8, recording inertia and silhouette.
  2. Fit DBSCAN with min_samples near twice the number of features and three values of eps taken from the k-th neighbour distance percentiles; record clusters and noise share.
  3. Fit a GMM over the same k and note where BIC is lowest.
  4. Write one sentence per algorithm on what its result says about the shape and density of your data, and pick the solution to profile.

07. Review prompt

Without looking back, explain what k-means minimises and why it prefers round clusters of similar spread; what soft assignments and per-component covariance add in a GMM; how single and Ward linkage differ; what eps and min_samples mean and how to choose eps; and why a higher silhouette does not prove a clustering is right.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check