Pros and cons of k-means
K-means clustering is popular because it is simple, fast, and scales linearly in sample count with time complexity O(n * k * d * i). However, it requires specifying k upfront, converges only to local minima sensitive to initialization, struggles with non-convex clusters or varying sizes and densities, and is sensitive to outliers and feature scales.
Study Card: Pros and Cons of K-means Clustering
Direct Answer
K-means clustering partitions data into clusters by minimizing within-cluster sum of squares (WCSS).
Pros:
- Simplicity & Interpretability: Easy to implement and understand via geometric centroids.
- Scalability: Runs in time ( samples, clusters, dimensions, iterations) and adapts easily to large datasets via Mini-Batch K-means.
- Guaranteed Objective Descent: Each assignment and mean-update step monotonically decreases WCSS, guaranteeing convergence in finite steps.
Cons:
- Requires Pre-specifying : Cluster count must be chosen beforehand (e.g., via Elbow or Silhouette analysis).
- Initialization & Local Minima: Non-convex objective; poor random starts yield suboptimal clusters unless mitigated with
k-means++and multiple restarts (n_init). - Geometric Assumptions: Implicitly favors convex, roughly spherical clusters of similar size/variance, failing on elongated, ring-shaped, or widely varying-density clusters.
- Outlier & Scale Sensitivity: Because centroids are means under squared Euclidean distance, extreme outliers heavily skew centroids, and unscaled large-magnitude features dominate distance calculations.
Key Terms
- Centroid: The mean vector of all data points assigned to a cluster.
- Within-Cluster Sum of Squares (WCSS): Sum of squared Euclidean distances from points to their assigned centroids, minimized by K-means.
- Initialization: Choosing starting centroids;
k-means++spreads initial centers probabilistically to improve convergence and solution quality. - Convergence: Reached when assignments stop changing or centroid updates fall below tolerance; guarantees a local minimum, not necessarily global optimality.
- Euclidean Distance: Scale-sensitive metric requiring feature standardization prior to clustering.
Example
Consider segmenting a large e-commerce customer base by standardized recency, frequency, and monetary spend with . K-means runs quickly even across hundreds of thousands of users, revealing clear segments such as high-value frequent buyers and inactive bargain hunters. However, if a small, ultra-dense niche segment sits near a wide, sparse segment, or if a few extreme wholesale outliers inflate one feature, K-means can split the large cluster or pull a centroid toward the outliers—requiring feature scaling, outlier handling, or validation with Silhouette scores.
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
# Generate sample data
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.6, random_state=0)
# Apply k-means clustering with k-means++ initialization and multiple restarts
kmeans = KMeans(n_clusters=4, init='k-means++', max_iter=300, n_init=10, random_state=0)
y_kmeans = kmeans.fit_predict(X)
centroids = kmeans.cluster_centers_
# Visualize results
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=y_kmeans, s=50, cmap='viridis')
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=200, alpha=0.75, label='Centroids')
plt.title('K-means Clustering')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.legend()
plt.show()
Related Concepts
- K-Medoids Clustering: Uses actual observed data points (medoids) as centers and supports arbitrary distance metrics (such as ), reducing sensitivity to outliers at higher computational cost.
- DBSCAN / HDBSCAN: Density-based algorithms that uncover arbitrarily shaped clusters and flag outliers as noise without pre-specifying .
- Gaussian Mixture Models (GMM): Probabilistic generalization providing soft assignments and covariance matrices for elliptical clusters.
- Determining the Optimal k: Methods such as Elbow, Silhouette, and Gap Statistic for validating .
- Curse of Dimensionality: In high dimensions, Euclidean distances concentrate and become less discriminative; applying PCA or UMAP beforehand often helps.