Skip to content

39. Unsupervised learning

Modules 35 to 38 trained models to predict a known answer: a house price, a churn flag. Many data sets have no answer column. A shop has 5,000 customers and wants to know which kinds of customers it has. A factory has 2,000 sensor readings and wants to know which ones look wrong. A data set has 64 columns and you want to see it on a screen. This module teaches the tools for these jobs: clustering, dimensionality reduction and anomaly detection. You segment the customers in data/customers.csv, group the products in data/products.csv, map handwritten digits in two dimensions and flag faulty readings in data/sensors.csv.

  • Explain what unsupervised learning is, and why you scale features before any distance-based method.
  • Cluster data with k-means, choose k with the elbow method and the silhouette score, and turn the clusters into named segments with a profile table.
  • Build a hierarchy of clusters with agglomerative clustering, compare linkage types and read a dendrogram.
  • Find clusters of any shape and mark noise with DBSCAN (choose eps with a k-distance plot), and fit Gaussian mixtures for soft assignments (choose the number of components with BIC).
  • Reduce dimensions with PCA (explained variance, scree plot, loadings), and draw 2-D maps with t-SNE and UMAP without misreading them.
  • Detect anomalies with Isolation Forest and the Local Outlier Factor, and set the contamination rate.

The lesson page runs top to bottom in one namespace. The first block fixes the pandas display, loads the customers and picks five behavior columns for segmentation.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
features = [
"tenure_months",
"monthly_charges",
"logins_last_30d",
"avg_session_minutes",
"support_tickets",
]
print(customers[features].agg(["mean", "std", "min", "max"]).round(1).T)
Output
mean std min max
tenure_months 23.1 19.8 0.0 72.0
monthly_charges 60.8 22.9 28.0 143.2
logins_last_30d 11.7 7.9 0.0 60.0
avg_session_minutes 14.3 7.9 1.0 68.1
support_tickets 1.2 1.2 0.0 9.0

The five columns use very different units: months, US dollars, logins, minutes and tickets. Their standard deviations run from about 1 ticket to about 20 months. Keep this in mind; it matters for every method on this page.

In supervised learning (module 18 defined it) each row has a target, and the model learns to predict it. In unsupervised learning there is no target. The algorithm only sees the features, and it looks for structure in them: groups, directions or rare points. Nobody tells it what the right answer is.

Unsupervised learning has three main jobs:

Task Question Algorithms on this page Data example
Clustering Which rows are similar to each other? k-means, hierarchical, DBSCAN, Gaussian mixture customer segments, product families
Dimensionality reduction Can fewer columns keep most of the information? PCA, t-SNE, UMAP a 2-D map of 64-pixel digit images
Anomaly detection Which rows do not look like the rest? Isolation Forest, Local Outlier Factor faulty sensor readings, fraud

Clustering splits the rows into groups, called clusters, so that rows in the same cluster are similar and rows in different clusters are not. Dimensionality reduction replaces many columns with a few new ones. Anomaly detection scores each row by how unusual it is.

Without a target, there is no test-set accuracy. You judge the result in three ways: with internal scores (inertia, silhouette, BIC), with labels that you kept aside (if you have any), and with domain sense: does a person who knows the business find the groups useful? The last check is the one that matters most.

Most methods on this page compare rows by their Euclidean distance (module 32): the straight-line distance between two feature vectors. A column with a large spread dominates this distance. Look at three customers who differ in one column each:

from sklearn.preprocessing import StandardScaler
trio = pd.DataFrame(
{
"tenure_months": [12, 32, 12],
"monthly_charges": [60.0, 60.0, 60.0],
"logins_last_30d": [10, 10, 10],
"avg_session_minutes": [14.0, 14.0, 14.0],
"support_tickets": [1, 1, 4],
},
index=["A", "B", "C"],
)
scaler = StandardScaler().fit(customers[features])
trio_scaled = scaler.transform(trio)
def dist(u, v):
return float(np.linalg.norm(np.asarray(u) - np.asarray(v)))
print("raw: A-B", round(dist(trio.loc["A"], trio.loc["B"]), 2),
" A-C", round(dist(trio.loc["A"], trio.loc["C"]), 2))
print("scaled: A-B", round(dist(trio_scaled[0], trio_scaled[1]), 2),
" A-C", round(dist(trio_scaled[0], trio_scaled[2]), 2))
Output
raw: A-B 20.0 A-C 3.0
scaled: A-B 1.01 A-C 2.56

B has 20 more months of tenure than A. C has 3 more support tickets. In raw units, B looks far away and C looks close, because 20 is a bigger number than 3. But 20 months is about one standard deviation of tenure, and 3 tickets is about two and a half standard deviations of tickets. C is the more unusual customer. After standardization (each column has mean 0 and standard deviation 1), the distances say so.

The rule: scale the features before k-means, hierarchical clustering, DBSCAN, Gaussian mixtures, PCA, t-SNE, UMAP and LOF. StandardScaler is the usual choice. Use RobustScaler when a few extreme values would distort the mean and standard deviation. Tree-based Isolation Forest is the one method here that does not need scaling.

k-means splits the rows into k clusters. Each cluster has a centroid (module 20): the mean of its rows. Every row belongs to the cluster with the nearest centroid. The algorithm repeats two steps until nothing changes:

flowchart TD
    A["Choose k"] --> B["Place k starting centroids<br/>(k-means++)"]
    B --> C["Assign step:<br/>each row joins its<br/>nearest centroid"]
    C --> D["Update step:<br/>move each centroid to<br/>the mean of its rows"]
    D --> E{"Did any row<br/>change cluster?"}
    E -- yes --> C
    E -- no --> F["Done: labels_ and<br/>cluster_centers_"]

Each pass lowers the inertia, also called the within-cluster sum of squares (WCSS): the sum of the squared distances from each row to its own centroid.

inertia=∑i=1n∥xi−μc(i)∥2\text{inertia} = \sum_{i=1}^{n} \lVert x_i - \mu_{c(i)} \rVert^2

Here xix_i is row ii, c(i)c(i) is its cluster and μc(i)\mu_{c(i)} is that cluster’s centroid. A low inertia means tight clusters. k-means tries to make it as small as possible.

Try it on make_blobs, a generator that draws points around a few centers. Four blobs of 75 points each:

from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
X_blobs, y_blobs = make_blobs(
n_samples=300, centers=4, cluster_std=0.9, random_state=42
)
kmeans = KMeans(n_clusters=4, n_init=10, random_state=42)
labels = kmeans.fit_predict(X_blobs)
print("labels:", labels[:12])
print("sizes:", np.bincount(labels))
print("centers:\n", kmeans.cluster_centers_.round(2))
print("inertia:", round(kmeans.inertia_, 1), "iterations:", kmeans.n_iter_)
print("new points ->", kmeans.predict([[0.0, 0.0], [-8.0, 7.0]]))
Output
labels: [3 3 0 1 3 1 2 1 0 2 0 2]
sizes: [75 75 75 75]
centers:
[[-2.65 8.98]
[-6.84 -6.84]
[ 4.71 2.03]
[-8.83 7.2 ]]
inertia: 458.8 iterations: 3
new points -> [2 3]

fit_predict fits the model and returns one label per row. The label numbers are arbitrary names: cluster 2 is not “bigger” than cluster 0, and another seed can number the same clusters differently. predict assigns new rows to the nearest centroid, so a fitted k-means can label tomorrow’s customers too.

Three settings matter:

  • Start positions. The result depends on where the centroids start. The default start, k-means++, picks starting centroids that are far apart. It is much better than random starts, but not perfect.
  • n_init runs the whole algorithm several times from different starts and keeps the run with the lowest inertia. The default n_init="auto" runs it once with k-means++. Pass n_init=10 to be safe; the cost is 10 times the work.
  • random_state=42 fixes the random starts, so you get the same clusters, with the same numbers, every time.

Each single run can get stuck in a local minimum: a solution that no small change improves, but that is not the best one. Here are ten single runs with random starts and ten with k-means++:

for init in ("random", "k-means++"):
runs = [
KMeans(n_clusters=4, init=init, n_init=1, random_state=seed)
.fit(X_blobs)
.inertia_
for seed in range(10)
]
print(f"{init:>9}:", [round(r) for r in runs])
Output
random: [459, 8334, 1970, 1968, 459, 459, 459, 1968, 459, 1968]
k-means++: [459, 459, 459, 459, 459, 459, 459, 459, 459, 459]

Half of the random starts end with an inertia four or more times too high: two true blobs share one centroid, and another blob is cut in two. k-means++ finds the best answer every time on these easy blobs. On real data it fails sometimes too, which is why you set n_init.

k-means has built-in assumptions. It works best when clusters are round, of similar size and similar spread. It always gives exactly k clusters, it puts every row in one of them (outliers too), and it needs numeric, scaled features.

k-means needs k before it starts. Two tools help you choose.

The elbow method plots inertia against k. Inertia always falls when k grows: with one cluster per row it is 0. You look for the elbow, the k after which the curve flattens, because more clusters then buy little.

The silhouette score compares, for each row, how close it is to its own cluster and to the next-nearest cluster. Let a(i)a(i) be the mean distance from row ii to the other rows of its cluster, and b(i)b(i) the mean distance to the rows of the nearest other cluster:

s(i)=b(i)−a(i)max⁡(a(i), b(i))s(i) = \frac{b(i) - a(i)}{\max\big(a(i),\, b(i)\big)}

