Skip to content

39. Unsupervised learning — Cheat sheet

The essentials of module 39 on one page. Every runnable block on this page is checked against its output. The blocks run top to bottom and share their variables.

I want to… Use… Key settings
put features on one scale before clustering StandardScaler() (or RobustScaler() with outliers) inside make_pipeline
split rows into k round groups KMeans(n_clusters=k, n_init=10, random_state=42) n_clusters, n_init
cluster millions of rows MiniBatchKMeans(n_clusters=k, random_state=42) batch_size
choose k inertia per k (elbow) + silhouette_score sample_size= for big data
check the stability of k refit on bootstrap samples, compare with adjusted_rand_score 5–20 resamples
describe clusters df.groupby(labels)[cols].mean() + sizes + outside columns original units
build a tree of clusters scipy.cluster.hierarchy.linkage(X, method="ward") method
draw the tree dendrogram(Z, labels=..., color_threshold=...) truncate_mode="lastp"
cut the tree fcluster(Z, t=k, criterion="maxclust") or criterion="distance"
hierarchical clustering in a pipeline AgglomerativeClustering(n_clusters=k, linkage="ward") linkage
find clusters of any shape and noise DBSCAN(eps=..., min_samples=...) eps, min_samples
choose eps k-distance plot: NearestNeighbors(n_neighbors=min_samples) look for the bend
DBSCAN without choosing eps sklearn.cluster.HDBSCAN(min_cluster_size=...) min_cluster_size; no predict
soft cluster probabilities GaussianMixture(n_components=k).predict_proba(X) covariance_type
choose the number of components lowest gmm.bic(X) try several covariance_type
compress correlated features PCA(n_components=0.9) float = variance share
see what a component means pca.components_ as a DataFrame (loadings)
draw a scree plot pca.explained_variance_ratio_ (and .cumsum())
draw a 2-D map of neighbors TSNE(perplexity=30, random_state=42) perplexity
a 2-D map that can place new rows umap.UMAP(random_state=42, n_jobs=1) n_neighbors, min_dist
check a 2-D map sklearn.manifold.trustworthiness(X, emb) n_neighbors
flag anomalies, many features IsolationForest(contamination=0.01, random_state=42) contamination
flag local anomalies LocalOutlierFactor(n_neighbors=20) + fit_predict scale first
score new rows for novelty LocalOutlierFactor(novelty=True) + predict train on clean data
compare two clusterings adjusted_rand_score(a, b) ignores label names
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris, make_blobs, make_moons
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.precision", 3)
X_iris, y_iris = load_iris(return_X_y=True)
X_blobs, y_blobs = make_blobs(
n_samples=300, centers=4, cluster_std=0.9, random_state=42
)
X_scaled = StandardScaler().fit_transform(X_iris) # mean 0, std 1 per column
print(X_scaled.mean(axis=0).round(2) + 0.0, X_scaled.std(axis=0).round(2))
Output
[0. 0. 0. 0.] [1. 1. 1. 1.]
Method Scale first? Why
k-means, agglomerative, DBSCAN, GMM, LOF yes distances: the widest column wins
PCA, t-SNE, UMAP yes, unless all features share one unit (pixels, cm) variance or distances
Isolation Forest no each tree cuts one feature at a time
from sklearn.cluster import KMeans
km = KMeans(n_clusters=4, n_init=10, random_state=42).fit(X_blobs)
print(np.bincount(km.labels_)) # rows per cluster
print(round(km.inertia_, 1), km.n_iter_) # within-cluster sum of squares, passes
print(km.predict([[0.0, 0.0]])) # nearest centroid for a new row
print(km.transform([[0.0, 0.0]]).round(2)) # distance to each centroid
Output
[75 75 75 75]
458.8 3
[2]
[[ 9.37 9.67 5.13 11.4 ]]
Parameter or attribute Meaning
n_clusters k, chosen by you
init="k-means++" default; spread-out starting centroids
n_init runs from different starts; keeps the lowest inertia. Default "auto" = 1 run with k-means++
random_state repeatable starts
labels_ cluster id of each training row
cluster_centers_ centroids, in the (scaled) feature space
inertia_ sum of squared distances to the own centroid
predict(X) / transform(X) nearest centroid / distances to all centroids

