Module 9/15 · Weeks 9 · 9 h

Unsupervised learning, clustering and dimensionality reduction

UAT 456 Artificial Intelligence, Machine Learning and Computer Vision for UAS

About 100 minDraft, awaiting reviewLast updated 1 October 2026

Lesson

By the end of this module you will be able to

  1. Explain and choose k-means, GMM and DBSCAN to match the shape and density of the data
  2. Choose the number of clusters with silhouette and BIC, and state the limits of these criteria
  3. Set eps and min_samples of DBSCAN from neighbour distances, and interpret noise points with care
  4. Use PCA for dimensionality reduction by standardising first, reading the loadings and choosing the number of components
  5. Explain the cautions for t-SNE and UMAP when interpreting cluster size, distance and shape

Prerequisites: Module 6 of this course and UAT 106 Statistics and Data Analytics for Technology

Why this matters

Most automation data has no labels. A PLC records sensors every minute without anyone writing down which mode the line was in during that minute, and a flight log does not say which flight was strange. Unsupervised learning helps answer two questions: how many kinds of data are there, and which data do not belong. It also reduces the number of dimensions until a human can look at the data. With no labels there is no answer key for computing a score, so the check relies on criteria inside the data and on domain knowledge. In this module the data is synthetic, so the true modes are known and used as an answer key purely for teaching (the ARI metric); in real work this key does not exist. The case study has two data sets. The first is a per-minute record of 8 sensors on the bottling line (line speed, conveyor current, capper torque, vibration, bearing temperature, air pressure, fill variation and water temperature). The second is a per-flight summary of the drone fleet. The details of k-means, GMM and DBSCAN in scikit-learn are in the library’s clustering guide (scikit-learn developers). All numbers are assumed.

Clustering with k-means

k-means splits the data into groups by minimising the sum of squared distances from each point to the centre of its own group, (called the inertia). Lloyd’s algorithm alternates two steps: first assign each point to the nearest centre, then move each centre to the mean of its members, and repeat until nothing changes. There are three cautions. First, standardise the features beforehand, because the method relies on distance. Second, the result depends on the starting points because it can get stuck in a local minimum; Arthur and Vassilvitskii (2007) proposed k-means++, which spreads the starting points apart, and the scikit-learn guide sets n_init automatically (1 run with k-means++, 10 with random starts). Third, k-means assumes round clusters of similar size.

Choosing is hard because inertia falls every time increases. The silhouette (Rousseeuw, 1987) measures how well one point fits, , where is the mean distance to the other members of its own cluster and is the mean distance to the nearest other cluster. The value lies between −1 and 1; average it over all points and choose the with the highest value.

Example 1 k-means step by step, and on the bottling-line record

The first part walks through Lloyd’s algorithm on six points on a line, one round at a time. The second part uses 1,800 minutes of 8 sensors from the bottling line (function make_modes), generated from three known modes: small bottles at high speed, large bottles at low speed, and a changeover period where values spread widely. The table shows inertia, silhouette and ARI against the true modes. Then k-means is started 30 times from a single initialisation, with random starts and with k-means++, to compare them.

import numpy as np, pandas as pd
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score, silhouette_score
from sklearn.preprocessing import StandardScaler

x, c = np.array([1.0, 2.0, 4.0, 9.0, 11.0, 12.0]), np.array([2.0, 4.0])       # six points on a line and two initial centres
for it in range(1, 4):
    lab = np.abs(x[:, None] - c[None, :]).argmin(1)                           # step 1: assign each point to the nearest centre
    c = np.array([x[lab == j].mean() for j in range(2)])                      # step 2: move each centre to the mean of its members
    sse = sum(((x[lab == j] - c[j]) ** 2).sum() for j in range(2))
    print(f"iteration {it}: labels {lab.tolist()}, centres {np.round(c, 2).tolist()}, inertia {sse:.2f}")