The value lies between −1 and 1. Near 1: the row sits deep inside its cluster. Near 0: it sits on a border. Below 0: it is probably in the wrong cluster. silhouette_score returns the mean over all rows. Higher is better, and unlike inertia, it does not grow by itself when k grows.

from sklearn.metrics import silhouette_score
ks = range(2, 9)
blob_scores = []
for k in ks:
model = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X_blobs)
blob_scores.append(
(k, model.inertia_, silhouette_score(X_blobs, model.labels_))
)
blob_table = pd.DataFrame(blob_scores, columns=["k", "inertia", "silhouette"])
print(blob_table.round(3).to_string(index=False))
Output
k inertia silhouette
2 9308.011 0.597
3 2009.211 0.768
4 458.754 0.812
5 415.177 0.709
6 372.860 0.577
7 331.247 0.439
8 295.122 0.341
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.5))
ax1.plot(blob_table["k"], blob_table["inertia"], marker="o")
ax1.set(title="Elbow: inertia", xlabel="k", ylabel="inertia")
ax2.plot(blob_table["k"], blob_table["silhouette"], marker="o", color="tab:orange")
ax2.set(title="Silhouette score", xlabel="k", ylabel="mean silhouette")
for ax in (ax1, ax2):
ax.axvline(4, color="gray", linestyle="--", linewidth=1)
fig.tight_layout()
plt.show()
Left: inertia drops steeply from k = 2 to k = 4, then the curve is almost flat up to k = 8. Right: the silhouette score rises to its maximum of about 0.81 at k = 4 and then falls. A dashed line marks k = 4 on both panels.
On clean blobs, both tools agree: the elbow and the silhouette peak are at k = 4.

On these blobs both tools point to k = 4. On real data the elbow is often soft and the silhouette peak is low and flat. Then you choose among a few good values of k with domain sense: which k gives segments that a team can act on? Example 1 shows this on the customers.

A cluster label is a number. A business needs a description: “long-tenure customers with low churn”. You get it with a cluster profile: a table with one row per cluster and the mean (or median) of each feature, in the original units, plus the cluster size. Add columns that the model did not see, such as the churn rate or the plan mix. They show whether the clusters matter for the business.

Then name each cluster after its most distinctive features. Compare each cluster mean with the overall mean: a ratio of 2.2 for support tickets says “this group calls support more than twice as often as the average customer”. A short name such as “Support-heavy” is easier to discuss than “cluster 2”. A segment is a cluster with a name and a business meaning.

Three rules keep the names honest:

  1. Profile with the original units, not the scaled ones. Nobody understands “tenure +1.7”.
  2. Check the sizes. A cluster of 12 customers is not a marketing segment.
  3. Name the clusters after you look at the profile, never before. Clustering does not know what “premium” means.

Hierarchical clustering builds a tree of clusters instead of one flat split. The usual form is agglomerative clustering, which works bottom-up:

  1. Start with every row in its own cluster.
  2. Merge the two closest clusters.
  3. Repeat until one cluster holds all rows.

The tree records every merge and its distance. A dendrogram draws this tree: the leaves at the bottom are the rows, and the height of each join is the distance at which two clusters merged. To get flat clusters, you cut the tree at a height: every branch below the cut becomes one cluster. You can choose k after you see the tree.

“The distance between two clusters” needs a definition. This choice is the linkage:

Linkage Distance between two clusters Effect
ward the increase in inertia if you merge them compact, round clusters of similar size; the usual default (Euclidean only)
complete the largest distance between their members compact clusters; sensitive to outliers
average the mean distance between their members a middle ground
single the smallest distance between their members follows long, thin shapes, but chains: one bridge of points joins two groups

SciPy builds the tree with linkage. Here are the floor areas of six stores from data/stores.csv:

from scipy.cluster.hierarchy import fcluster, linkage
stores = pd.read_csv("data/stores.csv").head(6)
print(stores[["store_id", "city", "size_sqm"]].to_string(index=False))
Z_stores = linkage(stores[["size_sqm"]], method="ward")
merges = pd.DataFrame(Z_stores, columns=["left", "right", "distance", "size"])
print(merges.astype({"left": int, "right": int, "size": int}).round(1))
print("3 clusters:", fcluster(Z_stores, t=3, criterion="maxclust"))
Output
store_id city size_sqm
S01 Chicago 2850
S02 Minneapolis 1950
S03 Detroit 1420
S04 Houston 3100
S05 Atlanta 2300
S06 Miami 1680
left right distance size
0 0 3 250.0 2
1 2 5 260.0 2
2 1 4 350.0 2
3 7 8 813.2 4
4 6 9 1857.5 6
3 clusters: [1 3 2 1 3 2]

The linkage matrix Z has one row per merge (the code shows it as a DataFrame). The first two columns are the ids of the merged clusters: 0 to 5 are the original stores, id 6 is the cluster that the first merge made, id 7 the second, and so on. The third column is the merge distance and the fourth is the size of the new cluster. Chicago (2,850 m²) and Houston (3,100 m²) are only 250 m² apart, so they merge first, into cluster 6. Detroit and Miami (260 m² apart) follow as cluster 7. The last merge joins the two big stores with the four others at a distance of 1,857.5, much higher than the rest: that big jump says “two groups” is a natural cut. fcluster(..., criterion="maxclust") cuts the tree into at most t flat clusters. scikit-learn has AgglomerativeClustering(n_clusters=..., linkage=...) for the same job inside a pipeline; SciPy is the tool for the dendrogram itself.

Hierarchical clustering keeps every pairwise distance in memory, so it suits a few thousand rows at most. Its strength is the tree: you see the structure at every level at once.

k-means draws straight borders between centroids, so it cannot follow curved or stretched clusters. DBSCAN (Density-Based Spatial Clustering of Applications with Noise) defines a cluster as a dense region of points. It needs two settings:

  • eps: the radius of a neighborhood.
  • min_samples: how many points (the point itself included) a neighborhood must hold to count as dense.

Each point then gets one of three roles:

Role Rule Result
Core point at least min_samples points within eps starts or grows a cluster
Border point fewer neighbors, but within eps of a core point joins that core point’s cluster
Noise point neither gets the label -1; belongs to no cluster

A cluster is all core points that you can reach from each other in steps of at most eps, plus their border points. DBSCAN finds the number of clusters by itself and marks outliers as noise. It struggles when clusters have very different densities, because one eps cannot suit them all.

To choose eps, draw a k-distance plot: for every point, compute the distance to its k-th nearest neighbor (k = min_samples), sort these distances and plot them. Points inside clusters have small distances; noise points have large ones. The curve bends sharply upward where the noise starts. Choose eps near that bend. Example 3 does this.

k-means gives each row exactly one cluster: a hard assignment. A Gaussian mixture model (GMM) gives each row a probability for every cluster: a soft assignment. A customer can be 70% “power user” and 30% “regular”.

A GMM assumes that the data comes from k Gaussian (normal) distributions, called components. Each component has a mean, a covariance matrix (how the features spread and move together) and a weight (its share of the rows). The fit uses the expectation–maximization (EM) algorithm, which repeats two steps like k-means: compute each row’s probabilities for each component, then update each component’s mean, covariance and weight from those probabilities.

Because each component has its own covariance, a GMM can fit stretched, tilted, elliptical clusters, where k-means assumes round ones. The covariance_type setting controls the shape:

covariance_type Shape of each component Parameters
"full" any ellipse, any tilt (default) most
"tied" one shared ellipse for all components fewer
"diag" ellipses aligned with the axes fewer
"spherical" circles, as in k-means fewest

To choose the number of components, use the Bayesian information criterion (BIC). It rewards a good fit (a high likelihood L^\hat{L}, module 32) and penalizes the number of parameters pp, for nn rows:

BIC=pln⁡n−2ln⁡L^\text{BIC} = p \ln n - 2 \ln \hat{L}

Lower BIC is better. Fit several models and keep the one with the lowest BIC. The penalty stops you from adding components that only fit noise. GaussianMixture.bic(X) computes it. Example 4 uses it on the iris flowers.

PCA: fewer columns, most of the information

Section titled “PCA: fewer columns, most of the information”

Module 23 built principal component analysis (PCA) from an eigen-decomposition. Here is the ML view. PCA finds new axes, called principal components. The first component is the direction in which the data varies most. The second is the direction of most remaining variance, at a right angle to the first, and so on. Each component is a weighted mix of the original features. Keeping the first few components gives a smaller table that keeps most of the variance.

Three outputs tell you what PCA found:

  • The explained variance ratio: the share of the total variance that each component captures. A scree plot draws these shares (or their running total) against the component number.
  • The loadings: the weights of each original feature in each component (components_). A large positive or negative weight means the feature drives that component.
  • The projection: the rows in the new coordinates (transform). Plot the first two to see the data in 2-D.

PCA is variance-based, so a column in large units dominates. Scale first. Here is PCA on the five scaled customer features:

from sklearn.decomposition import PCA
X_cust = scaler.transform(customers[features])
pca_cust = PCA(random_state=42).fit(X_cust)
print("explained variance ratio:", pca_cust.explained_variance_ratio_.round(3))
print("cumulative:", pca_cust.explained_variance_ratio_.cumsum().round(3))
loadings = pd.DataFrame(
pca_cust.components_[:3].T, index=features, columns=["PC1", "PC2", "PC3"]
)
print(loadings.round(2))
Output
explained variance ratio: [0.265 0.241 0.2 0.159 0.136]
cumulative: [0.265 0.506 0.706 0.864 1. ]
PC1 PC2 PC3
tenure_months 0.00 -0.41 0.81
monthly_charges -0.09 -0.57 -0.58
logins_last_30d 0.70 -0.06 -0.00
avg_session_minutes 0.70 -0.05 -0.08
support_tickets 0.04 0.71 0.00

