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:
1
import numpy as np
2
import pandas as pd
3
from sklearn.datasets import load_iris, make_moons
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.
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.
1
km = KMeans(n_clusters=5, n_init=10, random_state=42).fit(X_cust)
2
profile = customers.groupby(km.labels_)[behavior].mean() # original units
3
profile["size"] = np.bincount(km.labels_)
4
profile["churn_rate"] = customers.groupby(km.labels_)["churned"].mean() # not a feature
5
print(profile.round(2).T) # one column per cluster
6
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.
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.
BIC picks 2 components here for the 3 iris species: two species overlap. BIC =plnn−2lnL^, 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.
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.
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.
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.