Skip to content

Unsupervised learning

Unsupervised learning finds structure without a target: groups of rows (clustering), a smaller set of columns (dimensionality reduction) and rows that do not fit (anomaly detection). This page covers the scikit-learn, SciPy and umap-learn tools for all three, how to choose their settings and how to check the result. The examples use data/customers.csv, data/sensors.csv and small synthetic sets. The blocks share one session:

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris, 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)
customers = pd.read_csv("data/customers.csv")
behavior = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "avg_session_minutes"]
X_cust = StandardScaler().fit_transform(customers[behavior]) # scale before distances
X_iris = StandardScaler().fit_transform(load_iris().data)
print(X_cust.shape, X_iris.shape)
Output
(5000, 5) (150, 4)
I want to… Use… Notes
put columns on one scale before distances StandardScaler() (RobustScaler() with outliers) first step of the pipeline
split rows into k round groups KMeans(n_clusters=k, n_init=10, random_state=42) default n_init="auto" runs once
cluster millions of rows MiniBatchKMeans(n_clusters=k, random_state=42) batch_size=
choose k silhouette_score per k + elbow of inertia_ sample_size= for big data
check that k is stable refit on bootstrap samples, adjusted_rand_score 5–20 resamples
describe each cluster df.groupby(labels)[cols].mean() + sizes original units, not scaled
label new rows (k-means) km.predict(X_new) nearest centroid
build a tree of merges scipy.cluster.hierarchy.linkage(X, method="ward") (n - 1) x 4 array
draw the tree dendrogram(Z, truncate_mode="lastp", p=20) Matplotlib
cut the tree into k groups fcluster(Z, t=k, criterion="maxclust") ids start at 1
hierarchical clustering in a pipeline AgglomerativeClustering(n_clusters=k, linkage="ward") fit_predict only
clusters of any shape, plus noise DBSCAN(eps=0.3, min_samples=5) noise label -1
choose eps k-distance curve: NearestNeighbors(n_neighbors=min_samples) the bend
density clusters without eps HDBSCAN(min_cluster_size=15) sklearn.cluster; no predict
label new rows after DBSCAN or HDBSCAN fit a classifier (k-NN) on the clustered rows noise rows excluded
soft cluster probabilities GaussianMixture(n_components=k).predict_proba(X) rows sum to 1
choose the number of mixture components lowest gmm.bic(X) try several covariance_type
keep 90% of the variance in fewer columns PCA(n_components=0.9) float = variance share
read what a component means pca.components_ as a DataFrame (loadings) signs are arbitrary
a scree plot pca.explained_variance_ratio_ and .cumsum()
a 2-D map of neighbors (picture only) TSNE(perplexity=30, random_state=42) no transform
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 trustworthiness(X, emb, n_neighbors=10) 1 = neighbors kept
repeatable t-SNE numbers fit inside threadpool_limits(limits=1) threadpoolctl
flag anomalies fast, many columns IsolationForest(contamination=0.01, random_state=42) no scaling needed
flag local anomalies LocalOutlierFactor(n_neighbors=20).fit_predict(X) scale first
score new rows against clean data LocalOutlierFactor(novelty=True).fit(X_clean) then predict
a continuous anomaly score score_samples(X) lower = stranger
compare two clusterings adjusted_rand_score(a, b) ignores label names
compare a clustering with true labels adjusted_rand_score, normalized_mutual_info_score
Method You give it Cluster shape Noise label Scale first predict new rows Size
KMeans k round, similar sizes no yes yes millions
AgglomerativeClustering / linkage k or a cut height depends on linkage no yes no a few thousand
DBSCAN eps, min_samples any -1 yes no ~100,000
HDBSCAN min_cluster_size any, varying density -1 yes no ~100,000
GaussianMixture k, covariance_type ellipses no yes yes (+ probabilities) ~100,000
PCA components or a variance share linear — yes transform millions
TSNE perplexity local neighbors — yes no ~10,000
umap.UMAP n_neighbors, min_dist local + some global — yes transform 100,000s
IsolationForest contamination any -1 = anomaly no yes millions
LocalOutlierFactor n_neighbors, contamination local density -1 = anomaly yes only with novelty=True ~100,000

A first pass on tabular data: scale, run KMeans for k = 2…8, read the silhouette and the profiles. Try HDBSCAN when the groups are not round or when noise matters. Use a GaussianMixture when rows can belong to two groups.