Read the loadings column by column. PC1 has weights of 0.70 on logins and on session minutes, and almost 0 on the rest: it measures engagement. PC2 puts support tickets (+0.71) against monthly charges (−0.57) and tenure (−0.41). PC3 is mostly tenure (+0.81) against charges (−0.58). The five shares are close to each other (26%, 24%, 20%, 16%, 14%): no direction dominates, so these five features carry fairly separate kinds of information, and you need 4 components for 86% of the variance. On data with strongly correlated columns, such as the digit images in Example 5, a few components capture most of the variance.

A note on signs: PCA can flip the sign of a whole component. PC1 = engagement and PC1 = −engagement describe the same axis. Do not read meaning into the sign alone; read the pattern of the loadings.

PCA is linear: it can only rotate and flatten the data. Groups that are tangled in many dimensions often overlap in a PCA plot. t-SNE (t-distributed Stochastic Neighbor Embedding) is a nonlinear method made for 2-D pictures. It builds a 2-D embedding (a new, low-dimensional set of coordinates for the rows) in which each point keeps the same near neighbors that it had in the original space.

Its main setting is perplexity: roughly, how many neighbors each point pays attention to. Typical values are 5 to 50, and it must be smaller than the number of rows. Small values show fine local detail; large values show more of the global shape.

Read a t-SNE plot with care:

  • Distances between clusters mean little. Two groups far apart on the map may be close in the data. Do not read them.
  • Cluster sizes mean little. t-SNE expands dense groups and shrinks sparse ones.
  • It is random. Another random_state gives a different layout. Always set it.
  • It has no transform. You cannot place new rows on an existing map. Use it to look, not as a model step.
  • It is slow on large data. Keep it to a few thousand rows, or reduce to about 50 dimensions with PCA first.

UMAP: faster maps that can place new points

Section titled “UMAP: faster maps that can place new points”

UMAP (Uniform Manifold Approximation and Projection) has the same goal as t-SNE: a low-dimensional map that keeps the neighbors. It comes from the umap-learn package (import umap). It is usually faster, it keeps more of the global layout, and it has a transform method, so you can place new rows on a fitted map.

Setting Meaning Typical
n_neighbors how many neighbors define the local structure (like perplexity) 5–50, default 15
min_dist how tightly points may pack in the map 0.0–0.5, default 0.1
n_components output dimensions 2 for plots
random_state fixes the layout 42

UMAP normally runs on several CPU cores. A fixed random_state makes it run on one core, because parallel runs cannot repeat exactly. If you set random_state and leave n_jobs at its default, UMAP warns you about this. Pass n_jobs=1 together with random_state=42 to say that you know, and the warning goes away.

The t-SNE caveats apply to UMAP too: sizes and gaps between clusters are not measurements.

Anomaly detection: Isolation Forest and LOF

Section titled “Anomaly detection: Isolation Forest and LOF”

An anomaly (module 18) is a row that does not look like the others: a broken sensor reading, a fraudulent payment. Anomaly detection gives each row a score of how unusual it is. Two methods cover most cases.

An Isolation Forest isolates rows with random cuts. Each tree picks a random feature and a random cut value, again and again, until every row sits alone in a leaf. An unusual row is easy to isolate: a few cuts separate it. A normal row in a dense crowd needs many cuts. The average path length (the number of cuts from the root to the row’s leaf) over many trees is the anomaly score. The model is fast, works on many features and does not need scaling.

The Local Outlier Factor (LOF) compares the density around a row with the density around its neighbors. A row in a sparse spot next to a dense crowd gets a high factor. LOF finds local anomalies: a reading that is normal for the whole data set but odd for its neighborhood. It uses distances, so scale first.

Both methods share one setting, contamination: the share of rows that you expect to be anomalies. The model uses it only to set the threshold between “normal” and “anomaly”. It does not change the scores.

Method fit_predict / predict Score (lower = more unusual) New data
IsolationForest -1 anomaly, 1 normal score_samples, decision_function (score minus threshold) predict works
LocalOutlierFactor fit_predict only, -1 / 1 negative_outlier_factor_ needs novelty=True, then predict

There are two settings for anomaly detection. In outlier detection, the training data itself contains the anomalies and you want to find them: use LocalOutlierFactor() with fit_predict. In novelty detection, you train on clean data and score new rows later: use LocalOutlierFactor(novelty=True) with fit, then predict on the new rows. Isolation Forest does both.

Method You give it Cluster shape Handles noise Scale first Rows Use when
k-means k round, similar sizes no, every row joins a cluster yes millions fast segmentation, a first try
Agglomerative k or a cut height depends on linkage no yes ≤ a few thousand you want the tree, small data
DBSCAN eps, min_samples any shape yes, label -1 yes up to about 100,000 curved shapes, outliers, unknown k
Gaussian mixture k, covariance_type ellipses no yes up to about 100,000 soft assignments, overlapping groups
PCA number of components or a variance share linear no yes millions compress, decorrelate, plot, preprocess
t-SNE perplexity local neighbors no yes ≤ about 10,000 a picture only
UMAP n_neighbors, min_dist local and some global no yes 100,000s a picture, or a nonlinear step with transform
Isolation Forest contamination any it is the point no millions many features, fast anomaly scores
LOF n_neighbors, contamination local density it is the point yes up to about 100,000 local anomalies

Example 1 — Segment subscription customers with k-means

Section titled “Example 1 — Segment subscription customers with k-means”

Goal: The marketing team of the subscription service wants 4 to 6 customer segments with clear names, so that it can write one campaign per segment. Use the five behavior columns of data/customers.csv. The churn flag stays out of the model; it only checks afterward whether the segments matter.

X_seg = StandardScaler().fit_transform(customers[features])
print(X_seg.shape)
print("means:", X_seg.mean(axis=0).round(2) + 0.0) # + 0.0 turns -0.0 into 0.0
print("stds: ", X_seg.std(axis=0).round(2))
Output
(5000, 5)
means: [0. 0. 0. 0. 0.]
stds: [1. 1. 1. 1. 1.]

Every column now has mean 0 and standard deviation 1, so 1 unit of distance means “one standard deviation” in every direction. No column dominates the distances any more.

rows = []
for k in range(2, 11):
model = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X_seg)
rows.append((k, model.inertia_, silhouette_score(X_seg, model.labels_)))
k_table = pd.DataFrame(rows, columns=["k", "inertia", "silhouette"])
print(k_table.round(3).to_string(index=False))
Output
k inertia silhouette
2 20871.906 0.204
3 17715.065 0.174
4 15184.066 0.190
5 13217.303 0.202
6 12052.048 0.211
7 11495.821 0.167
8 10959.468 0.182
9 10423.067 0.176
10 9986.208 0.173

Inertia falls at every step, as it must. The silhouette scores are all low (about 0.17 to 0.21): real customers do not form separate blobs. They form a continuum with denser regions. This is normal for behavior data, and it is the reason why you use more than one score.

Step 3 — Plot the elbow and the silhouette

Section titled “Step 3 — Plot the elbow and the silhouette”
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.5))
ax1.plot(k_table["k"], k_table["inertia"], marker="o")
ax1.set(title="Elbow: inertia", xlabel="k", ylabel="inertia")
ax2.plot(k_table["k"], k_table["silhouette"], marker="o", color="tab:orange")
ax2.set(title="Silhouette score", xlabel="k", ylabel="mean silhouette")
for ax in (ax1, ax2):
ax.axvline(5, color="gray", linestyle="--", linewidth=1)
fig.tight_layout()
plt.show()
Left: inertia falls smoothly from about 20,900 at k = 2 to about 10,000 at k = 10 with no sharp elbow. Right: the silhouette score zigzags between about 0.17 and 0.21, highest at k = 6, with smaller peaks at k = 2 and k = 8. A dashed line marks k = 5.
On real customers the elbow is soft and the silhouette is low. Several k values are defensible.

There is no sharp elbow. The silhouette is highest at k = 6, with k = 2 and k = 5 close behind. Two segments are too few for the team’s goal. k = 5 and k = 6 score almost the same, so the choice comes down to which one gives clearer segments. Look at what the sixth cluster adds.

kmeans_6 = KMeans(n_clusters=6, n_init=10, random_state=42).fit(X_seg)
means_6 = customers.groupby(kmeans_6.labels_)[features].mean()
ratios_6 = means_6 / customers[features].mean()
ratios_6["size"] = np.bincount(kmeans_6.labels_)
ratios_6["churn_rate"] = customers.groupby(kmeans_6.labels_)["churned"].mean()
print(ratios_6.round(2))
Output
tenure_months monthly_charges logins_last_30d avg_session_minutes support_tickets size \
0 2.49 0.94 0.88 0.88 0.83 773
1 0.96 0.94 2.61 1.30 0.83 376
2 0.66 0.85 0.78 0.80 0.42 1462
3 0.87 0.98 1.20 2.08 0.83 506
4 0.80 1.60 0.83 0.84 0.78 838
5 0.60 0.80 0.85 0.86 2.25 1045
churn_rate
0 0.04
1 0.12
2 0.15
3 0.13
4 0.32
5 0.32