def make_modes(seed=482):
    rng = np.random.default_rng(seed)
    cols = ["speed", "conv_amps", "torque", "vib", "bearing_temp", "air_bar", "fill_sd", "water_temp"]
    spec = {   # mode: (minutes, means, weights on the shared latent variable, independent standard deviations)
        "fast small": (900, [330, 4.4, 1.6, 2.2, 46, 6.0, 0.8, 18], [12, 0.15, 0.05, 0.15, 1.2, 0.05, 0.04, 0.5], [6, 0.10, 0.06, 0.15, 0.8, 0.08, 0.05, 0.8]),
        "slow large": (600, [210, 3.7, 2.1, 1.6, 41, 6.2, 0.6, 18], [10, 0.12, 0.06, 0.12, 1.0, 0.05, 0.04, 0.5], [6, 0.10, 0.06, 0.15, 0.8, 0.08, 0.05, 0.8]),
        "changeover": (300, [120, 3.2, 1.2, 1.4, 38, 5.6, 0.9, 18], [70, 0.9, 0.4, 0.7, 6.0, 0.3, 0.2, 0.5], [10, 0.15, 0.1, 0.2, 1.0, 0.1, 0.08, 0.8])}
    X, y = [], []
    for k, (n, mu, a, s) in enumerate(spec.values()):
        z = rng.normal(size=(n, 1))                                            # a shared latent variable makes the sensors in one mode correlated
        X.append(np.array(mu) + z * np.array(a) + rng.normal(size=(n, 8)) * np.array(s)); y += [k] * n
    X, y = np.vstack(X), np.array(y)
    p = rng.permutation(len(y))
    return pd.DataFrame(X[p], columns=cols), y[p]

modes, truth = make_modes()                                                    # truth is for checking only; real work has no answer key
scaler = StandardScaler().fit(modes)
Z = scaler.transform(modes)                                                    # standardise, otherwise speed (in the hundreds) dominates every distance
print(f"{len(modes)} minutes of PLC data, 8 sensors")
print("k  inertia  silhouette  ARI vs true modes")
for k in range(2, 7):
    km = KMeans(k, n_init=10, random_state=0).fit(Z)
    print(f"{k}  {km.inertia_:>7.0f}  {silhouette_score(Z, km.labels_):>10.3f}  {adjusted_rand_score(truth, km.labels_):>16.3f}")
starts = {init: np.array([KMeans(5, init=init, n_init=1, random_state=s).fit(Z).inertia_ for s in range(30)]) for init in ("random", "k-means++")}
best = min(v.min() for v in starts.values())
for init, v in starts.items():                                                 # 30 single random starts, to see how bad the local minima get
    print(f"k=5, 30 single starts, init={init:<9}: inertia median {np.median(v):.0f}, worst {v.max():.0f}, reached the best ({best:.0f}) in {(v < best + 1).sum()} runs")
iteration 1: labels [0, 0, 1, 1, 1, 1], centres [1.5, 9.0], inertia 38.50
iteration 2: labels [0, 0, 0, 1, 1, 1], centres [2.33, 10.67], inertia 9.33
iteration 3: labels [0, 0, 0, 1, 1, 1], centres [2.33, 10.67], inertia 9.33
1800 minutes of PLC data, 8 sensors
k  inertia  silhouette  ARI vs true modes
2     8847       0.538             0.217
3     5042       0.479             0.852
4     4110       0.490             0.901
5     3399       0.373             0.659
6     2945       0.317             0.520
k=5, 30 single starts, init=random   : inertia median 3650, worst 4447, reached the best (3399) in 13 runs
k=5, 30 single starts, init=k-means++: inertia median 3399, worst 3850, reached the best (3399) in 17 runs

The step-by-step run shows that the result settles after round 2, with inertia falling from 38.50 to 9.33. On the line data, inertia falls every time increases (8,847 at down to 2,945 at ), so there is no clear elbow. The silhouette peaks at (0.538), but against the true modes the ARI at is only 0.217 because two of the modes are merged. At the ARI is 0.852 and at it is 0.901 (the wide cluster is split in two); beyond that it falls. The lesson is that the silhouette favours coarse, cleanly separated structure, so it must be combined with domain knowledge. Here the technician knows there are small bottles, large bottles and a changeover period, so is chosen. A single start is risky. At , 30 random starts gave a median inertia of 3,650, a worst of 4,447, and reached the best value (3,399) only 13 times, whereas k-means++ gave a median of 3,399, a worst of 3,850 and reached the best 17 times. In practice, run several starts and keep the result with the lowest inertia.

