Unit 4 of 8 · about 4 hours · derive, implement
k-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 decide the answer.
You'll be able to
- 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 choice with inertia, silhouette and repeated runs.
Covers
Read
In this order, only the parts listed
0 of 3 done
- 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 diagramSkim 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 with its convex-cluster bias and the adjusted Rand index correcting for chance - k-means on simulated dataISLP - Unsupervised Learning
K-Means Clustering: separation on the simulated 50-point data with
random_state, splitting behavior, andinertia_as within-cluster sum of squaresThe 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 grows. Read 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.
Common mistakes · 3
- Comparing inertia across different k or seeds as quality. Inertia is comparable only for fixed data, fixed 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.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why do Lloyd iterations terminate?Answer
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 or
max_iter.2.Two seeds give inertia 120 and 95 at . Which clustering wins on the objective, and what stays unknown?Answer
The 95 run wins on inertia. Whether either is near the global optimum or the right stays unknown; check silhouette and seed spread.
3.A center gets no points in one iteration. Name two sound repairs.Answer
Re-seed it at a far point such as the highest-inertia contributor, or drop it and continue with . Either way record the event.
4.Silhouette prefers on two stretched blobs while the task needs subgroups. What do you do?Answer
Keep the task and justify it downstream. Silhouette rewards convex separation; it does not know the use.
Practice
- Deep-ML 17: K-Means Clustering
Problem 17: implement
k_means_clustering(points, k, initial_centroids, max_iterations)returning centroids rounded to 4 decimalsThe 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.
You're done when
Your implementation reproduces the hand round exactly, matches both Deep-ML centroid sets, and reports inertia spread across ten seeds for your .
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 5 more in the section
- Hands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learningAurelien Geron (O'Reilly, 2025) · primary
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 detectionscikit-learn · reference
Check decomposition orientation and solver behavior, cluster API semantics, and the distinction between novelty and outlier detection after the independent tests pass.
- ISLP - Unsupervised LearningJames, Witten, Hastie, Tibshirani and Taylor · required
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 problemsDeep-ML · support
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 datascikit-learn · reference
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 estimatorsscikit-learn · reference
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 valuesscikit-learn · reference
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 parametersMcInnes, Healy and the UMAP contributors · reference
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.