Cheat sheets

Clustering, Dimensionality Reduction and Anomalies

Cluster, reduce and flag outliers without labels. K-Means, DBSCAN, GMM, PCA, Isolation Forest, LOF.

  • Concepts and terms
  • Tasks and commands
  • Annotated code
  • Diagrams
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

Three jobs without labels#

reducedRaw datano labelsPCAkeep 90-95%varianceClusteringK-Means, DBSCAN,GMMDetectorIsolation Forest,LOFReconstructionerrorhigh error is anoutlierAnomaly scorerank, thenthresholdFlagged pointshuman reviewreducedRaw datano labelsPCAkeep 90-95%varianceClusteringK-Means,DBSCAN, GMMDetectorIsolationForest, LOFReconstructionerrorhigh error isan outlierAnomalyscorerank, thenthresholdFlaggedpointshuman review

From Lesson 02.07, Lesson 02.16, Lesson 01.10

From-scratch calls#

TaskCode
K clusters, hard labelskmeans(data, k=3)
Inertia and silhouette per Kfind_best_k(data, max_k=6)
Dense regions, noise is -1dbscan(data, eps=1.5, min_samples=5)
Soft labels with EMgmm(data, k=3)
Project to 2 axesPCA(n_components=2).fit_transform(X)
Separate ringskernel_pca(X, n_components, kernel="rbf", gamma=1.0)
Flag by standard deviationszscore_detect(X, threshold=3.0)
Flag outside the fencesiqr_detect(X, factor=1.5)

From 02.07 code/clustering.py, 01.10 code/dim_reduction.py, 02.16 code/anomaly_detection.py

The same in sklearn#

km = KMeans(n_clusters=3, random_state=42).fit(data)
db = DBSCAN(eps=1.5, min_samples=5).fit(data)
gmm_model = GaussianMixture(n_components=3, random_state=42).fit(data)
sklearn_pca = SklearnPCA(n_components=2)explained_variance_ratio_
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
reducer = UMAP(n_components=2, n_neighbors=15, min_dist=0.1, random_state=42)
iso = IsolationForest(n_estimators=100, contamination=0.05, random_state=42)
iso.fit(X_train)fit on normal data
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.05, novelty=True)
oc_svm = OneClassSVM(kernel="rbf", gamma="auto", nu=0.05)

From Lesson 02.07, Lesson 02.16, Lesson 01.10

Formulas#

Inertia
sum of squared distances from each point to its centroid. Lower is tighter.
Silhouette
(b - a) / \max(a, b), from -1 (wrong cluster) to +1.
Z-score
(x - \text{mean}) / \text{std}. Flag when the absolute value passes the threshold.
IQR fences
Q1 - \text{factor} \cdot IQR and Q3 + \text{factor} \cdot IQR, with IQR = Q3 - Q1.
Isolation score
2^{-\text{average\_path\_length}(x) / c(n)}. Near 1 is an anomaly, near 0.5 is normal.
c(n)
2 * H(n-1) - 2*(n-1)/n, expected path length of a failed search.
Explained ratio
\text{eigenvalue}_k / \sum \text{all eigenvalues}
PCA fraction lost
dropped eigenvalues over all eigenvalues.

From Lesson 02.07, Lesson 02.16, Lesson 01.10

Clustering: use X when#

CommandWhat it does
K-MeansLarge data, spherical clusters, known K. Hurt by outliers
DBSCANUnknown K, any shape, finds noise. Fails on varying density
HierarchicalSmall data, needs a dendrogram. O(n^2) memory
GMMOverlapping, elliptical clusters, soft assignments
Ward linkageMerge with the smallest rise in within-cluster variance

From Lesson 02.07

Abbreviations#

DBSCAN
density-based clustering. Core, border and noise points.
GMM
Gaussian Mixture Model. K Gaussians with soft assignments.
EM
Expectation-Maximization. E-step probabilities, M-step parameters.
PCA
Principal Component Analysis. Axes of maximum variance.
t-SNE
t-Distributed Stochastic Neighbor Embedding. Keeps neighbors.
UMAP
Uniform Manifold Approximation and Projection. Faster, more global.
LOF
Local Outlier Factor. Above 1.0 is lower density than neighbors.
AUPRC
area under the precision-recall curve. Better than AUROC here.

From Lesson 02.07, Lesson 02.16, Lesson 01.10

Reduce and detect: use X when#

CommandWhat it does
PCAPreprocessing and compression. Fast, global variance
t-SNE2D plots of local neighborhoods. Below 10k samples
UMAP2D plots at scale. Some global structure
Kernel PCANonlinear manifold. Kernel matrix is n by n
Z-score / IQROne feature at a time. Very fast
Isolation ForestNo assumptions. Works in high dimensions
LOFLocal anomalies, clusters of different density. Slow
One-Class SVMSmall to medium data. Kernel matrix grows quadratically

From Lesson 01.10, Lesson 02.16

Anomaly detection pipeline#

1Baselinecollect a period with no or very few anomalies.2Featuresadd rolling statistics, time features andratios.3Trainfit the detector on the baseline. It learnsnormal.4Scoregive each new observation an anomaly score.5Thresholdpick the cutoff from the cost of false alarmsand misses.6Alertsend flagged points to human review.7Feedbackrecord true anomalies and false alarms. Tune thethreshold.

From Lesson 02.16

Defaults and numbers#

SettingDefaultNote
Z-score threshold3.099.7% of Gaussian data is inside
IQR factor1.53.0 flags fewer points
n_estimators100Isolation trees. Usually enough
max_samples256Rows per tree, from the original paper
predict threshold0.5Score above it is an anomaly
contamination0.05Sets the cutoff only, not the scores
t-SNE perplexity30Typical range 5-50
Variance kept0.95Or 0.90 for the PCA cutoff

From Lesson 02.16, 02.16 code/anomaly_detection.py, Lesson 01.10

Failures and fixes#

SymptomCauseFix
K-Means splits moons badlyClusters are not sphericalUse DBSCAN with eps=0.3
K-Means results change per runLocal minimum of inertiaFix the seed or use K-Means++
Z-score misses pointsMultimodal data or outliers in trainingUse IQR or Isolation Forest
Per-feature methods miss a pointUnusual only in the joint spaceUse Isolation Forest
99.9% accuracy, no catches0.1% anomalies, accuracy is uselessPrecision@k and AUPRC
Operators ignore alertsToo many false alarmsStart with a high threshold
Median score drifts upData changed or model is staleRetrain on recent normal data
t-SNE cluster gaps differDistances between clusters mean nothingRead only the clusters

From Lesson 02.07, Lesson 02.16, Lesson 01.10

Questions#

How do I pick K?
Find the elbow in inertia. Check the silhouette score.
Why model normal data?
Anomalies are rare and change. Deviations from normal include novel types.
What is the best training setup?
Semi-supervised: fit on a clean set of normal data only.
Few labeled anomalies?
Use them for evaluation, not training.
Why is Isolation Forest fast?
Each tree uses a small subsample.
Why reduce dimensions?
Distances converge in high dimensions. Nearest-neighbor search stops working.

From Lesson 02.07, Lesson 02.16, Lesson 01.10