k-means steps
Basic Concepts
K-means clustering partitions data into k clusters by minimizing the within-cluster sum of squares. After choosing k and initializing k centroids, Lloyd's algorithm alternates between assigning each point to its nearest centroid and recomputing each centroid as the mean of its assigned points until assignments stabilize.
Study Card: K-Means Clustering Steps
Direct Answer
K-means clustering partitions data points into clusters by iteratively minimizing the within-cluster sum of squares (WCSS), also known as inertia:
The core steps of Lloyd’s algorithm are:
- Choose : Specify the target number of clusters.
- Initialize centroids: Select initial centroids (for example, randomly or with k-means++).
- Assign points: Assign each data point to the cluster whose centroid minimizes squared Euclidean distance .
- Update centroids: Recompute each centroid as the mean of all points currently assigned to cluster .
- Repeat until convergence: Alternate steps 3 and 4 until cluster assignments no longer change, centroid movement falls below a tolerance, or a maximum iteration count is reached.
Practical applications include customer segmentation, color/image quantization, and vector quantization.
Key Terms
- Centroid: The center of a cluster, calculated as the mean of all data points assigned to that cluster.
- Cluster: A group of data points assigned to the same centroid (forming a Voronoi cell in Euclidean space).
- K: The pre-specified number of clusters.
- Convergence: The stopping state where assignments stabilize, centroids move less than a tolerance threshold, or
max_iteris reached; note that Lloyd’s algorithm converges to a local minimum, not necessarily the global minimum. - Euclidean Distance: Standard K-means minimizes squared Euclidean distance, because the arithmetic mean is the exact minimizer of squared distances. Using Manhattan () distance with mean updates does not guarantee monotonic objective decrease; distance instead requires component-wise medians (K-medians) or actual data points (K-medoids).
Example
Imagine grouping customers into market segments:
- Choose : Decide on the number of segments (e.g., ).
- Initialize: Select 3 initial segment representatives (centroids) from the standardized feature space.
- Assign: Assign each customer to the closest centroid based on Euclidean distance over their standardized purchase features.
- Update: Recalculate each segment’s centroid by averaging the feature vectors of all customers assigned to it.
- Repeat: Repeat assignment and update until segment representatives and customer memberships stabilize.
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs # For generating sample data
# 1. Generate sample data
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
# 2. Choose the number of clusters (k)
k = 4
# 3. Pick explicit random initial centroids so we can visualize initial vs. final positions
rng = np.random.default_rng(42)
initial_indices = rng.choice(len(X), size=k, replace=False)
initial_centroids = X[initial_indices].copy()
# 4 & 5. Run K-Means (assignment + update until convergence) from those initial centroids
kmeans = KMeans(n_clusters=k, init=initial_centroids, n_init=1, random_state=42)
kmeans.fit(X)
labels = kmeans.labels_
final_centroids = kmeans.cluster_centers_ # Centroids after the algorithm converges
# Visualize initial vs. converged centroids
plt.figure(figsize=(10, 6))
plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap='viridis')
plt.scatter(initial_centroids[:, 0], initial_centroids[:, 1], c='red', marker='X', s=200, label='Initial Centroids')
plt.scatter(final_centroids[:, 0], final_centroids[:, 1], c='black', marker='X', s=200, label='Final Centroids')
plt.title(f'K-Means Clustering Results (k={k})')
plt.legend()
plt.show()
Related Concepts
- Choosing k: Determining the optimal number of clusters is crucial. Techniques like the Elbow Method, Silhouette Analysis, and the Gap Statistic can be used. Follow-up question: Explain how to select in k-means.
- K-means++: An improved centroid initialization method that spaces initial centroids apart probabilistically proportional to , typically achieving faster convergence and lower inertia than uniform random initialization.
- Distance Metrics & Feature Scaling: Because Euclidean distance is scale-sensitive, features should be standardized beforehand. Switching to or arbitrary dissimilarities motivates K-medians or K-medoids.
- Convergence Criteria: Understanding how k-means determines when to stop iterating (zero assignment changes, centroid shift below
tol, or maximum iterations). - Limitations of K-means: Sensitivity to initial centroid positions and outliers, need to pre-specify , and tendency to fail on clusters of widely varying sizes, densities, or non-spherical (non-convex) shapes.
- Evaluating K-means: Quantitative metrics such as inertia (WCSS), Silhouette score, Davies-Bouldin index, and Calinski-Harabasz index assess clustering quality.