Two-panel chart. The left panel is the k-means silhouette for k from 2 to 6: 0.538, 0.479, 0.490, 0.373 and 0.317, highest at k equal to 2. The right panel is the GMM BIC for k from 1 to 6: 22146, 14038, 10517, 10815, 11110 and 11407, lowest at k equal to 3
Figure 1 Silhouette of k-means and BIC of GMM by number of clusters

Gaussian mixture models (GMM)

A Gaussian mixture model (GMM) assumes each group comes from its own multivariate normal distribution, with a mean, a covariance matrix and a weight. It is trained with the EM algorithm (Dempster et al., 1977), which also alternates two steps. The E step computes the probability that each point belongs to each component; the M step updates the means, covariances and weights using those probabilities. The result is a soft assignment and clusters that can be tilted ellipses. k-means is the limiting case in which every cluster is round and equal in size and membership is hard. The number of components is chosen with the BIC (Schwarz, 1978), , where is the number of parameters, the number of samples and the maximised likelihood; lower is better, and the term penalises models with many parameters.

Example 2 GMM on the modes of the bottling line

Using the data and Z from Example 1, compare k-means with GMMs that have a full, diagonal (diag) and spherical covariance, then summarise each component back in the original units.

from sklearn.mixture import GaussianMixture
print("k  BIC (lower is better)")
for k in range(1, 7):
    print(f"{k}  {GaussianMixture(k, n_init=5, random_state=0).fit(Z).bic(Z):>8.0f}")
km3 = KMeans(3, n_init=10, random_state=0).fit(Z)
print(f"k-means, k=3: ARI {adjusted_rand_score(truth, km3.labels_):.3f}")
for cov in ("full", "diag", "spherical"):
    gm = GaussianMixture(3, covariance_type=cov, n_init=5, random_state=0).fit(Z)
    print(f"GMM {cov:<9}: BIC {gm.bic(Z):>7.0f}, ARI {adjusted_rand_score(truth, gm.predict(Z)):.3f}")
gm = GaussianMixture(3, covariance_type="full", n_init=5, random_state=0).fit(Z)
prob = gm.predict_proba(Z)                                                     # probability that each minute belongs to each component
centres = scaler.inverse_transform(gm.means_)                                  # convert the centres back to the original units
print("component  weight  speed  torque  bearing temp")
for j in np.argsort(centres[:, 0]):
    print(f"{j:>9}  {gm.weights_[j]:>6.2f}  {centres[j, 0]:>5.0f}  {centres[j, 2]:>6.2f}  {centres[j, 4]:>12.1f}")
print(f"minutes whose top probability is below 0.999: {int((prob.max(1) < 0.999).sum())} of {len(Z)}")
k  BIC (lower is better)
1     22146
2     14038
3     10517
4     10815
5     11110
6     11407
k-means, k=3: ARI 0.852
GMM full     : BIC   10517, ARI 1.000
GMM diag     : BIC   20097, ARI 0.984
GMM spherical: BIC   27196, ARI 0.936
component  weight  speed  torque  bearing temp
        0    0.17    118    1.19          37.9
        1    0.33    210    2.10          41.0
        2    0.50    330    1.60          46.0
minutes whose top probability is below 0.999: 0 of 1800

The BIC is lowest at 3 components (10,517 against 10,815 at 4), matching the true number of modes, and the full GMM reaches an ARI of 1.000 against 0.852 for k-means at . The reason is that the sensors within one mode are correlated (speed, current and bearing temperature rise and fall together), so the clusters are tilted ellipses, and the changeover cluster is much wider than the others, which k-means, assuming round clusters of equal size, splits wrongly. The spherical model, which is close to the assumption of k-means, gives a BIC of 27,196 and an ARI of 0.936, and the diagonal one a BIC of 20,097. Choosing the covariance structure therefore matters as much as choosing the number of clusters. The component summary reads straight off the plant: the weights 0.50, 0.33 and 0.17 match the share of minutes of fast small bottles (330 bottles per minute), slow large bottles (210) and changeover (118). In this data every minute has a top probability of at least 0.999 because the modes are well separated; if the modes overlapped there would be uncertain minutes, and the GMM would say how uncertain. The limitation is that GMM and BIC assume Gaussian-shaped clusters; if the true clusters are curved or heavy-tailed, BIC may choose too many.

