k-Means Clustering
-Means is an unsupervised partition-based clustering algorithm that divides a dataset of observations into distinct, non-overlapping clusters where each observation belongs to the cluster with the nearest mean (centroid).
Objective Function
The objective is to minimize the Within-Cluster Sum of Squares (WCSS), also known as Inertia:
Where:
- is the number of clusters.
- is the set of points belonging to cluster .
- is the centroid (mean vector) of cluster .
- is the squared Euclidean distance between point and centroid .
Algorithm Steps (Lloyd's Algorithm)
- Initialization: Select initial centroids .
- Assignment Step: Assign each data point to the closest centroid:
- Update Step: Recompute the centroid of each cluster as the mean of all points assigned to it:
- Convergence Check: Repeat steps 2 and 3 until centroids stabilize (movement ) or maximum iterations are reached.
Initialization Strategies
- Random Initialization: Randomly chooses data points as initial centroids. Prone to converging to poor local optima.
- -Means++: Chooses the first centroid uniformly at random, then chooses subsequent centroids with probability proportional to the squared distance to the nearest existing centroid (). This ensures well-spaced initial centroids and substantially faster convergence.
Determining Optimal
- Elbow Method: Plot Inertia (WCSS) against different values of . Look for the "elbow point" where the rate of decrease sharpens to a plateau.
- Silhouette Score: Measures how similar a point is to its own cluster compared to other clusters (values range from to , where higher indicates well-separated clusters): where is mean intra-cluster distance and is mean nearest-cluster distance.
Python Example (scikit-learn)
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
# Standardize features (crucial for distance-based algorithms)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Fit KMeans with k-means++ initialization
kmeans = KMeans(n_clusters=3, init='k-means++', random_state=42, n_init=10)
labels = kmeans.fit_predict(X_scaled)
centroids = kmeans.cluster_centers_
Strengths & Limitations
- Strengths:
- Simple, scalable ( time complexity), and easy to interpret.
- Guaranteed to converge to a local optimum.
- Weaknesses:
- Assumes spherical, equally sized clusters with isotropic variance.
- Vulnerable to outliers (which distort the cluster means).
- Struggles with complex, non-convex cluster geometries (better handled by DBSCAN or Spectral Clustering).
- Requires specifying in advance.