Unit 4.4 · about 4 h
155 / 324k-means: objective, initialization, empty clusters and instability
k-means is the first clustering mechanism and the initializer inside Gaussian mixtures. Its objective only descends, never to a global promise, so seeds and \(k\) decide the answer.
- derive
- implement
You can now
- Derive the assignment and centroid updates and show each step cannot increase the inertia.
- Implement Lloyd iterations from a blank file with
k-means++seeding and a fixed iteration cap. - Diagnose empty clusters, seed instability and \(k\) choice with inertia, silhouette and repeated runs.
Covers
- k-means objective, assignment, update and initialization
- Empty clusters, inertia and seed instability
Study, in this order
3 steps
- k-means mechanics and k searchHands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learning
Book Chapter 8: k-Means Clustering (printed pp. 249-258). Notebook 08 cells: K-Means through Finding the optimal number of clusters: blob demo, the
max_iterassignment and update walk, Inertia, Multiple Initializations with then_initautorule,k-means++seeding, elbow plot andsilhouette_scorewith the silhouette diagramDepth · Skim Accelerated K-Means and Mini-Batch K-Means; keep the
max_iterwalk and the k-search plots. - k-means objective and cluster evaluationscikit-learn - decomposition, clustering and outlier detection
2.3.2 K-means: inertia objective, local minima with repeated initializations,
k-means++default; 2.3.11 cluster evaluation: silhouette coefficient \(s=(b-a)/\max(a,b)\) with its convex-cluster bias and the adjusted Rand index correcting for chance - k-means on simulated dataISLP - Unsupervised Learning
K-Means Clustering: \(K=2\) separation on the simulated 50-point data with
random_state, \(K=3\) splitting behavior, andinertia_as within-cluster sum of squaresDepth · The lab says the
n_initdefault is 10; that predates scikit-learn 1.4. The default is nowauto, one run underk-means++, which is why the lab passesn_init=20explicitly.
Focus on
- Each assignment step and each mean update cannot increase the inertia, so Lloyd iterations converge, usually to a local minimum. Restarts pick among minima.
- Since version 1.4 the default
n_init=autoruns once underk-means++and ten times under random init. Onek-means++run is not ten restarts. - Inertia always falls as \(k\) grows. Read \(k\) from elbows, silhouette and repeated-seed stability, never from one inertia value.
- Empty clusters happen when a center loses every point. Know the repair: re-seed, drop, or error.
Reproduce closed-book
Traps
- Comparing inertia across different k or seeds as quality. Inertia is comparable only for fixed data, fixed \(k\) and best-of-restarts.
- Assuming
n_init=10always. Under the defaultk-means++theautodefault is a single run; setn_init=10explicitly when stability matters. - Requesting more clusters than samples. scikit-learn 1.9 raises an error for
n_samples=3withn_clusters=5; it does not return empty clusters silently.
Practice
Deep-ML 17: K-Means Clustering
Problem 17: implement k_means_clustering(points, k, initial_centroids, max_iterations) returning centroids rounded to 4 decimals
The tests check exact centroids on a 2D two-group set and a 3D set from fixed starts. Re-derive one update by hand first, then match.
Self-test
-
Why do Lloyd iterations terminate?
Assignments are finite and the inertia never increases: neither the assignment step nor the mean update can raise the objective, so the loop ends at a fixed assignment ormax_iter. -
Two seeds give inertia 120 and 95 at \(k=5\). Which clustering wins on the objective, and what stays unknown?
The 95 run wins on inertia. Whether either is near the global optimum or the right \(k\) stays unknown; check silhouette and seed spread. -
A center gets no points in one iteration. Name two sound repairs.
Re-seed it at a far point such as the highest-inertia contributor, or drop it and continue with \(k-1\). Either way record the event. -
Silhouette prefers \(k=2\) on two stretched blobs while the task needs subgroups. What do you do?
Keep the task \(k\) and justify it downstream. Silhouette rewards convex separation; it does not know the use.
Completion criterion
Stop when
Your implementation reproduces the hand round exactly, matches both Deep-ML centroid sets, and reports inertia spread across ten seeds for your \(k\).
Mark passed, then open 4.5 Only mark this when you can do it without notes.Leads to
- 4.5 Gaussian mixtures and EM Soften hard assignments into responsibilities.
- 4.6 DBSCAN, agglomerative clustering and cluster validation Contrast partition geometry with density and merge geometry.
Comes after
- 4.3 PCA via SVD: directions, explained variance and sign ambiguityCluster in PCA space and compare stability with and without reduction.
Resources for this unit
- Hands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learning Read Chapters 7 and 8 and run notebooks 07 and 08 for PCA, k-means, DBSCAN, agglomerative clustering, Gaussian mixtures and anomaly detection. Stop before extended semi-supervised and face-data projects.
- scikit-learn - decomposition, clustering and outlier detection Check decomposition orientation and solver behavior, cluster API semantics, and the distinction between novelty and outlier detection after the independent tests pass.
- ISLP - Unsupervised Learning Use Chapter 12 and its Python lab for the PCA derivations (12.2, including the low-rank approximation view and proportion of variance explained) and k-means (12.4.1), plus stability and interpretation limits, beside the notebook route.
Also in this section
- Deep-ML - unsupervised problems Use 17 K-Means Clustering, 19 PCA, 341 Gaussian Mixture Model with EM, 259 DBSCAN and 367 Isolation Forest as unit checks after the local implementation passes. Their tests were read in review; each card states what they pin, including the 367 path-length convention.
- scikit-learn - preprocessing data Read 8.3.1 standardization with the sparse
with_mean=Falserule, 8.3.1.3 scaling data with outliers, and 8.3.4 categorical encoding withhandle_unknown, infrequent andsparse_outputbehavior. Apply after the HOML notebook build works. - scikit-learn - pipelines and composite estimators Read 8.1.1
Pipelinechaining with the no-leakage rule and transformer caching, and 8.1.4ColumnTransformerfor heterogeneous columns withremainderand fitted-state behavior. Use it to assemble and serialize the feature-selection pipeline. - scikit-learn - imputation of missing values Read 8.4.2 univariate median and
most_frequentstrategies, 8.4.6 Marking imputed values withMissingIndicatororadd_indicator=Truefor missingness flags, and 8.4.7 estimators that acceptNaNdirectly. Decide impute-only versus impute-plus-indicator per column. - UMAP - basic usage and parameters Work the Penguin scaling and
fit_transformsection and the Digitsfitandtransformsection, then read the parameters page for then_neighborslocal-global tradeoff andmin_distpacking. Stay in 2D exploratory views with fixed seeds.