K-Means Clustering

Partition data into K clusters using K-Means algorithm. Groups data points into K clusters by minimizing within-cluster sum of squares (WCSS). Visualizes…

Groups data points into K clusters by minimizing within-cluster sum of squares (WCSS). Visualizes clusters with colored scatter plot and centroid markers.

What Is K-Means Clustering?

K-Means is an iterative partitioning algorithm that divides n data points into K clusters by minimizing the Within-Cluster Sum of Squares (WCSS). Each cluster is represented by its centroid (mean of assigned points), and every point belongs to the cluster with the nearest centroid.

The algorithm starts with K initial centroids (often randomly selected), then alternates between two steps: (1) assign each point to the nearest centroid, and (2) recompute centroids as the mean of assigned points. It converges when assignments stabilize, typically in 10-50 iterations.

Choosing K is a key challenge. The Elbow Method plots WCSS vs. K and looks for a 'bend' where adding more clusters yields diminishing returns. The Silhouette Score measures how similar a point is to its own cluster versus neighboring clusters, with values near +1 indicating good clustering.

Formula: WCSS = Σₖ Σ(xᵢ ∈ Cₖ) ‖xᵢ − μₖ‖² where μₖ = centroid of cluster Cₖ ‖·‖ = Euclidean distance Algorithm converges when assignments unchanged

Example Calculation

Points: (1,1), (1.5,2), (3,4), (5,7), (3.5,5), (4.5,5), (3.5,4.5). With K=2, centroids converge to μ₁≈(1.25, 1.5) and μ₂≈(3.9, 5.1). WCSS = 0.625 + 7.9 = 8.525. Cluster 1: {(1,1),(1.5,2)}, Cluster 2: {(3,4),(5,7),(3.5,5),(4.5,5),(3.5,4.5)}.

When to Use This Calculator

Common Mistakes to Avoid

How to Interpret Results

Related Standards & References

Frequently Asked Questions

How do I choose the right number of clusters (K)?

Use the Elbow Method: plot WCSS for K = 1 to 10 and pick the K where the curve bends sharply. Alternatively, compute the Silhouette Score for each K and choose the K with the highest average score. Domain knowledge should also guide the decision — sometimes the 'correct' K is known from the business context.

What are the limitations of K-Means?

K-Means assumes spherical, equally-sized clusters and is sensitive to initial centroid placement and outliers. It cannot detect non-convex clusters (e.g., crescent shapes). For such cases, consider DBSCAN (density-based) or Gaussian Mixture Models. K-Means also requires numeric data; categorical variables need encoding first.