from sklearn.cluster import KMeans
from sklearn.metrics import davies_bouldin_score, silhouette_score
rows = []
for k in range(2, 8):
km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X_cust)
sil = silhouette_score(X_cust, km.labels_, sample_size=2000, random_state=42)
rows.append((k, km.inertia_, sil, davies_bouldin_score(X_cust, km.labels_)))
scores = pd.DataFrame(rows, columns=["k", "inertia", "silhouette", "davies_bouldin"])
print(scores.round(3).to_string(index=False))
Output
k inertia silhouette davies_bouldin
2 20871.906 0.202 2.010
3 17715.065 0.172 1.732
4 15184.066 0.193 1.490
5 13217.303 0.204 1.357
6 12052.048 0.212 1.366
7 11495.821 0.167 1.569
Tool Best k Watch out
Elbow of inertia_ where the drop flattens always falls with k; the bend is often soft
silhouette_score highest, −1 to 1 O(n²): pass sample_size= and random_state=
davies_bouldin_score lowest, ≥ 0 favors round clusters
calinski_harabasz_score highest favors round clusters
Bootstrap ARI most stable across resamples slower, most honest
Profiles groups a team can act on the final judge

On behavior data the silhouette is often 0.2–0.3: the groups touch. That is normal. Here the silhouette is flat and Davies–Bouldin is lowest at k = 5, so the next block uses 5. Pick k from the scores and the profiles together.

km = KMeans(n_clusters=5, n_init=10, random_state=42).fit(X_cust)
profile = customers.groupby(km.labels_)[behavior].mean() # original units
profile["size"] = np.bincount(km.labels_)
profile["churn_rate"] = customers.groupby(km.labels_)["churned"].mean() # not a feature
print(profile.round(2).T) # one column per cluster
print(km.predict(X_cust[:3]), km.transform(X_cust[:1]).round(2)) # new rows, distances
Output
0 1 2 3 4
tenure_months 15.13 57.20 14.07 20.19 18.61
monthly_charges 52.05 56.95 48.59 58.41 97.56
support_tickets 0.53 1.00 2.77 1.06 0.95
logins_last_30d 9.22 10.60 10.22 23.82 9.76
avg_session_minutes 12.21 13.26 12.60 25.55 12.55
size 1550.00 819.00 1087.00 679.00 865.00
churn_rate 0.15 0.04 0.32 0.13 0.31
[1 1 1] [[3.4 1.87 4.18 3.64 3.03]]
Parameter or attribute Meaning
n_clusters k
init="k-means++" default: spread-out start centroids
n_init=10 10 starts; keeps the lowest inertia
max_iter=300 passes per start
labels_, cluster_centers_ cluster per training row; centroids in scaled space
inertia_ sum of squared distances to the own centroid
predict(X) / transform(X) nearest centroid / distance to every centroid
scaler.inverse_transform(km.cluster_centers_) centroids in original units

Name a cluster after the columns that differ most from the overall mean. Columns the model did not see, such as churned above, show whether the segments matter.

from scipy.cluster.hierarchy import cophenet, fcluster, linkage
from scipy.spatial.distance import pdist
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import adjusted_rand_score
Z = linkage(X_iris, method="ward") # rows: left id, right id, height, size
print(Z.shape, Z[-4:, 2].round(2)) # the last merges: cut below a big jump
tree_ids = fcluster(Z, t=3, criterion="maxclust") # 1-based ids
agg = AgglomerativeClustering(n_clusters=3, linkage="ward").fit_predict(X_iris)
print(np.bincount(tree_ids)[1:], adjusted_rand_score(tree_ids, agg))
print(round(cophenet(Z, pdist(X_iris))[0], 3)) # tree heights vs real distances
Output
(149, 4) [ 6.61 8. 12.64 27.25]
[49 30 71] 1.0
0.823
Linkage Distance between two clusters Result
ward rise in within-cluster variance compact, similar sizes; Euclidean only
complete farthest pair compact; sensitive to outliers
average mean over all pairs a middle ground; any metric
single closest pair long chains; follows curves
Cut Code
into k clusters fcluster(Z, t=k, criterion="maxclust")
at a height fcluster(Z, t=h, criterion="distance")
draw it dendrogram(Z, labels=names, color_threshold=h, orientation="right")
big trees dendrogram(Z, truncate_mode="lastp", p=20)
from sklearn.cluster import DBSCAN, HDBSCAN
from sklearn.neighbors import NearestNeighbors
X_moons = StandardScaler().fit_transform(
make_moons(n_samples=300, noise=0.08, random_state=42)[0]
)
dist, _ = NearestNeighbors(n_neighbors=5).fit(X_moons).kneighbors(X_moons)
print("k-distance, 90th/99th pct:", np.percentile(dist[:, -1], [90, 99]).round(2))
db = DBSCAN(eps=0.3, min_samples=5).fit(X_moons)
hdb = HDBSCAN(min_cluster_size=15, copy=True).fit(X_moons) # copy= avoids a warning
for name, labels in (("DBSCAN", db.labels_), ("HDBSCAN", hdb.labels_)):
n_clusters = len(set(labels.tolist()) - {-1}) # -1 is noise, not a cluster
print(name, "clusters:", n_clusters, "noise:", int((labels == -1).sum()))
Output
k-distance, 90th/99th pct: [0.22 0.31]
DBSCAN clusters: 2 noise: 0
HDBSCAN clusters: 2 noise: 7

