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

k-means objective, assignment, update and initializationEmpty clusters, inertia and seed instability
1

Read

In this order, only the parts listed

0 of 3 done

  1. 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_iter assignment and update walk, Inertia, Multiple Initializations with the n_init auto rule, k-means++ seeding, elbow plot and silhouette_score with the silhouette diagram

    Skim Accelerated K-Means and Mini-Batch K-Means; keep the max_iter walk and the k-search plots.

  2. 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

  3. k-means on simulated dataISLP - Unsupervised Learning

    K-Means Clustering: separation on the simulated 50-point data with random_state, splitting behavior, and inertia_ as within-cluster sum of squares

    The lab says the n_init default is 10; that predates scikit-learn 1.4. The default is now auto, one run under k-means++, which is why the lab passes n_init=20 explicitly.

2

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=auto runs once under k-means++ and ten times under random init. One k-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=10 always. Under the default k-means++ the auto default is a single run; set n_init=10 explicitly when stability matters.
  • Requesting more clusters than samples. scikit-learn 1.9 raises an error for n_samples=3 with n_clusters=5; it does not return empty clusters silently.
3

Try it yourself

Closed-book, before checking anything

Closed-book, run one Lloyd round on from centers : labels , new centers , inertia 2.0 down to 1.0. State why the next round cannot raise it.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 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. 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. 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. 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.

5

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.

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

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=False rule, 8.3.1.3 scaling data with outliers, and 8.3.4 categorical encoding with handle_unknown, infrequent and sparse_output behavior. Apply after the HOML notebook build works.

  • scikit-learn - pipelines and composite estimatorsscikit-learn · reference

    Read 8.1.1 Pipeline chaining with the no-leakage rule and transformer caching, and 8.1.4 ColumnTransformer for heterogeneous columns with remainder and 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_frequent strategies, 8.4.6 Marking imputed values with MissingIndicator or add_indicator=True for missingness flags, and 8.4.7 estimators that accept NaN directly. 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_transform section and the Digits fit and transform section, then read the parameters page for the n_neighbors local-global tradeoff and min_dist packing. Stay in 2D exploratory views with fixed seeds.