Each row is a cluster, and each feature column is the cluster mean divided by the overall mean. At k = 6, the engaged customers split in two: one cluster logs in very often (ratio 2.61 on logins) and one has long sessions (ratio 2.08 on session minutes). Their churn rates are almost the same (about 12% and 13%), so a team would treat them the same way. The extra cluster adds a name but no new action. Exercise M39-X02 adds a second argument: k = 5 gives the most stable clusters across bootstrap samples (mean ARI 0.968, against 0.946 for k = 6). Choose k = 5.

Step 5 — Fit k = 5 and build the profile table

Section titled “Step 5 — Fit k = 5 and build the profile table”
kmeans_seg = KMeans(n_clusters=5, n_init=10, random_state=42).fit(X_seg)
segmented = customers.assign(cluster=kmeans_seg.labels_)
profile = segmented.groupby("cluster")[features].mean()
profile["size"] = segmented["cluster"].value_counts().sort_index()
profile["churn_rate"] = segmented.groupby("cluster")["churned"].mean()
print(profile.round(2))
Output
tenure_months monthly_charges logins_last_30d avg_session_minutes support_tickets \
cluster
0 15.13 52.05 9.22 12.21 0.53
1 57.20 56.95 10.60 13.26 1.00
2 14.07 48.59 10.22 12.60 2.77
3 20.19 58.41 23.82 25.55 1.06
4 18.61 97.56 9.76 12.55 0.95
size churn_rate
cluster
0 1550 0.15
1 819 0.04
2 1087 0.32
3 679 0.13
4 865 0.31

The profile is in the original units, so you can read it. Each cluster stands out in one or two columns. Cluster 1 has an average tenure of 57 months, more than twice the overall 23. Cluster 2 has 2.8 support tickets. Cluster 3 logs in twice as often as the others and stays twice as long. Cluster 4 pays almost 98 USD a month. Cluster 0 is close to average everywhere, with the fewest support tickets.

relative = profile[features] / customers[features].mean()
print(relative.round(2))
names = {
0: "Quiet regulars",
1: "Loyal veterans",
2: "Support-heavy",
3: "Power users",
4: "Premium payers",
}
segmented["segment"] = segmented["cluster"].map(names)
summary = segmented.groupby("segment").agg(
customers=("customer_id", "size"),
churn_rate=("churned", "mean"),
premium_share=("plan", lambda plan: (plan == "premium").mean()),
)
print(summary.sort_values("churn_rate").round(3))
Output
tenure_months monthly_charges logins_last_30d avg_session_minutes support_tickets
cluster
0 0.66 0.86 0.79 0.85 0.43
1 2.48 0.94 0.90 0.92 0.80
2 0.61 0.80 0.87 0.88 2.24
3 0.87 0.96 2.03 1.78 0.85
4 0.81 1.60 0.83 0.88 0.77
customers churn_rate premium_share
segment
Loyal veterans 819 0.044 0.131
Power users 679 0.127 0.122
Quiet regulars 1550 0.146 0.000
Premium payers 865 0.313 0.889
Support-heavy 1087 0.316 0.029

The ratio table makes the names easy: a ratio far from 1 is what makes a segment special. The churn flag was not part of the model, yet the segments differ a lot: loyal veterans churn about 4% of the time, and support-heavy customers and premium payers about 31–32%. The plan mix confirms the “premium” name: almost 90% of premium payers are on the premium plan, a column that k-means never saw. The segments show where churn concentrates, so the team knows where to look: support issues for one group, prices for another. They do not show that an action will lower churn; only a test, such as an A/B test (module 29), can show that.

Step 7 — Draw the segments in 2-D with PCA

Section titled “Step 7 — Draw the segments in 2-D with PCA”
pca_2d = PCA(n_components=2, random_state=42)
coords = pca_2d.fit_transform(X_seg)
print("variance kept by 2 components:", pca_2d.explained_variance_ratio_.sum().round(3))
fig, ax = plt.subplots(figsize=(6.5, 4.5))
for cluster_id, name in names.items():
mask = kmeans_seg.labels_ == cluster_id
ax.scatter(coords[mask, 0], coords[mask, 1], s=6, alpha=0.5, label=name)
ax.set(xlabel="PC1 (engagement)", ylabel="PC2 (tickets vs charges, tenure)")
ax.set_title("Customer segments on the first two principal components")
ax.legend(markerscale=3, fontsize=8)
plt.show()
Output
variance kept by 2 components: 0.506
A scatter plot of 5,000 customers on PC1 and PC2. Power users spread out to the right along PC1. Support-heavy customers sit at the top along PC2. Quiet regulars, premium payers and loyal veterans overlap in the lower left.
Two components keep about half of the variance, so some segments overlap in this view.

Power users separate along PC1 (engagement) and support-heavy customers along PC2. Quiet regulars, premium payers and loyal veterans overlap in the lower left, because they differ mainly in charges and tenure, which PC3 separates (see the loadings in the PCA concept section). A 2-D picture is a summary, not the clustering itself: k-means used all five dimensions.

Common mistakes:

  • Clustering raw columns. Tenure (standard deviation 20) and charges (23) then decide everything, and tickets (1.2) count for almost nothing.
  • Putting the target (churned) or an id column into the features. The segments then describe churn by construction, and the “finding” that they differ in churn is circular.
  • Reading the cluster numbers as an order or comparing them across runs. Map them to names once, after you read the profile.
  • Trusting one score. A silhouette of 0.2 does not mean “no segments”; it means the groups touch. Check the profile and the sizes too.

Example 2 — Group products into families with hierarchical clustering

Section titled “Example 2 — Group products into families with hierarchical clustering”

Goal: The buying team wants to group the 30 products in data/products.csv by how they sell, not by their catalog category. Describe each product with four numbers from data/sales.csv and draw the tree of similarities.

sales = pd.read_csv("data/sales.csv")
products = pd.read_csv("data/products.csv").set_index("product_id")
per_product = sales.groupby("product_id").agg(
lines=("order_id", "size"), mean_qty=("quantity", "mean")
)
items = products[["product", "category", "unit_price", "unit_cost"]].join(per_product)
items["margin_rate"] = 1 - items["unit_cost"] / items["unit_price"]
items["log_price"] = np.log10(items["unit_price"])
item_features = ["log_price", "margin_rate", "lines", "mean_qty"]
print(items[["product"] + item_features].head(6).round(3))
Output
product log_price margin_rate lines mean_qty
product_id
P001 Wireless Earbuds 1.903 0.606 1375 1.128
P002 Noise-Cancelling Headphones 2.396 0.582 856 1.129
P003 55-inch 4K Smart TV 3.114 0.349 427 1.180
P004 14-inch Ultrabook Laptop 3.060 0.321 532 1.126
P005 Smartwatch Series 5 2.301 0.560 752 1.120
P006 Espresso Machine 2.543 0.536 479 1.221

Each product gets four features: its price level, its margin rate, its popularity (number of sales lines) and how many units a buyer takes per line. Prices run from 14.99 to 1,299 USD, a factor of almost 90, so the base-10 logarithm puts them on a fairer scale: 1 means 10 USD, 3 means 1,000 USD.

Step 2 — Build the tree with Ward linkage

Section titled “Step 2 — Build the tree with Ward linkage”
X_items = StandardScaler().fit_transform(items[item_features])
Z_items = linkage(X_items, method="ward")
print(Z_items.shape)
print("last five merge heights:", Z_items[-5:, 2].round(2))
Output
(29, 4)
last five merge heights: [ 3.05 3.79 5.37 6.23 10.68]

30 products need 29 merges, so Z has 29 rows. The last merge heights grow slowly and then jump to 10.68. A jump in merge height means that two clearly different groups were forced together. Cutting just below a jump gives natural clusters.

from scipy.cluster.hierarchy import dendrogram
fig, ax = plt.subplots(figsize=(9, 5))
dendrogram(
Z_items,
labels=items["product"].tolist(),
orientation="right",
color_threshold=5.0,
ax=ax,
)
ax.axvline(5.0, color="gray", linestyle="--", linewidth=1)
ax.set(title="Products by sales profile (Ward linkage)", xlabel="merge distance")
ax.tick_params(axis="y", labelsize=7)
fig.tight_layout()
plt.show()
A horizontal dendrogram of 30 products. A dashed cut line at distance 5 crosses four branches: 15 books, beauty and clothing items; the TV and the laptop; earbuds, yoga mat and bed sheets; and 10 mid-price electronics, home and sports products.
Cutting the tree at distance 5 gives four product families.

Read the tree from the left: products that join early are similar. The dashed line at distance 5 cuts four branches, and color_threshold=5.0 colors each one. The TV and the laptop stay apart from everything until late: they are the only products over 1,000 USD with margins near 33%.

Step 4 — Cut the tree and profile the families

Section titled “Step 4 — Cut the tree and profile the families”
items["family"] = fcluster(Z_items, t=4, criterion="maxclust")
family_profile = items.groupby("family").agg(
products=("product", "size"),
price=("unit_price", "median"),
margin=("margin_rate", "mean"),
lines=("lines", "mean"),
qty=("mean_qty", "mean"),
)
print(family_profile.round(2))
print(pd.crosstab(items["family"], items["category"]))
Output
products price margin lines qty
family
1 15 24.99 0.69 646.0 1.71
2 2 1224.00 0.34 479.5 1.15
3 3 69.99 0.65 1155.0 1.24
4 10 194.99 0.58 611.4 1.27
category Beauty Books Clothing Electronics Home Sports
family
1 5 5 5 0 0 0
2 0 0 0 2 0 0
3 0 0 0 1 1 1
4 0 0 0 2 4 4

