Skip to content
E
Educatum

k-means steps

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 nn data points into kk clusters by iteratively minimizing the within-cluster sum of squares (WCSS), also known as inertia:

min⁡{C1,…,Ck},{μ1,…,μk}∑j=1k∑xi∈Cj∥xi−μj∥22\min_{\{C_1, \dots, C_k\}, \{\mu_1, \dots, \mu_k\}} \sum_{j=1}^{k} \sum_{x_i \in C_j} \|x_i - \mu_j\|_2^2

The core steps of Lloyd’s algorithm are:

  1. Choose kk: Specify the target number of clusters.
  2. Initialize centroids: Select kk initial centroids (for example, randomly or with k-means++).
  3. Assign points: Assign each data point xix_i to the cluster CjC_j whose centroid μj\mu_j minimizes squared Euclidean distance ∥xi−μj∥22\|x_i - \mu_j\|_2^2.
  4. Update centroids: Recompute each centroid μj=1∣Cj∣∑xi∈Cjxi\mu_j = \frac{1}{|C_j|}\sum_{x_i \in C_j} x_i as the mean of all points currently assigned to cluster jj.
  5. 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_iter is 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 L2L_2 distances. Using Manhattan (L1L_1) distance with mean updates does not guarantee monotonic objective decrease; L1L_1 distance instead requires component-wise medians (K-medians) or actual data points (K-medoids).

Example

Imagine grouping customers into market segments:

  1. Choose kk: Decide on the number of segments (e.g., k=3k=3).
  2. Initialize: Select 3 initial segment representatives (centroids) from the standardized feature space.
  3. Assign: Assign each customer to the closest centroid based on Euclidean distance over their standardized purchase features.
  4. Update: Recalculate each segment’s centroid by averaging the feature vectors of all customers assigned to it.
  5. 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()
  • 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 kk in k-means.
  • K-means++: An improved centroid initialization method that spaces initial centroids apart probabilistically proportional to D(x)2D(x)^2, 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 L1L_1 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 kk, 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.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.