k-Means Clustering
Partitioning data into k groups around centroids, choosing k, and understanding where the method breaks down.
Intermediate · about 4 hours · difficulty 2/5
Learn first: Encoding Categories and Scaling Numbers, Linear Algebra for ML
k-means alternates between assigning each point to its nearest centroid and moving each centroid to the mean of its points. It is fast, simple and the first clustering method to try.
Using it
- Scale features first; k-means uses Euclidean distance.
- Use
k-means++initialization (the default) and several restarts (n_init). - Choosing k: elbow plot of inertia, silhouette score, and above all whether clusters are useful and interpretable for the task.
MiniBatchKMeansfor large datasets.
Limitations
k-means assumes roughly spherical, similarly sized clusters and forces every point into a cluster, including outliers. It struggles with elongated or nested shapes. Gaussian mixture models generalize it with soft assignments and elliptical clusters.
Evaluating clusters
Without labels, evaluation is partly subjective. Profile each cluster (feature means, sizes), check stability across random seeds, and validate against a downstream use such as targeted marketing.
Good enough to move on when you can segment a dataset, justify k, and describe each cluster in plain language.
Key concepts
- Lloyd's algorithm
- k-means++ initialization
- Elbow and silhouette
- Cluster profiling
- Gaussian mixture models
- MiniBatchKMeans
Mini project
Segment customers in the UCI Online Retail dataset using RFM (recency, frequency, monetary) features and k-means, then write a one-line persona for each segment.
Check yourself
Why does k-means perform badly on two interleaved crescent-shaped clusters?
Free resources
- scikit-learn: Clustering (scikit-learn)
- scikit-learn: Gaussian mixture models (scikit-learn)