The four families have clear names: 1 are cheap, high-margin items bought several at a time (books, beauty, clothing). 2 are the big-ticket electronics. 3 are bestsellers with about 1,150 lines each. 4 are mid-price durables. The crosstab shows that the families cut across the catalog categories: electronics land in three different families. That is the useful insight: the buying team can plan stock by family, not only by category.

from scipy.cluster.hierarchy import cophenet
from scipy.spatial.distance import pdist
pair_dist = pdist(X_items)
earbuds = items.index.get_loc("P001")
for method in ("ward", "complete", "average", "single"):
Z_m = linkage(X_items, method=method)
corr, _ = cophenet(Z_m, pair_dist)
groups = fcluster(Z_m, t=4, criterion="maxclust")
sizes = np.bincount(groups)[1:]
print(f"{method:>8}: cophenetic r = {corr:.3f}, 4-cluster sizes = {sizes}")
mates = items.index[groups == groups[earbuds]].tolist()
print(" with the earbuds (P001):", ", ".join(mates))
Output
ward: cophenetic r = 0.655, 4-cluster sizes = [15 2 3 10]
with the earbuds (P001): P001, P010, P017
complete: cophenetic r = 0.674, 4-cluster sizes = [ 2 10 13 5]
with the earbuds (P001): P001, P010, P014, P015, P017
average: cophenetic r = 0.803, 4-cluster sizes = [ 2 10 13 5]
with the earbuds (P001): P001, P010, P014, P015, P017
single: cophenetic r = 0.765, 4-cluster sizes = [ 2 10 17 1]
with the earbuds (P001): P001

The cophenetic correlation measures how well the tree keeps the original distances: it correlates each pairwise distance with the height at which the two rows first join. Average linkage keeps the distances best (0.803). Complete and average linkage give the same group sizes: they put the three bestsellers (earbuds P001, bed sheets P010, yoga mat P017) in one group with the two cheapest clothing items (socks P014, T-shirts P015). Single linkage chains 17 products into one cluster and leaves the earbuds alone in a cluster of 1, the typical sign of chaining. Ward has the lowest correlation, but its four groups have the clearest business meaning (Step 4). No score decides alone: you want groups that a team can use.

Common mistakes:

  • Plotting a dendrogram of thousands of rows. The leaves become unreadable. Use truncate_mode="lastp", p=30 to show only the last merges, or cluster a sample.
  • Using Ward linkage with a non-Euclidean distance. Ward is defined for Euclidean distance only.
  • Mixing up fcluster criteria. criterion="maxclust" takes a number of clusters; criterion="distance" takes a cut height.

Example 3 — Find curved clusters and noise with DBSCAN

Section titled “Example 3 — Find curved clusters and noise with DBSCAN”

Goal: Two curved groups of points with some scattered noise, made with make_moons, look like customers’ paths through a web app. Show that k-means cuts them wrong, choose eps with a k-distance plot and let DBSCAN find the groups and the noise.

from sklearn.datasets import make_moons
X_moons, y_moons = make_moons(n_samples=300, noise=0.07, random_state=42)
rng = np.random.default_rng(42)
stray = rng.uniform([-1.5, -1.0], [2.5, 1.5], size=(20, 2))
X_shapes = StandardScaler().fit_transform(np.vstack([X_moons, stray]))
print(X_shapes.shape, "moon points:", len(X_moons), "stray points:", len(stray))
Output
(320, 2) moon points: 300 stray points: 20

The two moons are interlocking half circles of 150 points each. 20 uniform random points play the noise. y_moons holds the true moon of each moon point; the clusterers never see it.

from sklearn.metrics import adjusted_rand_score
km_moons = KMeans(n_clusters=2, n_init=10, random_state=42).fit(X_shapes)
ari_km = adjusted_rand_score(y_moons, km_moons.labels_[:300])
print("k-means ARI on the moon points:", round(ari_km, 3))
Output
k-means ARI on the moon points: 0.479

The adjusted Rand index (ARI) compares two labelings of the same rows: 1 means they agree perfectly, about 0 means no better than random. It ignores label names, so cluster 0 versus moon 1 does not matter. You can only compute it when you have true labels, as here. k-means scores about 0.48: it cuts each moon in half with a straight border.

Step 3 — Choose eps with a k-distance plot

Section titled “Step 3 — Choose eps with a k-distance plot”
from sklearn.neighbors import NearestNeighbors
min_samples = 5
neighbors = NearestNeighbors(n_neighbors=min_samples).fit(X_shapes)
distances, _ = neighbors.kneighbors(X_shapes)
k_dist = np.sort(distances[:, -1])
pcts = np.percentile(k_dist, [50, 90, 95, 97, 99]).round(2)
print("percentiles 50/90/95/97/99:", pcts)
fig, ax = plt.subplots(figsize=(6, 3.5))
ax.plot(k_dist)
ax.axhline(0.3, color="gray", linestyle="--", linewidth=1)
ax.set(
title=f"Distance to the {min_samples}th nearest neighbor",
xlabel="points, sorted by distance",
ylabel="k-distance",
)
plt.show()
Output
percentiles 50/90/95/97/99: [0.13 0.21 0.26 0.41 0.84]
A sorted k-distance curve over 320 points. It rises slowly from about 0.05 to about 0.26 over the first 300 points, then bends sharply upward to above 1. A dashed horizontal line at 0.3 sits just below the bend.
The curve bends where the stray points start. eps = 0.3 sits just below the bend.

kneighbors counts the point itself as its first neighbor, so the 5th column is the distance that DBSCAN’s min_samples=5 uses. 95% of the points have a 5th neighbor within about 0.26. Above that, the curve shoots up: those are the stray points. An eps near 0.3 keeps the moons dense and leaves the strays out.

from sklearn.cluster import DBSCAN
dbscan = DBSCAN(eps=0.3, min_samples=min_samples).fit(X_shapes)
db_labels = dbscan.labels_
values, counts = np.unique(db_labels, return_counts=True)
print(dict(zip(values.tolist(), counts.tolist())))
print("core points:", len(dbscan.core_sample_indices_))
ari_db = adjusted_rand_score(y_moons, db_labels[:300])
print("DBSCAN ARI on the moon points:", round(ari_db, 3))
print("stray points marked as noise:", int((db_labels[300:] == -1).sum()), "of 20")
Output
{-1: 10, 0: 156, 1: 154}
core points: 307
DBSCAN ARI on the moon points: 1.0
stray points marked as noise: 10 of 20

DBSCAN finds exactly two clusters without being told k, and it matches the moons perfectly (ARI 1.0). It marks 10 points as noise (label -1). They are all stray points; the other 10 strays happened to land close to a moon and joined it as border or core points. No density-based method can tell them apart: they sit inside the dense region.

fig, axes = plt.subplots(1, 2, figsize=(9, 3.8), sharey=True)
for ax, lab, title in (
(axes[0], km_moons.labels_, "k-means, k = 2"),
(axes[1], db_labels, "DBSCAN, eps = 0.3"),
):
noise = lab == -1
ax.scatter(X_shapes[~noise, 0], X_shapes[~noise, 1], c=lab[~noise], cmap="tab10",
vmin=0, vmax=9, s=12)
ax.scatter(X_shapes[noise, 0], X_shapes[noise, 1], c="black", marker="x", s=30,
label="noise (-1)")
ax.set_title(title)
axes[1].legend(loc="lower left", fontsize=8)
fig.tight_layout()
plt.show()
Left: k-means splits the two interlocking moons with a straight diagonal border, so each color holds half of each moon. Right: DBSCAN colors each moon in one color and marks 10 scattered points with black crosses as noise.
k-means draws straight borders. DBSCAN follows density, so it finds the curved shapes and the noise.

The picture shows why: k-means draws a straight line between two centroids. DBSCAN grows clusters through dense chains of neighbors, so it can follow any shape.

Common mistakes:

  • Running DBSCAN on unscaled data. eps is one radius for all directions, so the features must share a scale.
  • Choosing eps by trial and error on the final picture. Use the k-distance plot with n_neighbors = min_samples.
  • Expecting predict. DBSCAN has only fit_predict and labels_. To label new points, train a classifier (for example KNN) on the clustered points.

Example 4 — Soft clusters of iris flowers with a Gaussian mixture

Section titled “Example 4 — Soft clusters of iris flowers with a Gaussian mixture”

Goal: The iris data (load_iris) has 150 flowers of three species, with four measurements in centimeters. Two species overlap. Fit Gaussian mixtures, let BIC choose the model, and find the flowers whose cluster is uncertain.