Horizontal bar chart of ARI against the true modes: k-means 0.852 in yellow, GMM with full covariance 1.000, GMM with diagonal covariance 0.984 in green, GMM with spherical covariance 0.936 in blue
Figure 2 ARI of k-means and of GMMs with different covariance structures

Density-based clustering with DBSCAN

DBSCAN (Ester et al., 1996) needs no number of clusters. A point with at least min_samples points (itself included) within radius is a core point. Core points close to each other link into a cluster. A point inside the radius of a core point that is not core itself is a border point of that cluster, and the remaining points are noise (label −1). Clusters can therefore have any shape, and there is a built-in place for outliers. Schubert et al. (2017) review when to use DBSCAN and how to set it. The value of is read from a plot of the distance to the -th neighbour sorted from small to large; the point where the curve bends sharply upward is the seam between points inside clusters and isolated points.

Example 3 Finding unusual flights with DBSCAN

The per-flight summary has 548 flights of the fleet (function make_flights) with 6 features: mean speed, altitude, maximum bank angle, mean current, duration and vibration. It contains 300 mapping flights, 150 inspection flights, 80 ferry flights (lower density), 8 night-survey flights (a new type that really exists but is still rare) and 10 injected anomalous flights. The table shows the effect of and min_samples.

from sklearn.cluster import DBSCAN
from sklearn.neighbors import NearestNeighbors

def make_flights(seed=482):
    rng = np.random.default_rng(seed)
    cols = ["speed", "alt", "bank", "amps", "minutes", "vib"]
    kinds = {"mapping": (300, [10.0, 80, 22, 24, 28, 9], [0.6, 3, 2, 1.0, 2.0, 0.8]),
             "inspection": (150, [3.5, 35, 12, 21, 18, 8], [0.5, 4, 2, 1.0, 2.0, 0.8]),
             "ferry": (80, [16.0, 110, 8, 30, 9, 11], [1.5, 8, 3, 2.0, 2.5, 1.5]),           # sparser and more spread out
             "night survey": (8, [8.0, 60, 18, 27, 40, 9], [0.4, 3, 1.5, 0.8, 1.5, 0.6])}   # a new flight type that really exists but is rare
    X, y = [], []
    for k, (n, mu, sd) in kinds.items():
        X.append(rng.normal(mu, sd, size=(n, 6))); y += [k] * n
    odd = np.array([[13, 100, 40, 33, 11, 12], [6, 60, 35, 38, 25, 20], [9, 85, 24, 26, 30, 24], [2, 25, 10, 42, 12, 9], [18, 60, 30, 22, 7, 10], [11, 95, 20, 38, 40, 15],
                    [5, 120, 28, 25, 20, 10], [14, 70, 15, 20, 45, 9], [8, 30, 45, 30, 15, 16], [20, 130, 6, 34, 6, 20]], float)   # ten injected anomalous flights
    X.append(odd); y += ["anomaly"] * len(odd)
    return pd.DataFrame(np.vstack(X), columns=cols), np.array(y)

flights, kind = make_flights()
F = StandardScaler().fit_transform(flights)
is_anomaly, is_night = kind == "anomaly", kind == "night survey"
kdist = np.sort(NearestNeighbors(n_neighbors=5).fit(F).kneighbors(F)[0][:, -1])        # distance to the 4th neighbour (not counting the point itself)
print(f"{len(F)} flights; distance to the 4th neighbour, quantiles 50/80/90/95/98/100%: " + " ".join(f"{q:.2f}" for q in np.quantile(kdist, [0.5, 0.8, 0.9, 0.95, 0.98, 1.0])))
print("min_samples  eps  clusters  noise  anomalies caught  other noise  night survey in noise")
for ms, eps in ((5, 0.5), (5, 0.7), (5, 1.0), (5, 1.5), (10, 1.0), (10, 1.5)):
    lab = DBSCAN(eps=eps, min_samples=ms).fit_predict(F); noise = lab == -1
    print(f"{ms:>11}  {eps:.1f}  {len(set(lab) - {-1}):>8}  {noise.sum():>5}  {(noise & is_anomaly).sum():>16}  {(noise & ~is_anomaly).sum():>11}  {(noise & is_night).sum():>20}")
