What is K-Means Clustering?
Unlabeled Data Points ──► Assign to Nearest Centroid ──► Update Centroids ──► Converged Clusters
-
$K$ is the total number of clusters.
-
$C_k$ is the set of data points belonging to cluster $k$.
-
$x_i$ is an individual data point.
-
$\mu_k$ is the centroid (mean vector) of cluster $k$.
-
$\Vert{} x_i – \mu_k \Vert{}$ represents the Euclidean distance between point $x_i$ and centroid $\mu_k$.
How K-Means Works: Step-by-Step
┌───────────────────────────┐
│ 1. Choose K & Init Means │
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ 2. Assign Points to │ ◄─────────────────┐
│ Nearest Centroid │ │
└─────────────┬─────────────┘ │ Iteration Loop
│ │ (Until Convergence)
▼ │
┌───────────────────────────┐ │
│ 3. Recalculate Centroids │ ──────────────────┘
│ (Mean of assigned pts) │
└─────────────┬─────────────┘
│ (No centroid movement)
▼
┌───────────────────────────┐
│ 4. Convergence Reached │
└───────────────────────────┘
Step 1: Initialize $K$ Centroids
Step 2: Assign Data Points (Expectation Step)
Step 3: Update Centroids (Maximization Step)
Step 4: Repeat Until Convergence
-
Centroid locations stop changing (or change below a set tolerance limit).
-
Data points stop swapping clusters.
-
The maximum number of specified iterations is reached.
How to Determine the Optimal $K$
1. The Elbow Method
Inertia (WCSS)
▲
│ \
│ \
│ \ Elbow Point (Optimal K=3)
│ \ ╭─────────────
│ \ ╭┘
│ ▼
└─────────────────────────────► Number of Clusters (K)
1 2 3 4 5 6
2. Silhouette Analysis
-
$+1$: Point is well-matched to its own cluster and far from neighbors.
-
$0$: Point is sitting on the boundary between two clusters.
-
$-1$: Point is likely misassigned to the wrong cluster.
When to Use (and Avoid) K-Means
| Ideal Use Cases (When to Use) | Limitations & Pitfalls (When to Avoid) |
| Customer Segmentation: Grouping shoppers by spend volume and visit frequency. | Non-Spherical Clusters: Fails on complex shapes (like concentric circles or interlocking spirals). Use DBSCAN instead. |
| Document Classification: Grouping text vectors (TF-IDF/embeddings) by topic. | Varying Cluster Densities/Sizes: Struggles when clusters differ drastically in variance or population size. |
| Image Compression (Color Quantization): Reducing millions of RGB colors to $K$ representative shades. | Sensitive to Outliers: Single extreme values distort centroid calculations significantly. |
| Anomaly Preprocessing: Finding points far away from all cluster centroids. | High Dimensionality: Euclidean distance degrades in high dimensions (“curse of dimensionality”). |
Practical Python Implementation
scikit-learn:Python
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
# 1. Standardize features (Crucial: K-Means relies on Euclidean distance!)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 2. Instantiate K-Means with K-Means++ initialization
kmeans = KMeans(n_clusters=3, init='k-means++', random_state=42, n_init=10)
# 3. Fit model and predict cluster labels
cluster_labels = kmeans.fit_predict(X_scaled)
# 4. Access cluster centroids and total inertia
centroids = kmeans.cluster_centers_
inertia = kmeans.inertia_
Crucial Tip: Always scale your features (usingStandardScalerorMinMaxScaler) before applying K-Means. Because distance calculations are magnitude-sensitive, unscaled features measured in large units (e.g., annual income in thousands) will completely dominate features measured in small units (e.g., age in years).