from sklearn.datasets import load_iris
from sklearn.mixture import GaussianMixture
iris = load_iris(as_frame=True)
X_iris = iris.data
bic_rows = []
for cov in ("full", "tied", "diag", "spherical"):
for k in range(1, 7):
gmm = GaussianMixture(n_components=k, covariance_type=cov, random_state=42)
bic_rows.append((cov, k, gmm.fit(X_iris).bic(X_iris)))
bic_table = pd.DataFrame(bic_rows, columns=["covariance", "k", "bic"])
print(bic_table.pivot(index="k", columns="covariance", values="bic").round(1))
Output
covariance diag full spherical tied
k
1 1522.1 830.0 1804.1 830.0
2 857.6 574.0 1012.2 688.1
3 744.6 580.9 853.8 633.8
4 705.1 622.2 784.9 618.0
5 701.1 681.5 747.0 607.2
6 697.2 726.1 705.8 625.4

All four measurements are in centimeters, so this example skips scaling. The lowest BIC in the whole table is the full-covariance model with 2 components. BIC only judges how well the model describes the density of the points. Two of the three species overlap so much that one ellipse describes them nearly as well as two, and BIC’s penalty prefers the simpler model. BIC does not know about species.

Step 2 — Fit three components and read the soft assignments

Section titled “Step 2 — Fit three components and read the soft assignments”
gmm_iris = GaussianMixture(n_components=3, covariance_type="full", random_state=42)
gmm_iris.fit(X_iris)
proba = gmm_iris.predict_proba(X_iris)
print("weights:", gmm_iris.weights_.round(3))
print("first row:", proba[0].round(3))
confidence = proba.max(axis=1)
print("flowers with max probability < 0.9:", int((confidence < 0.9).sum()))
uncertain = X_iris.assign(
species=iris.target_names[iris.target], confidence=confidence.round(3)
)
print(uncertain.sort_values("confidence").head(4))
Output
weights: [0.365 0.333 0.301]
first row: [0. 1. 0.]
flowers with max probability < 0.9: 3
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) species \
77 6.7 3.0 5.0 1.7 versicolor
133 6.3 2.8 5.1 1.5 virginica
84 5.4 3.0 4.5 1.5 versicolor
73 6.1 2.8 4.7 1.2 versicolor
confidence
77 0.627
133 0.760
84 0.856
73 0.920

You know there are three species, so fit three components to compare with them. predict_proba gives one probability per component, and each row sums to 1. Most flowers are almost certain (probability near 1). Only 3 have a top probability below 0.9: they sit where the versicolor and virginica ellipses overlap. A hard method such as k-means would hide this doubt.

gmm_labels = gmm_iris.predict(X_iris)
km_iris = KMeans(n_clusters=3, n_init=10, random_state=42).fit_predict(X_iris)
print("GMM ARI: ", round(adjusted_rand_score(iris.target, gmm_labels), 3))
print("k-means ARI:", round(adjusted_rand_score(iris.target, km_iris), 3))
print(pd.crosstab(iris.target_names[iris.target], gmm_labels,
rownames=["species"], colnames=["component"]))
Output
GMM ARI: 0.904
k-means ARI: 0.73
component 0 1 2
species
setosa 0 50 0
versicolor 5 0 45
virginica 50 0 0

The GMM matches the species much better than k-means (ARI 0.90 against 0.73). The versicolor and virginica clusters are long, tilted ellipses. A full covariance matrix can fit that shape; k-means assumes round clusters. The crosstab shows the mistakes: 5 versicolor flowers land in the virginica component. Only one of them (row 77, confidence 0.627) is among the uncertain flowers. The other four sit deep inside the virginica ellipse, and the model is confidently wrong about them. A soft probability measures doubt under the model’s assumptions; it does not measure correctness.

Common mistakes:

  • Reading the lowest BIC as “the true number of groups”. It is the best trade-off between fit and size for this model family. Use it with domain knowledge.
  • Forgetting random_state. EM starts from k-means and can end in a local optimum; pass n_init=5 for more restarts on harder data.
  • Using covariance_type="full" with many features and few rows. Each component then has many parameters to estimate; try "diag" or reduce dimensions with PCA first.

Example 5 — Compress handwritten digits with PCA

Section titled “Example 5 — Compress handwritten digits with PCA”

Goal: load_digits holds 1,797 images of handwritten digits, each 8 × 8 pixels, so each row has 64 features. Find how many components keep most of the information, draw the digits in 2-D and test PCA as a step before clustering.

Step 1 — Fit PCA and draw the scree plot

Section titled “Step 1 — Fit PCA and draw the scree plot”
from sklearn.datasets import load_digits
X_digits, y_digits = load_digits(return_X_y=True)
pca_digits = PCA(random_state=42).fit(X_digits)
ratio = pca_digits.explained_variance_ratio_
cumulative = ratio.cumsum()
print("first five ratios:", ratio[:5].round(3))
for share in (0.5, 0.8, 0.9, 0.95):
needed = np.argmax(cumulative >= share) + 1
print(f"{share:.0%} of variance needs {needed} components")
fig, ax = plt.subplots(figsize=(6.5, 3.5))
ax.bar(range(1, 31), ratio[:30], label="per component")
ax.plot(range(1, 31), cumulative[:30], marker=".", color="tab:orange",
label="cumulative")
ax.axhline(0.9, color="gray", linestyle="--", linewidth=1)
ax.set(title="Scree plot: digits", xlabel="component",
ylabel="explained variance ratio")
ax.legend()
plt.show()
Output
first five ratios: [0.149 0.136 0.118 0.084 0.058]
50% of variance needs 5 components
80% of variance needs 13 components
90% of variance needs 21 components
95% of variance needs 29 components
Bars for components 1 to 30 fall from about 0.15 to below 0.01. The cumulative line rises steeply at first, crosses the dashed 0.9 line at component 21 and flattens toward 1.
The first 21 of 64 components keep 90% of the pixel variance.

The pixel values are strongly correlated: neighboring pixels are usually both ink or both paper. So 21 components hold 90% of the variance of 64 pixels. The digits are not scaled here, because all 64 features are pixel intensities on the same 0–16 scale.

pca90 = PCA(n_components=0.9, random_state=42)
X_digits_90 = pca90.fit_transform(X_digits)
restored = pca90.inverse_transform(X_digits_90)
error = np.mean((X_digits - restored) ** 2)
two = PCA(n_components=2, random_state=42).fit(X_digits)
error_2 = np.mean((X_digits - two.inverse_transform(two.transform(X_digits))) ** 2)
print("shape after PCA:", X_digits_90.shape)
print("reconstruction error, 21 components:", round(float(error), 2))
print("reconstruction error, 2 components: ", round(float(error_2), 2))
baseline = X_digits.var(axis=0).mean() # error when every image is the mean image
print("error of the mean image (0 components):", round(float(baseline), 2))
Output
shape after PCA: (1797, 21)
reconstruction error, 21 components: 1.82
reconstruction error, 2 components: 13.42
error of the mean image (0 components): 18.77

A float between 0 and 1 for n_components means “as many components as this share of the variance needs”. inverse_transform maps the 21 numbers back to 64 pixels. The reconstruction error is the mean squared difference between the original and the rebuilt pixels. Compare it with a baseline: replacing every image with the mean image (0 components) gives the mean pixel variance. 21 components remove about 90% of that error, and 2 components only about 29%: the same shares as the explained variance.

Step 3 — Draw the digits on two components

Section titled “Step 3 — Draw the digits on two components”
coords_digits = PCA(n_components=2, random_state=42).fit_transform(X_digits)
fig, ax = plt.subplots(figsize=(6, 4.5))
points = ax.scatter(coords_digits[:, 0], coords_digits[:, 1], c=y_digits,
cmap="tab10", s=6)
fig.colorbar(points, ax=ax, label="true digit")
ax.set(title="Digits on the first two principal components", xlabel="PC1", ylabel="PC2")
plt.show()
A scatter plot of 1,797 digits colored by their true label. Zeros, threes, fours and sixes form fairly separate regions near the edges, while most other digits overlap in the middle.
Two linear components keep only about 29% of the variance. Many digits overlap.

Two components keep only about 29% of the variance. A few digits separate (0, 3, 4, 6), but most overlap in the middle. A linear 2-D view is too simple for this data. Example 6 uses nonlinear maps.

for name, data in (
("64 pixels", X_digits),
("21 components", X_digits_90),
("2 components", coords_digits),
):
found = KMeans(n_clusters=10, n_init=10, random_state=42).fit_predict(data)
print(f"{name:>13}: ARI = {adjusted_rand_score(y_digits, found):.3f}")
Output
64 pixels: ARI = 0.667
21 components: ARI = 0.673
2 components: ARI = 0.388

k-means on 21 components matches the true digits as well as on all 64 pixels, with a third of the columns. Two components lose too much. PCA before clustering is safe when you keep most of the variance; a 2-D PCA is for pictures, not for clustering.

Common mistakes:

  • Running PCA on unscaled features with different units. The column with the largest numbers wins the first component.
  • Fitting PCA on the whole data before a train/test split in a supervised model. Fit it inside a Pipeline, on the training folds only (module 34).
  • Reading components_ rows as clusters. They are directions, not groups.

Example 6 — Map the digits with t-SNE and UMAP

Section titled “Example 6 — Map the digits with t-SNE and UMAP”

Goal: Draw a 2-D map of 1,000 digit images in which similar images sit together, compare t-SNE and UMAP with PCA, and measure how well each map keeps the neighbors.

from sklearn.manifold import TSNE
from threadpoolctl import threadpool_limits
X_map, y_map = X_digits[:1000], y_digits[:1000]
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
with threadpool_limits(limits=1): # one thread: the same numbers on every machine
emb_tsne = tsne.fit_transform(X_map)
print(emb_tsne.shape, "KL divergence:", round(float(tsne.kl_divergence_), 3))
Output
(1000, 2) KL divergence: 0.558