Algorithm: start centroids → assign each row to the nearest centroid → move each centroid to the mean of its rows → repeat until no row moves.

from sklearn.metrics import (
calinski_harabasz_score,
davies_bouldin_score,
silhouette_score,
)
rows = []
for k in range(2, 7):
labels = KMeans(n_clusters=k, n_init=10, random_state=42).fit_predict(X_blobs)
rows.append((
k,
silhouette_score(X_blobs, labels), # higher is better, -1..1
davies_bouldin_score(X_blobs, labels), # lower is better, >= 0
calinski_harabasz_score(X_blobs, labels), # higher is better
))
print(pd.DataFrame(rows, columns=["k", "silhouette", "davies_bouldin", "calinski"])
.round(2).to_string(index=False))
Output
k silhouette davies_bouldin calinski
2 0.60 0.51 337.87
3 0.77 0.34 1319.44
4 0.81 0.26 4173.01
5 0.71 0.58 3454.32
6 0.58 0.85 3073.32
Tool Read it as Watch out
Elbow (inertia per k) k where the curve flattens always falls; the elbow is often soft
Silhouette highest mean value; −1 to 1 O(n²); use sample_size
Davies–Bouldin lowest value favors round clusters
Calinski–Harabasz highest value favors round clusters
Bootstrap stability highest mean ARI across resamples slower; most honest
Business sense segments a team can act on the final judge
iris_df = pd.DataFrame(X_iris, columns=["sepal_l", "sepal_w", "petal_l", "petal_w"])
labels = make_pipeline(
StandardScaler(), KMeans(n_clusters=3, n_init=10, random_state=42)
).fit_predict(iris_df)
profile = iris_df.groupby(labels).mean() # means in original units
profile["size"] = np.bincount(labels)
print(profile.round(2))
print((iris_df.groupby(labels).mean() / iris_df.mean()).round(2)) # ratio to overall
Output
sepal_l sepal_w petal_l petal_w size
0 5.80 2.67 4.37 1.41 53
1 5.01 3.43 1.46 0.25 50
2 6.78 3.10 5.51 1.97 47
sepal_l sepal_w petal_l petal_w
0 0.99 0.87 1.16 1.18
1 0.86 1.12 0.39 0.21
2 1.16 1.01 1.47 1.64

Name a cluster after its most extreme ratios (far from 1). Add outside columns (churn, plan, revenue) that the model did not see to show that the segments matter.

from scipy.cluster.hierarchy import fcluster, linkage
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import adjusted_rand_score
Z = linkage(X_scaled, method="ward") # (n - 1) x 4: left, right, distance, size
print(Z.shape, Z[-3:, 2].round(2)) # the last three merge heights
flat = fcluster(Z, t=3, criterion="maxclust") # ids start at 1
agg = AgglomerativeClustering(n_clusters=3, linkage="ward").fit_predict(X_scaled)
print(np.bincount(flat)[1:], adjusted_rand_score(flat, agg)) # same partition
Output
(149, 4) [ 8. 12.64 27.25]
[49 30 71] 1.0
Linkage Cluster distance Gives
ward rise in inertia after the merge compact, similar sizes (Euclidean only)
complete farthest pair compact; outlier-sensitive
average mean of all pairs middle ground
single closest pair long chains; follows curves

Dendrogram: dendrogram(Z, labels=names, orientation="right", color_threshold=h). Cut below a big jump in merge height. Check a tree with cophenet(Z, pdist(X)): the correlation between tree heights and real distances.