Neither model can label new rows:

db.predict(X_moons[:2])
Output
AttributeError: 'DBSCAN' object has no attribute 'predict'

Train a classifier on the clustered rows instead:

from sklearn.neighbors import KNeighborsClassifier
kept = db.labels_ != -1 # drop the noise rows
knn = KNeighborsClassifier(n_neighbors=5).fit(X_moons[kept], db.labels_[kept])
print(knn.predict(X_moons[:5]), db.labels_[:5])
Output
[0 0 0 1 0] [0 0 0 1 0]
Setting Model Rule of thumb
eps DBSCAN the bend of the sorted k-distance curve (k = min_samples)
min_samples both about 2 × the number of features; larger = more noise
min_cluster_size HDBSCAN the smallest group you care about
metric both "euclidean" default; "cosine" for text vectors
Point type (DBSCAN) Rule Label
core ≥ min_samples points within eps, itself included cluster id
border within eps of a core point cluster id
noise neither -1

HDBSCAN (hierarchical DBSCAN) tries every eps and keeps the most stable clusters. It handles clusters of different densities. hdb.probabilities_ gives each row’s membership strength.

from sklearn.mixture import GaussianMixture
bic = {
(k, cov): GaussianMixture(k, covariance_type=cov, random_state=42).fit(X_iris)
.bic(X_iris)
for k in (2, 3, 4)
for cov in ("full", "diag")
}
print(min(bic, key=bic.get), round(min(bic.values()), 1)) # lowest BIC wins
gmm = GaussianMixture(n_components=3, random_state=42).fit(X_iris)
proba = gmm.predict_proba(X_iris) # one column per component, rows sum to 1
print(proba[:2].round(3), "unsure rows:", int((proba.max(axis=1) < 0.9).sum()))
Output
(2, 'full') 794.7
[[0. 1. 0.]
[0. 1. 0.]] unsure rows: 1
covariance_type Shape per component Parameters
"full" (default) any tilted ellipse most
"tied" one shared ellipse fewer
"diag" axis-aligned ellipses fewer
"spherical" circles, like k-means fewest

BIC picks 2 components here for the 3 iris species: two species overlap. BIC =pln⁡n−2ln⁡L^= p \ln n - 2 \ln \hat{L}, lower is better; aic penalizes less. Add n_init=5 for more restarts. gmm.score_samples(X) is a log density: low values are unusual rows.

from sklearn.decomposition import PCA
pca = PCA().fit(X_cust)
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=behavior, columns=["PC1", "PC2"])
print(loadings.round(2))
print(PCA(n_components=0.8).fit(X_cust).n_components_) # components for 80%
Output
[0.265 0.241 0.2 0.159 0.136]
[0.265 0.506 0.706 0.864 1. ]
PC1 PC2
tenure_months 0.00 -0.41
monthly_charges -0.09 -0.57
support_tickets 0.04 0.71
logins_last_30d 0.70 -0.06
avg_session_minutes 0.70 -0.05
4
Need Code
a 2-D projection PCA(n_components=2).fit_transform(X_scaled)
keep a variance share PCA(n_components=0.9)
back to the original space pca.inverse_transform(Z)
reconstruction error (anomaly score) ((X - pca.inverse_transform(pca.transform(X))) ** 2).sum(axis=1)
PCA before a model make_pipeline(StandardScaler(), PCA(0.9), KMeans(4, n_init=10))
sparse input (text) TruncatedSVD(n_components=100): no centering, any sparse size; PCA accepts sparse input only with the arpack or covariance_eigh solver (the default "auto" picks one)
unit-variance components PCA(whiten=True)

The five behavior columns are almost uncorrelated, so PCA needs 4 of 5 components for 80% of the variance. PCA compresses only correlated columns. PCA finds linear directions of maximum variance. The variance shares depend on the scaling, and the signs of the loadings can flip between versions. Read the pattern, not the sign.