t-SNE takes only fit_transform: there is no transform for new rows. The KL divergence is the loss that t-SNE minimizes (how different the neighbor probabilities in the map are from those in the data). Use it only to compare runs on the same data.

t-SNE sums its gradients in parallel threads, and the order of these float sums changes the last digits. So even with random_state=42, the exact numbers depend on the number of CPU threads, and a 4-core and an 8-core laptop print slightly different values. threadpool_limits(limits=1) from threadpoolctl (installed with scikit-learn) runs the fit on one thread, so your output matches this page; without it, expect small differences.

import umap
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=42, n_jobs=1)
emb_umap = reducer.fit_transform(X_map)
emb_new = reducer.transform(X_digits[1000:1005])
print(emb_umap.shape, "new rows placed:", emb_new.shape)
Output
(1000, 2) new rows placed: (5, 2)

random_state=42 makes the layout repeatable, and n_jobs=1 states the single-core run that a fixed seed needs, so there is no warning. Unlike t-SNE, the fitted reducer can place new images on the same map with transform.

Step 3 — Draw the three maps side by side

Section titled “Step 3 — Draw the three maps side by side”
emb_pca = PCA(n_components=2, random_state=42).fit_transform(X_map)
fig, axes = plt.subplots(1, 3, figsize=(11, 3.8))
for ax, emb, title in (
(axes[0], emb_pca, "PCA"),
(axes[1], emb_tsne, "t-SNE, perplexity 30"),
(axes[2], emb_umap, "UMAP, 15 neighbors"),
):
ax.scatter(emb[:, 0], emb[:, 1], c=y_map, cmap="tab10", s=5)
for digit in range(10):
cx, cy = np.median(emb[y_map == digit], axis=0)
ax.text(cx, cy, str(digit), fontsize=11, weight="bold")
ax.set_title(title)
ax.set_xticks([])
ax.set_yticks([])
fig.tight_layout()
plt.show()
Three scatter plots of 1,000 digits colored by label, with each digit's number at its median position. PCA shows heavy overlap in the middle. t-SNE shows ten mostly separate islands, one per digit. UMAP shows ten tighter, well-separated islands.
Nonlinear maps separate the digits that PCA mixes. Gaps and sizes on these maps are not distances.

The colors are the true labels, which none of the three methods saw. t-SNE and UMAP put almost every digit in its own island. Do not read the gaps: an island far away from another is not necessarily more different. Both maps keep neighbors, not global distances.

Step 4 — Measure how well each map keeps neighbors

Section titled “Step 4 — Measure how well each map keeps neighbors”
from sklearn.manifold import trustworthiness
for name, emb in (("PCA", emb_pca), ("t-SNE", emb_tsne), ("UMAP", emb_umap)):
score = trustworthiness(X_map, emb, n_neighbors=10)
print(f"{name:>5}: trustworthiness = {score:.3f}")
Output
PCA: trustworthiness = 0.801
t-SNE: trustworthiness = 0.993
UMAP: trustworthiness = 0.989

Trustworthiness (between 0 and 1) checks whether the 10 nearest neighbors of each point on the map were also near neighbors in the 64-pixel space. 1 means no point gained false neighbors. t-SNE and UMAP score close to 1; PCA scores much lower, because in 2-D it squeezes different digits on top of each other.

Common mistakes:

  • Reading cluster distances or sizes on a t-SNE or UMAP map as real distances.
  • Running t-SNE or UMAP once and trusting the layout. Try two perplexities (or n_neighbors values) and two seeds; real structure survives all runs.
  • Clustering a t-SNE map and calling the clusters real. t-SNE can create clumps from noise. Cluster on the features or on PCA components.
  • Setting random_state on UMAP without n_jobs=1. It works, but it writes a warning.

Example 7 — Flag unusual sensor readings with Isolation Forest and LOF

Section titled “Example 7 — Flag unusual sensor readings with Isolation Forest and LOF”

Goal: Sensor S1 in data/sensors.csv sends temperature, humidity and vibration every 10 minutes. Some readings are spikes from a faulty sensor. Flag about 1% of the readings as anomalies, compare two detectors and check the flags against a simple rule.

sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
sensor_cols = ["temperature_c", "humidity_pct", "vibration_mm_s"]
s1 = sensors[sensors["sensor_id"] == "S1"].dropna(subset=sensor_cols)
s1 = s1.reset_index(drop=True)
print(len(s1), "readings")
print(s1[sensor_cols].describe().loc[["mean", "50%", "max"]].round(2))
Output
1989 readings
temperature_c humidity_pct vibration_mm_s
mean 22.05 55.0 2.14
50% 22.02 55.0 2.10
max 38.63 62.7 9.66

Both detectors need complete rows, so the readings with a blank cell are dropped. The maximum temperature and vibration are far above their medians: those are the spikes to find.

from sklearn.ensemble import IsolationForest
iso = IsolationForest(n_estimators=200, contamination=0.01, random_state=42)
s1["iso_flag"] = iso.fit_predict(s1[sensor_cols]) == -1
s1["iso_score"] = iso.score_samples(s1[sensor_cols])
print("flagged:", int(s1["iso_flag"].sum()))
print("threshold (offset_):", round(float(iso.offset_), 3))
top = s1.nsmallest(5, "iso_score")
print(top[["timestamp"] + sensor_cols + ["status", "iso_score"]].to_string(index=False))
Output
flagged: 20
threshold (offset_): -0.614
timestamp temperature_c humidity_pct vibration_mm_s status iso_score
2024-05-11 22:00:00 38.35 56.9 2.02 warn -0.691
2024-05-13 03:40:00 33.33 57.6 2.98 warn -0.690
2024-05-05 23:20:00 20.59 58.6 9.66 warn -0.689
2024-05-03 22:10:00 38.63 56.7 2.02 warn -0.686
2024-05-12 02:20:00 36.45 57.7 1.91 warn -0.681

contamination=0.01 sets the threshold offset_ so that 1% of the training rows fall below it. score_samples is lower for more unusual rows. The top five are four temperature spikes of 33 to 39 °C on a sensor whose median is 22 °C, and one vibration of 9.66 mm/s, more than four times the median of 2.10. No scaling was needed: each tree cuts one feature at a time.

from sklearn.neighbors import LocalOutlierFactor
X_s1 = StandardScaler().fit_transform(s1[sensor_cols])
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.01)
s1["lof_flag"] = lof.fit_predict(X_s1) == -1
s1["lof_score"] = lof.negative_outlier_factor_
print("flagged:", int(s1["lof_flag"].sum()))
print(pd.crosstab(s1["iso_flag"], s1["lof_flag"], rownames=["iso"], colnames=["lof"]))
Output
flagged: 20
lof False True
iso
False 1963 6
True 6 14

LOF uses distances, so the features are scaled first. With the same contamination it flags the same number of rows. The crosstab shows how much the two detectors agree: 14 of the 20 flags are shared. Rows that both detectors flag are the safest to act on first.

Step 4 — Check the flags against a spike rule

Section titled “Step 4 — Check the flags against a spike rule”
rolling_median = s1[sensor_cols].rolling(13, center=True, min_periods=1).median()
s1["rule_spike"] = (
(s1["temperature_c"] - rolling_median["temperature_c"] > 6)
| (s1["vibration_mm_s"] / rolling_median["vibration_mm_s"] > 2.2)
)
print("rule spikes:", int(s1["rule_spike"].sum()))
for col in ("iso_flag", "lof_flag"):
hits = int((s1[col] & s1["rule_spike"]).sum())
print(f"{col}: {hits} of {int(s1[col].sum())} flags are rule spikes")
Output
rule spikes: 14
iso_flag: 13 of 20 flags are rule spikes
lof_flag: 14 of 20 flags are rule spikes

The rule compares each reading with the median of the 13 readings around it (about two hours): a jump of more than 6 °C or a vibration more than 2.2 times the local median is a spike. Both detectors find almost every rule spike without being told the rule. In real work, a person checks a sample of flags; a perfect “truth” column rarely exists.

Step 5 — Inspect where the detector and the rule disagree

Section titled “Step 5 — Inspect where the detector and the rule disagree”
show = ["timestamp"] + sensor_cols
extra = s1[s1["iso_flag"] & ~s1["rule_spike"]]
missed = s1[~s1["iso_flag"] & s1["rule_spike"]]
print("flagged, not a rule spike:")
print(extra[show].to_string(index=False))
print("rule spike, not flagged:")
print(missed[show].to_string(index=False))
q02 = s1["temperature_c"].quantile(0.02)
print("2% quantile of temperature:", round(float(q02), 2))
Output
flagged, not a rule spike:
timestamp temperature_c humidity_pct vibration_mm_s
2024-05-01 14:50:00 24.91 48.6 2.55
2024-05-03 01:40:00 19.10 60.9 3.24
2024-05-09 04:10:00 18.89 61.9 2.49
2024-05-10 04:50:00 18.90 62.5 2.15
2024-05-11 02:30:00 18.62 61.0 2.70
2024-05-14 02:10:00 18.90 59.5 3.00
2024-05-14 02:20:00 18.91 59.2 3.38
rule spike, not flagged:
timestamp temperature_c humidity_pct vibration_mm_s
2024-05-06 16:30:00 34.71 52.0 2.03
2% quantile of temperature: 19.15