548 flights; distance to the 4th neighbour, quantiles 50/80/90/95/98/100%: 0.39 0.66 0.86 1.06 1.47 6.74
min_samples  eps  clusters  noise  anomalies caught  other noise  night survey in noise
          5  0.5         2    130                10          120                     8
          5  0.7         5     68                10           58                     0
          5  1.0         4     18                10            8                     0
          5  1.5         3     10                10            0                     0
         10  1.0         3     31                10           21                     8
         10  1.5         3     17                10            7                     7

The distance to the 4th neighbour grows slowly up to the 98% quantile (1.47) and then jumps to 6.74 at the last point. That bend is the isolated points, so values from 0.5 to 1.5 are tried. In the table, at there are only 2 clusters (mapping and inspection) and 130 noise points, made up of all 80 ferry flights (less dense than the other groups), all 8 night-survey flights, the 10 anomalies and another 32 flights on the edges of the two large clusters. At there are 4 clusters (night survey forms a cluster of its own) and 18 noise points: the 10 anomalies plus 8 flights at the edge of the ferry group. At the noise falls to 10 points, which are exactly the anomalies, but only 3 clusters remain because the night-survey flights were absorbed into another cluster. With min_samples raised to 10, the 8 night-survey flights are too few and become noise (at ). Three lessons follow. First, noise is not always an error: a flight that looks “strange” may be a new type that deserves its own cluster. Second, clusters have different densities, so no single fits all of them (scikit-learn also provides HDBSCAN, which relaxes this limit and is worth trying). Third, tune the values, check the result against domain knowledge and record the settings, because the result is sensitive to the parameters.

Grouped bar chart for four eps values 0.5, 0.7, 1.0 and 1.5. Yellow bars are the number of flights discarded as noise: 130, 68, 18 and 10. Pink bars are noise that is not an injected anomaly: 120, 58, 8 and 0
Figure 3 DBSCAN noise count by eps with min_samples equal to 5

Dimensionality reduction with PCA

Principal component analysis (PCA) rotates the data onto new, uncorrelated axes ordered by how much variance each axis keeps. It is computed by decomposing the covariance matrix, ; the columns of are the directions of the axes (the loadings) and is the variance along axis . The ratio tells how much of the data axis explains (Jolliffe and Cadima, 2016). Standardise first, otherwise a sensor with large units dominates every axis. Choose the number of axes from the cumulative ratio (for example 90%) or from the result of the downstream task. A caution: low variance does not mean unimportant, and the signal of a rare fault often sits on a low-variance axis.

Example 4 How many axes do the 8 sensors of the bottling line need?

Using the same per-minute data, compare PCA on raw values with PCA on standardised values, read the loadings of the first three axes, and see how the number of components affects the reconstruction error and the clustering.

from sklearn.decomposition import PCA
raw = PCA().fit(modes.values)                                                  # PCA on raw values, not standardised
print(f"raw units: PC1 explains {raw.explained_variance_ratio_[0]:.4f} of the variance; loading on speed {raw.components_[0][0]:.3f}")
pca = PCA().fit(Z)
print("standardised: variance ratio " + " ".join(f"{v:.3f}" for v in pca.explained_variance_ratio_))
print("cumulative:   " + " ".join(f"{v:.3f}" for v in np.cumsum(pca.explained_variance_ratio_)))
load = pd.DataFrame(pca.components_[:3], columns=modes.columns, index=["PC1", "PC2", "PC3"]).round(2)
print(load.to_string())
print("components  reconstruction RMSE (std units)  k-means ARI on the components")
for k in (1, 2, 3, 4, 8):
    pk = PCA(k).fit(Z)
    rmse = np.sqrt(((Z - pk.inverse_transform(pk.transform(Z))) ** 2).mean())
    ari = adjusted_rand_score(truth, KMeans(3, n_init=10, random_state=0).fit_predict(pk.transform(Z)))
    print(f"{k:>10}  {rmse:>31.3f}  {ari:>29.3f}")