import umap
from sklearn.manifold import TSNE, trustworthiness
from threadpoolctl import threadpool_limits
with threadpool_limits(limits=1): # t-SNE output depends on the thread count
emb_tsne = TSNE(perplexity=30, random_state=42).fit_transform(X_iris)
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=42, n_jobs=1)
emb_umap = reducer.fit_transform(X_iris) # random_state needs n_jobs=1
for name, emb in (("t-SNE", emb_tsne), ("UMAP", emb_umap)):
print(name, emb.shape, round(trustworthiness(X_iris, emb, n_neighbors=10), 3))
print(reducer.transform(X_iris[:2]).shape) # UMAP places new rows
Output
t-SNE (150, 2) 0.986
UMAP (150, 2) 0.975
(2, 2)
t-SNE UMAP
Import from sklearn.manifold import TSNE import umap (package umap-learn)
Main settings perplexity 5–50 (below n) n_neighbors 5–50, min_dist 0–0.5
New rows no transform reducer.transform(X_new)
Speed slow above ~10,000 rows faster
Repeatable random_state=42 + threadpool_limits(limits=1) random_state=42, n_jobs=1
Distances between clusters meaningless mostly meaningless
Use as model input no with care, inside a pipeline

Run PCA to about 50 components first when the data has hundreds of columns. Read a map only as “who is next to whom”. Check it with two seeds and two settings.

from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
s1 = pd.read_csv("data/sensors.csv").query("sensor_id == 'S1'")
cols = ["temperature_c", "humidity_pct", "vibration_mm_s"]
X_s1 = s1[cols].interpolate() # models reject NaN
iso = IsolationForest(n_estimators=200, contamination=0.01, random_state=42).fit(X_s1)
flags = iso.predict(X_s1) == -1 # -1 = anomaly, 1 = normal
print("flagged:", int(flags.sum()), "of", len(X_s1))
print(X_s1[flags].head(3))
lof = make_pipeline(StandardScaler(), LocalOutlierFactor(n_neighbors=20,
contamination=0.01))
print("LOF flagged:", int((lof.fit_predict(X_s1) == -1).sum()))
Output
flagged: 21 of 2016
temperature_c humidity_pct vibration_mm_s
584 20.09 57.60 7.53
820 22.92 54.40 7.53
876 36.03 50.65 1.81
LOF flagged: 21
Item IsolationForest LocalOutlierFactor
Idea anomalies need few random cuts to isolate lower density than its neighbors
Scale first no yes
Training rows fit_predict / predict: -1 anomaly fit_predict only
New rows predict, score_samples novelty=True, then predict
Score (lower = stranger) score_samples negative_outlier_factor_; score_samples with novelty=True
contamination the share of rows to flag; moves the threshold only same

Outlier detection: the anomalies are in the training data. Novelty detection: train on clean data, then score new rows. contamination is a quota: the model flags that share of training rows even if the data is clean. Without labels, use score_samples and inspect the strangest rows.

Metric Needs labels Range Question it answers
silhouette_score no −1 to 1, higher better are clusters separated?
davies_bouldin_score no ≥ 0, lower better compact vs separated
calinski_harabasz_score no ≥ 0, higher better between vs within variance
adjusted_rand_score yes, or a second clustering ~0 random, 1 identical do two partitions agree?
normalized_mutual_info_score yes 0 to 1 shared information
trustworthiness no 0 to 1 does a 2-D map keep neighbors?
gmm.bic(X) no lower better which mixture fits best?
Trap Symptom Fix
Unscaled columns the widest column (charges, tenure) decides every cluster or PC1 StandardScaler first, inside a pipeline
KMeans() with the default n_init="auto" different runs give different clusters n_init=10, random_state=42
Picking k by the lowest inertia “more clusters is always better” silhouette + elbow + profiles
Reading cluster ids as names “cluster 2” means something else after a rerun map ids to names once, from the profile; compare runs with ARI
Target or id columns in the features segments “explain” churn by construction cluster on behavior; use the target only to check
fcluster vs scikit-learn ids off-by-one when you compare fcluster starts at 1, scikit-learn at 0
Ward with a non-Euclidean metric ValueError average or complete linkage
DBSCAN with a guessed eps all rows are noise, or one big cluster k-distance curve
Counting -1 as a cluster one cluster too many len(set(labels) - {-1})
kneighbors(X) on the training rows the first neighbor is the row itself, distance 0 ask for one neighbor more, or read the last column
DBSCAN().predict or HDBSCAN().predict AttributeError k-NN classifier on the clustered rows
Lowest BIC read as the “true” number of groups BIC disagrees with the known classes BIC picks a density model; check the profiles
Gaps and sizes on a t-SNE or UMAP map false claims about which groups are similar read neighbors only; check with two seeds
t-SNE numbers change between machines same random_state, different output fit inside threadpool_limits(limits=1)
HDBSCAN(...) without copy= (scikit-learn 1.9) FutureWarning about copy pass copy=True
umap.UMAP(random_state=42) alone UserWarning about n_jobs add n_jobs=1
LocalOutlierFactor().predict(X) AttributeError fit_predict, or novelty=True for new rows
contamination far above the real rate many normal rows flagged start from a domain estimate; read score_samples
One anomaly model for several machines a whole machine flagged one model per machine, or add context columns
NaN in the input ValueError: Input X contains NaN impute or interpolate first