Six of the 7 extra flags are night readings between 18.6 and 19.1 °C, among the coldest 2% of all readings (the 2% quantile is 19.15 °C), with high humidity (59 to 62.5%). The seventh is an afternoon peak of 24.9 °C with low humidity. These are rare but real values, not faults. The one rule spike that the model misses is 34.7 °C at 16:30, the warmest time of day, where a high value is less surprising to a model that does not know the time.

Step 6 — Plot the flagged readings over time

Section titled “Step 6 — Plot the flagged readings over time”
fig, axes = plt.subplots(2, 1, figsize=(9, 5), sharex=True)
for ax, col in zip(axes, ["temperature_c", "vibration_mm_s"], strict=True):
ax.plot(s1["timestamp"], s1[col], linewidth=0.6, color="tab:blue")
flagged = s1[s1["iso_flag"]]
ax.scatter(flagged["timestamp"], flagged[col], color="tab:red", s=18,
label="Isolation Forest flag", zorder=3)
ax.set_ylabel(col)
axes[0].legend(loc="upper left", fontsize=8)
axes[0].set_title("Sensor S1: readings flagged as anomalies")
fig.autofmt_xdate()
fig.tight_layout()
plt.show()
Two stacked time series for sensor S1 over two weeks in May 2024. Temperature follows a daily cycle between about 19 and 25 °C. Six sharp spikes above 29 °C are marked in red, one spike near 35 °C on May 6 is not, and several red points sit on daily lows. Vibration stays near 2 mm/s with seven red-marked spikes between 6 and 10 mm/s.
Isolation Forest flags the temperature and vibration spikes without any labels.

The red points sit on the spikes in both series. Some flags sit on normal-looking temperatures: those rows have a vibration spike at the same time, which shows only in the lower panel. The flags at the bottom of the temperature panel are the cold night readings from Step 5. The thin spike on May 6 without a red point is the missed reading. Adding the hour of the day as a feature would help: the model could then learn what is normal at each time of day. Exercise M39-X03 tries this.

Common mistakes:

  • Setting contamination far above the real anomaly rate. The model then flags normal rows to reach the quota. Start with a domain estimate, then look at the score distribution.
  • Calling lof.predict after a plain LocalOutlierFactor(). It raises an error; use fit_predict, or novelty=True to score new data.
  • Fitting one detector on all four sensors at once. Each sensor has its own normal level (S4 vibrates more), so a pooled model flags whole sensors. Fit one model per sensor, or add features that describe the context.
Mistake Symptom Fix
Clustering or running PCA on unscaled features One column (tenure, charges, price) decides every cluster or the first component StandardScaler (or RobustScaler) first, inside a Pipeline
KMeans() with the default n_init="auto" on real data Different runs give different clusters and inertias n_init=10, random_state=42
Choosing k by inertia alone Inertia always falls, so “more clusters is better” Use the elbow together with the silhouette and the profile table
Reading cluster ids as names or an order “Cluster 2” means something else after a rerun Map ids to names once, from the profile
Putting the target or an id in the features Segments “explain” churn by construction Cluster on behavior; use the target only to check segments afterward
DBSCAN with a guessed eps Everything is noise (-1) or everything is one cluster k-distance plot with n_neighbors = min_samples
Lowest BIC read as “the true number of groups” BIC picks 2 iris components for 3 species Use BIC with domain knowledge; check the profile
Reading gaps and sizes on a t-SNE or UMAP map False conclusions about which groups are similar Read only “who is next to whom”; check with two seeds and two settings
umap.UMAP(random_state=42) alone UserWarning: n_jobs value 1 overridden to 1 by setting random_state Add n_jobs=1
LocalOutlierFactor().predict(X_new) AttributeError fit_predict on the same data, or novelty=True for new data
contamination far above the real anomaly rate Many normal rows flagged Start from a domain estimate; inspect score_samples
One anomaly model for several machines with different normal levels A whole machine flagged as anomalous One model per machine, or add context features
  • Web and product analytics: user sessions are clustered into behavior types (browsers, buyers, bouncers) to design pages and onboarding flows.
  • Security and operations: Isolation Forest scores logins, API calls and server metrics. An unusual combination of country, hour and request rate triggers an alert.
  • Search and recommendations: UMAP and PCA compress text or image embeddings for fast “more like this” lookups and for 2-D maps of a document collection.
  • Image tools: k-means on pixel colors reduces an image to a few colors (color quantization) for thumbnails and palette pickers.
  • Unsupervised learning finds structure without a target: clusters, low-dimensional maps and anomalies. You judge it with internal scores, held-back labels and, most of all, domain sense.
  • Scale features before every distance- or variance-based method. Isolation Forest is the exception.
  • k-means alternates “assign to the nearest centroid” and “move the centroid to the mean”. Set n_init=10 and random_state=42. Choose k with the elbow, the silhouette and the profile table.
  • A profile table of cluster means in original units, plus sizes and outside columns such as churn, turns clusters into named segments.
  • Agglomerative clustering builds a tree; the linkage defines cluster distance. A dendrogram shows every level; fcluster cuts it.
  • DBSCAN finds dense regions of any shape and labels noise -1. Choose eps with a k-distance plot.
  • Gaussian mixtures give soft probabilities and fit ellipses. Choose the number of components with the lowest BIC, then sanity-check.
  • PCA gives uncorrelated components ordered by variance. Read the explained variance ratio, the scree plot and the loadings. Keep 80–95% of the variance before clustering.
  • t-SNE and UMAP draw neighbor-preserving 2-D maps. Gaps and sizes are not distances. UMAP needs n_jobs=1 with random_state.
  • Isolation Forest isolates anomalies with few random cuts; LOF compares local densities. contamination only sets the threshold.

Q1. What is the difference between supervised and unsupervised learning? Give one data example of each unsupervised task.

Answer

Supervised learning has a target column and learns to predict it. Unsupervised learning has only features and looks for structure in them. Examples: clustering customers into segments, reducing 64 pixel columns to a 2-D map, and flagging faulty sensor readings as anomalies.

Q2. Customer A and customer B differ by 20 months of tenure; A and C differ by 3 support tickets. Without scaling, which pair does k-means treat as closer, and why is that a problem?

Answer

A and C, because 3 is smaller than 20. But tenure has a standard deviation of about 20 months and tickets about 1.2, so 3 tickets is the bigger difference in behavior. Without scaling, the column with the largest spread dominates every distance. Standardize first.

Q3. What do the two steps of k-means do, and what does n_init=10 add?

Answer

The assign step puts each row in the cluster of its nearest centroid. The update step moves each centroid to the mean of its rows. They repeat until no row changes cluster. n_init=10 runs the whole algorithm from 10 different starts and keeps the run with the lowest inertia, which protects against a bad local minimum.

Q4. Why can you not choose k by picking the k with the lowest inertia?

Answer

Inertia always falls when k grows. With one cluster per row it is 0. You look for the elbow, where extra clusters stop paying off, and use the silhouette score, which does not grow by itself with k.

Q5. A row has a silhouette value of −0.2. What does that say?

Answer

Its mean distance to its own cluster is larger than its mean distance to the nearest other cluster. It is probably in the wrong cluster, or it sits between two clusters.

Q6. When does DBSCAN beat k-means? What does the label -1 mean?

Answer

When the clusters have curved or irregular shapes, when the number of clusters is unknown and when the data has outliers. DBSCAN follows dense regions instead of drawing straight borders between centroids. -1 marks noise: points that are neither core points nor within eps of one.

Q7. What does a Gaussian mixture give that k-means does not? How do you pick its number of components?

Answer

Soft assignments: a probability for each component (predict_proba), and elliptical clusters through each component’s covariance matrix. Fit several numbers of components (and covariance types) and keep the model with the lowest BIC, then check that the result makes sense.

Q8. PCA on scaled customer features gives explained variance ratios of 0.27, 0.24, 0.20, 0.16 and 0.14. PCA on digit pixels needs 21 of 64 components for 90%. What does the difference tell you?

Answer

The customer features are weakly correlated, so each one carries separate information and PCA cannot compress them much. The pixels are strongly correlated (neighboring pixels move together), so a few components capture most of the variance.

Q9. A t-SNE map shows the cluster of digit 0 far from the cluster of digit 6. Can you conclude that zeros and sixes are very different?

Answer

No. t-SNE keeps local neighbors, not distances between clusters. Gaps and cluster sizes on the map are not measurements. Check distances in the original space, or with PCA.

Q10. What does contamination=0.01 change in an Isolation Forest, and what does it not change?

Answer

It sets the threshold (offset_) so that 1% of the training rows are labeled -1. It does not change the anomaly scores from score_samples, so the ranking of rows from most to least unusual stays the same.

Q11. You want to score tomorrow’s sensor readings with a LOF trained on today’s clean readings. How do you set it up?

Answer

Create LocalOutlierFactor(novelty=True), fit it on the clean, scaled training readings, then call predict (or score_samples) on the new readings, scaled with the same fitted scaler. Without novelty=True, LOF has only fit_predict on its training data.

Your progress

0 / 4 done

  • Exercises: 28 exercises with hints and full solutions, from warm-up to challenge.
  • Mini-project: build an anomaly watch for the whole sensor fleet.
  • Cheat sheet: every clusterer, reducer and detector of this module with its key settings.
  • Next module: 40. Time series works with time-indexed data: resampling, decomposition, lag features and forecasting.