raw units: PC1 explains 0.9995 of the variance; loading on speed 0.999
standardised: variance ratio 0.563 0.233 0.120 0.054 0.012 0.010 0.004 0.003
cumulative:   0.563 0.796 0.916 0.970 0.982 0.992 0.997 1.000
     speed  conv_amps  torque   vib  bearing_temp  air_bar  fill_sd  water_temp
PC1   0.43       0.46    0.21  0.44          0.46     0.31     0.19        0.16
PC2  -0.08      -0.07    0.61 -0.15         -0.10     0.51    -0.56       -0.04
PC3  -0.25      -0.10    0.12 -0.06         -0.08     0.03     0.18        0.93
components  reconstruction RMSE (std units)  k-means ARI on the components
         1                            0.661                          0.645
         2                            0.452                          0.844
         3                            0.290                          0.852
         4                            0.173                          0.852
         8                            0.000                          0.852

In raw units PC1 explains 99.95% of the variance and has a loading of 0.999 on speed, which is only an effect of units: speed is in the hundreds while the other sensors are in the units to tens. It is not structural information. After standardising, PC1 explains 56.3%, PC2 23.3% and PC3 12.0%, 91.6% for the first three together. The loadings read according to physics. PC1 has similar positive weights on speed, current, vibration and bearing temperature (0.43 to 0.46), so it is the “line load level” axis. PC2 contrasts torque and air pressure (positive) with fill variation (negative), and PC3 is almost entirely water temperature (0.93), an environmental variable unrelated to the line. The effect of the number of components is clear. With 3 axes the reconstruction error is 0.290 standard units and k-means reaches an ARI of 0.852, the same as with all 8 sensors. With 1 axis it reaches only 0.645 and with 2 axes 0.844. PCA therefore compresses the data from 8 dimensions to 3 without losing the information used to separate the modes.

Bar chart of the variance ratio of PC1 to PC8: 0.563, 0.233, 0.120, 0.054, 0.012, 0.010, 0.004 and 0.003, with a pink line for the cumulative sum at 0.563, 0.796, 0.916, 0.970, 0.982, 0.992, 0.997 and 1.000
Figure 4 Variance ratio of the principal components of the bottling-line sensors

t-SNE and UMAP, and their cautions

t-SNE (van der Maaten and Hinton, 2008) projects high-dimensional data into two dimensions while trying to keep close neighbours close. The perplexity sets the neighbourhood size and is usually between 5 and 50. UMAP (McInnes et al., 2018) has a similar goal but is faster. Both are good for looking at structure, but they must be read carefully. Wattenberg et al. (2016) demonstrate that the size of a cluster in a t-SNE plot means nothing, that distances between clusters can mislead, and that several perplexity values should always be tried. Chari and Pachter (2023), in a critique of two-dimensional embeddings of single-cell biology data, make the same point: t-SNE and UMAP should not be used for quantitative interpretation. The next example measures these distortions with numbers (UMAP needs an extra package, so it is not run in this module, but the same cautions apply).

Example 5 t-SNE keeps neighbours but distorts size and distance

Sample 600 minutes from the bottling-line data and embed them with t-SNE at perplexity 5, 30 and 100 and with different seeds. Three things are measured: the size of the changeover cluster relative to the fast-small cluster (mean distance from the centre), the ratio of distances between cluster centres, and trustworthiness, which measures whether the 10 nearest neighbours in the embedding are true neighbours (1 is perfect).

from sklearn.manifold import TSNE, trustworthiness
pick = np.random.default_rng(0).choice(len(truth), 600, replace=False)         # sample 600 minutes so that it runs quickly
Zs, ts = Z[pick], truth[pick]

def geometry(E):
    centre = np.array([E[ts == k].mean(0) for k in range(3)])
    spread = np.array([np.linalg.norm(E[ts == k] - centre[k], axis=1).mean() for k in range(3)])
    dist = lambda a, b: np.linalg.norm(centre[a] - centre[b])
    return spread[2] / spread[0], dist(0, 1) / dist(0, 2), dist(1, 2) / dist(0, 2)

