Topic 4 of 6 · 4 min read
Clustering and anomaly detection
Goal: Choose a clustering or anomaly detection method for an unlabelled dataset and judge whether the groups it finds are meaningful.
Clustering groups similar rows and anomaly detection flags rows that do not fit, both without labels, so the result is only useful if you check that it means something. There is no ground truth to score against, which is the main trap.
Check yourself · 1 of 3
Which algorithm labels sparse points as noise and does not need the number of clusters in advance?
Why it matters
Teams use clustering to segment customers and anomaly detection to find fraud, broken sensors or odd log lines. Every algorithm returns an answer, even on random data. An assistant can write the code in one line and describe the groups in confident prose. Whether those groups are real is your job.
The three tools
- k-means needs the number of clusters
kup front. It finds round, similar-sized groups around centres and assigns every point to one. It uses distance, so scale your features first. It is fast and a fine default for compact groups. - DBSCAN needs no
k. It grows clusters from dense regions, labels sparse points as noise (-1), and finds odd shapes. You tuneeps(neighbour radius) andmin_samples. It struggles when clusters have very different densities. - Isolation forest is for anomalies. It builds random trees and flags points that are isolated in few splits. You set
contamination, the expected share of outliers, which is a guess unless you know the rate.
How to judge the result
- Silhouette score (from -1 to 1) measures how well rows fit their own cluster compared with the nearest other. Compare values across
k, and treat a very low score as a sign the groups are weak. - Stability. Rerun with different seeds or on a resample. Groups that change each time are noise.
- Profile each cluster. Compute the mean of key columns per cluster. If you cannot describe the clusters in a sentence each, or they differ only on one scaled column, they are not useful.
- For anomalies, read the top flagged rows by hand. If a domain expert says they are ordinary, the detector is flagging rarity, not trouble.
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
Xs = StandardScaler().fit_transform(X)
for k in range(2, 8):
labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(Xs)
print(k, round(silhouette_score(Xs, labels), 3))
What goes wrong
- Unscaled features, so one large-unit column decides all the groups.
- Picking
kto make the story nice rather than from scores and stability. - Treating clusters as ground truth, for example naming a segment "bargain hunters" without checking behaviour.
- Assuming contamination equals the true fraud rate.
Examples
Choosing between k values
| k | silhouette |
|---|---|
| 2 | 0.41 |
| 3 | 0.38 |
| 4 | 0.22 |
| 5 | 0.19 |
The score drops sharply after 3, so 2 or 3 groups are defensible and 5 is not. Before settling, rerun with other seeds and profile the groups.
Rare is not bad
An isolation forest on server logs flags the 20 rows from the monthly backup job as the top anomalies. They are unusual (large and rare) and harmless. Add a feature such as job type, or exclude the known job, rather than raising the alert threshold.
Key points
- k-means needs k and scaled features and finds compact groups; DBSCAN finds dense regions of any shape and marks the rest as noise.
- Isolation forest flags points that are easy to separate, and its contamination setting is an assumption about the outlier rate.
- Silhouette score compares candidate cluster counts, and low values mean weak structure.
- Check stability across seeds or resamples before trusting a segmentation.
- Profile each cluster in plain language; if you cannot, the grouping is probably not useful.
Common mistakes
- Clustering without scaling the features first.
- Choosing k because it gives a tidy number of personas.
- Accepting the algorithm's output as real without checking stability or profiling the groups.
- Setting contamination to a round number such as 0.05 with no knowledge of the real outlier rate.
Check yourself · 2 of 3
Before running k-means on columns such as annual_spend (0 to 50,000) and visits_per_month (0 to 12), what should you do?
Check yourself · 3 of 3
Rerunning k-means with five different random seeds gives five very different groupings of the same customers. What does this suggest?
Practice items, not counted towards your mastery.
Start here
- scikit-learn: ensembles (gradient boosting, random forests) (opens in a new tab)DocsFree
Reference for random forests and histogram gradient boosting, with the parameters that matter.
- XGBoost documentation (opens in a new tab)DocsFree
Official docs for the most used boosted-tree library, including parameter tuning notes.
- Why do tree-based models still outperform deep learning on tabular data? (opens in a new tab)PaperFree
The benchmark paper behind the claim that trees lead on medium-sized tabular data.
More for this topic
- scikit-learn: clustering (opens in a new tab)DocsFree
Compares k-means, DBSCAN and others, with their assumptions and evaluation scores.
- scikit-learn: novelty and outlier detection (opens in a new tab)DocsFree
Explains isolation forest and other detectors and when each applies.