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.
profile = iris_df.groupby(labels).mean() # means in original units
6
profile["size"] = np.bincount(labels)
7
print(profile.round(2))
8
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.
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.
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.
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.
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.
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.