from sklearn.cluster import DBSCAN
from sklearn.neighbors import NearestNeighbors
X_moons, y_moons = make_moons(n_samples=300, noise=0.06, random_state=42)
X_moons = StandardScaler().fit_transform(X_moons)
dist, _ = NearestNeighbors(n_neighbors=5).fit(X_moons).kneighbors(X_moons)
print("95th pct of 5-NN distance:", np.percentile(dist[:, -1], 95).round(2))
db = DBSCAN(eps=0.3, min_samples=5).fit(X_moons)
print(sorted(set(db.labels_.tolist())), "core points:", len(db.core_sample_indices_))
Output
95th pct of 5-NN distance: 0.21
[0, 1] core points: 299
Point type Rule Label
core ≥ min_samples points within eps (itself included) cluster id
border fewer, but within eps of a core point cluster id
noise neither -1
  • min_samples: about 2 × the number of features is a common start; larger is more robust to noise.
  • eps: the bend of the sorted k-distance curve (k = min_samples).
  • No predict. To label new rows, train a classifier on the clustered rows.
  • Varying densities: try HDBSCAN(min_cluster_size=...). HDBSCAN (hierarchical DBSCAN) runs DBSCAN over many eps values and keeps the most stable clusters, so it needs no eps. Like DBSCAN, it labels noise -1 and has no predict.
from sklearn.mixture import GaussianMixture
bics = {
k: GaussianMixture(n_components=k, random_state=42).fit(X_iris).bic(X_iris)
for k in range(1, 5)
}
print({k: round(v, 1) for k, v in bics.items()}) # lowest BIC wins
gmm = GaussianMixture(n_components=3, covariance_type="full", random_state=42)
proba = gmm.fit(X_iris).predict_proba(X_iris) # one column per component
print(proba.shape, "uncertain rows:", int((proba.max(axis=1) < 0.9).sum()))
Output
{1: 830.0, 2: 574.0, 3: 580.9, 4: 622.2}
(150, 3) uncertain rows: 3
covariance_type Shape Parameters
full any tilted ellipse most
tied one shared ellipse fewer
diag axis-aligned ellipses fewer
spherical circles (like k-means) fewest

BIC=pln⁡n−2ln⁡L^\text{BIC} = p \ln n - 2 \ln \hat{L}; lower is better. gmm.aic(X) penalizes less. More restarts: n_init=5.

from sklearn.decomposition import PCA
pca = PCA(random_state=42).fit(X_scaled)
print(pca.explained_variance_ratio_.round(3)) # share per component
print(pca.explained_variance_ratio_.cumsum().round(3)) # running total
loadings = pd.DataFrame(pca.components_[:2].T, index=iris_df.columns,
columns=["PC1", "PC2"])
print(loadings.round(2))
print(PCA(n_components=0.95).fit(X_scaled).n_components_) # components for 95%
Output
[0.73 0.229 0.037 0.005]
[0.73 0.958 0.995 1. ]
PC1 PC2
sepal_l 0.52 0.38
sepal_w -0.27 0.92
petal_l 0.58 0.02
petal_w 0.56 0.07
2
Need Code
2-D projection PCA(n_components=2).fit_transform(X_scaled)
keep 90% of variance PCA(n_components=0.9)
back to original space pca.inverse_transform(Z)
reconstruction error ((X - pca.inverse_transform(pca.transform(X))) ** 2).mean()
PCA before clustering make_pipeline(StandardScaler(), PCA(0.9), KMeans(5, n_init=10))
whitened components (unit variance) PCA(whiten=True)

Signs of components are arbitrary; read the pattern of the loadings, not the sign.