print("embedding            changeover/fast-small spread   d(fast,slow)/d(fast,change)   trustworthiness")
s, r1, r2 = geometry(Zs)
print(f"original (8 sensors) {s:>28.2f}   {r1:>27.2f}   {'-':>15}")
for perp in (5, 30, 100):
    for seed in (0, 1):
        E = TSNE(2, perplexity=perp, init="random", random_state=seed).fit_transform(Zs)
        s, r1, r2 = geometry(E)
        print(f"t-SNE perp {perp:>3}, seed {seed} {s:>28.2f}   {r1:>27.2f}   {trustworthiness(Zs, E, n_neighbors=10):>15.3f}")
embedding            changeover/fast-small spread   d(fast,slow)/d(fast,change)   trustworthiness
original (8 sensors)                         2.49                          0.71                 -
t-SNE perp   5, seed 0                         0.71                          0.98             0.983
t-SNE perp   5, seed 1                         0.73                          0.88             0.984
t-SNE perp  30, seed 0                         0.60                          1.42             0.987
t-SNE perp  30, seed 1                         0.59                          1.27             0.987
t-SNE perp 100, seed 0                         0.71                          2.49             0.983
t-SNE perp 100, seed 1                         0.69                          2.46             0.983

In the original data (standardised) the changeover cluster is 2.49 times wider than the fast-small cluster, yet in the t-SNE plot every setting makes it look narrower (0.59 to 0.73 times), because t-SNE adjusts distances to the local density of each region and so evens out cluster sizes. The true ratio of distances between clusters is 0.71, but the plots give 0.88 to 2.49 depending on perplexity and seed, and even the same perplexity differs (perplexity 30 gives 1.42 and 1.27). Trustworthiness stays at 0.983 to 0.987 in every setting, so close neighbours are always well preserved. The conclusion is that a t-SNE plot can be trusted only for which points lie near which points. Do not read cluster size, distance between clusters or shape, and do not cluster on the t-SNE coordinates without checking against the original features. Always try several perplexities and several seeds.

Two sets of bars. The upper set is the size of the changeover cluster relative to the fast-small cluster: original 2.49, six t-SNE plots 0.59 to 0.73. The lower set is the ratio of distances between clusters: original 0.71, t-SNE plots 0.88, 0.98, 1.27, 1.42, 2.46 and 2.49
Figure 5 Cluster size and between-cluster distance in t-SNE plots against the original data

Module lab

Lab: cluster and reduce the production-line data

  1. Run Example 1 with seed set to your group number, make a table for from 2 to 6 and write which you choose, with reasons from the silhouette, domain knowledge and the ARI (if you have an answer key).
  2. Remove the standardisation before k-means and report how the result changes.
  3. Run Example 2 with 1 to 8 components, look at the BIC and explain why the largest value should not be chosen.
  4. Run Example 3 with finer values of between 0.8 and 1.5 and choose one with reasons. Say who should inspect the flights that are noise.
  5. Run Example 4 on your own data (for example 8 columns from a PLC record or telemetry), check the cumulative variance and write what PC1 and PC2 mean from the loadings.
  6. Run Example 5 with perplexity 2, 15 and 200 and write which conclusions from the plot stay the same in every setting.
  7. Summarise in one page when to use k-means, GMM and DBSCAN on your own production-line data.

Common mistakes

Watch out

  • Not standardising before k-means, DBSCAN or PCA. A sensor with large units dominates the result.
  • Starting k-means once. It gets stuck in a local minimum.
  • Choosing from inertia alone. The value falls every time a cluster is added.
  • Trusting silhouette or BIC without asking the domain. Both criteria assume something about cluster shape.
  • Using k-means on tilted clusters or clusters of very different sizes. Try a GMM.
  • Thinking DBSCAN noise is always an error. It may be a new, rare type.
  • Using one for clusters of different density.
  • Treating low variance as unimportant in PCA. Anomaly signals often sit there.
  • Reading cluster size, distance or shape from a t-SNE or UMAP plot, then clustering on the coordinates in the plot.

Summary

  • k-means minimises inertia by alternating an assignment step and a centre-update step. It needs standardising, several starts, and the assumption of round clusters of similar size.
  • Silhouette and BIC help choose the number of clusters but do not replace domain knowledge, and the two may disagree.
  • A GMM gives elliptical clusters and membership probabilities, chosen with BIC. The covariance structure matters.
  • DBSCAN finds clusters of any shape and returns noise points, but it is sensitive to and min_samples, and noise may be a new type.
  • PCA needs standardising; choose the number of axes from the cumulative variance or the downstream result, and read the loadings with the physics.
  • t-SNE and UMAP preserve close neighbours, but cluster size, distance and shape in the plot cannot be trusted.

Self-check questions

  1. Data points 2, 3, 7, 8, 12 and initial centres 3 and 8. After one assignment step and one centre-update step, what are the new centres?
  2. A point has a mean distance of 2 to the members of its own cluster and 6 to the nearest other cluster. What is its silhouette?
  3. A three-component GMM has a BIC of 10,517 and a four-component one has 10,815. Which do you choose, and why?
  4. Standardised data with 8 variables; the eigenvalues of PC1, PC2 and PC3 are 4.5, 1.8 and 0.9. What cumulative share of the variance do the first three axes explain?
  5. In a t-SNE plot cluster A looks twice as wide as cluster B. Can you conclude that the data in A is twice as spread out?
Answers
  1. Assignments: 2→3, 3→3, 7→8, 8→8, 12→8. The new centres are and .
  2. .
  3. Choose three components, because the lower BIC (10,517 against 10,815) means the fourth component does not add enough likelihood to pay for its extra parameters.
  4. , or 90% (the eigenvalues of standardised data sum to the number of variables).
  5. No. t-SNE adjusts distances to the local density of each region, so cluster size in the plot has no meaning (Example 5 found that a cluster that is truly 2.49 times wider looks narrower). Check against distances in the original data.

Key formulas

k-means objective (inertia)
Silhouette of one point
BIC
DBSCAN neighbourhood
PCA and explained variance ratio

Key references

  1. Géron, A. (2022). Hands-on machine learning with Scikit-Learn, Keras, and TensorFlow (3rd ed.). O'Reilly.
  2. scikit-learn developers. Clustering (scikit-learn 1.9). scikit-learn user guide. link
  3. Arthur, D., & Vassilvitskii, S. (2007). k-means++: The advantages of careful seeding. In Proceedings of the 18th Annual ACM-SIAM Symposium on Discrete Algorithms (pp. 1027–1035). SIAM. link
  4. Rousseeuw, P. J. (1987). Silhouettes: A graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics, 20, 53–65. link
  5. Dempster, A. P., Laird, N. M., & Rubin, D. B. (1977). Maximum likelihood from incomplete data via the EM algorithm. Journal of the Royal Statistical Society: Series B, 39(1), 1–22. link
  6. Schwarz, G. (1978). Estimating the dimension of a model. The Annals of Statistics, 6(2), 461–464. link
  7. Ester, M., Kriegel, H.-P., Sander, J., & Xu, X. (1996). A density-based algorithm for discovering clusters in large spatial databases with noise. In Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining (KDD-96) (pp. 226–231). AAAI Press. link
  8. Schubert, E., Sander, J., Ester, M., Kriegel, H.-P., & Xu, X. (2017). DBSCAN revisited, revisited: Why and how you should (still) use DBSCAN. ACM Transactions on Database Systems, 42(3), Article 19. link
  9. Jolliffe, I. T., & Cadima, J. (2016). Principal component analysis: A review and recent developments. Philosophical Transactions of the Royal Society A, 374(2065), Article 20150202. link
  10. van der Maaten, L., & Hinton, G. (2008). Visualizing data using t-SNE. Journal of Machine Learning Research, 9, 2579–2605. link
  11. Wattenberg, M., Viégas, F., & Johnson, I. (2016). How to use t-SNE effectively. Distill, 1(10), Article e2. link
  12. McInnes, L., Healy, J., & Melville, J. (2018). UMAP: Uniform manifold approximation and projection for dimension reduction. arXiv:1802.03426. link
  13. Chari, T., & Pachter, L. (2023). The specious art of single-cell genomics. PLOS Computational Biology, 19(8), Article e1011288. link

Further reading

Study the assigned knowledge units in advance, review media and take the module quiz

In class / field

Lab or field practice from worksheets with a safety checklist

Learning evidence: Checked worksheets and quiz results

Module quiz

This is a formative self-check, not a graded exam

Knowledge domain: Automation, robotics and swarms · Mathematics, physics and statistics · Programming and digital technology