import umap
from sklearn.manifold import TSNE, trustworthiness
from threadpoolctl import threadpool_limits
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
with threadpool_limits(limits=1): # t-SNE output depends on the thread count
emb_tsne = tsne.fit_transform(X_scaled)
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=42, n_jobs=1)
emb_umap = reducer.fit_transform(X_scaled)
for name, emb in (("t-SNE", emb_tsne), ("UMAP", emb_umap)):
print(name, emb.shape, round(trustworthiness(X_scaled, emb, n_neighbors=10), 3))
print(reducer.transform(X_scaled[:2]).shape) # UMAP places new rows; t-SNE cannot
Output
t-SNE (150, 2) 0.986
UMAP (150, 2) 0.975
(2, 2)
t-SNE UMAP
Package sklearn.manifold.TSNE umap-learn (import umap)
Main setting perplexity (5–50, below n) n_neighbors (5–50), min_dist (0–0.5)
New rows no transform transform works
Speed slow above ~10,000 rows faster
Repeatable random_state=42, fit inside threadpool_limits(limits=1) random_state=42, n_jobs=1
Read distances between clusters no no
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
rng = np.random.default_rng(42)
X_normal = rng.normal(0, 1, size=(200, 2))
X_odd = np.vstack([X_normal, [[6.0, 6.0], [-5.0, 4.0]]]) # two planted anomalies
iso = IsolationForest(n_estimators=200, contamination=0.01, random_state=42).fit(X_odd)
print(np.flatnonzero(iso.predict(X_odd) == -1)) # -1 = anomaly
print(iso.score_samples(X_odd[-2:]).round(3), round(float(iso.offset_), 3))
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.01)
print(np.flatnonzero(lof.fit_predict(X_odd) == -1))
novel = LocalOutlierFactor(n_neighbors=20, novelty=True).fit(X_normal)
print(novel.predict([[0.0, 0.0], [6.0, 6.0]])) # new rows: 1 normal, -1 novel
Output
[ 69 200 201]
[-0.848 -0.808] -0.666
[ 69 200 201]
[ 1 -1]

Both detectors flag the two planted rows and one normal row (69): 1% of 202 rows is a quota of about 2, rounded up by the threshold. contamination always fills its quota.

Item Isolation Forest LOF
Idea anomalies need few random cuts lower local density than the neighbors
Scale first no yes
Flags fit_predict / predict: -1 anomaly fit_predict only (predict with novelty=True)
Score, lower = stranger score_samples negative_outlier_factor_ (train), score_samples (novelty)
Threshold offset_; decision_function = score_samples - offset_ offset_
contamination expected anomaly share; only moves the threshold same

Outlier detection: the anomalies are in the training data. Novelty detection: train on clean data, score new rows.

Metric Needs true labels Range Use
adjusted_rand_score yes (or a second clustering) about 0 (random) to 1 agreement, ignores label names
normalized_mutual_info_score yes 0 to 1 agreement, information-based
silhouette_score no −1 to 1 separation of the clusters
davies_bouldin_score no ≥ 0, lower better compactness vs separation
trustworthiness no 0 to 1 does a 2-D map keep neighbors?
  • Clustering raw columns: the feature with the biggest numbers decides everything. Scale first.
  • KMeans() with default n_init="auto" runs once; real data can land in a worse local minimum. Use n_init=10.
  • Cluster ids are arbitrary. A rerun with another seed renames them. Compare clusterings with ARI, and map ids to names once.
  • Inertia always falls with k. Never pick k by the lowest inertia.
  • A low silhouette (about 0.2) on behavior data is normal; it means the groups touch, not that they are useless.
  • Do not put the target or ids in the clustering features.
  • fcluster ids start at 1; scikit-learn labels start at 0.
  • Ward linkage is defined for Euclidean distance only.
  • DBSCAN’s -1 is noise, not a cluster. Exclude it when you count clusters.
  • kneighbors(X) on the training data counts each point as its own first neighbor.
  • The lowest BIC is the best density model, not the “true” number of groups.
  • PCA signs are arbitrary; the PCA variance shares depend on scaling.
  • t-SNE and UMAP: gaps and cluster sizes are not distances; t-SNE has no transform; clusters found on a t-SNE map can be artifacts.
  • t-SNE numbers change slightly with the number of CPU threads, even with random_state. Fit inside threadpool_limits(limits=1) for exactly repeatable output.
  • umap.UMAP(random_state=42) alone warns; add n_jobs=1.
  • LocalOutlierFactor().predict fails without novelty=True.
  • contamination sets a quota: with 1% the model always flags 1% of the training rows, even on clean data. On new rows, predict flags whatever scores below offset_.
  • One anomaly model for several machines flags the “different” machine, not the faulty readings. Fit one model per machine or add context features.