Machine Learning

k-means Clustering

k-means is alternating minimization: assign points to the nearest centroid, move centroids to cluster means, and watch the within-cluster squared error fall.

status: reviewimportance: importantdifficulty 3/5math: undergraduateread: 18mlive demo

Concept Structure

k-means Clustering

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
3next concepts
3related links

Learner Contract

What this page should let you do.

You are here becausek-means is alternating minimization: assign points to the nearest centroid, move centroids to cluster means, and watch the within-cluster squared error fall.

This Machine Learning concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Test the linkManipulate one control and predict the visible change.Then continue to Gaussian Mixture Models and EM (review)

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources4 cited
Codeattached
Demolive
Reviewed2026-07-02
Updatedpage 2026-07-02

Learning item flow

4/4 sections readyAsk about thisResearch room
Conceptk-means ClusteringMachine Learning
4 sources attachedLocal snapshot ready
concept:machine-learning/clustering-k-means
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

Suppose you have unlabeled points and want a rough map of their structure. You are not asking for a classifier yet. You are asking:

If I had to replace each group of points by one representative point, where should those representatives go?

k-means answers with a loop. Start with KK centroids. Assign every data point to the nearest centroid. Then move each centroid to the mean of the points assigned to it. Repeat.

The important part is not that the dots move in a pleasing animation. The important part is that each half-step solves a simpler problem exactly:

  1. with centroids fixed, nearest-centroid assignment minimizes the current squared-distance cost;
  2. with assignments fixed, the arithmetic mean minimizes the squared distances inside that cluster.

That makes k-means an alternating minimization procedure. Each iteration makes the current run no worse, but it does not guarantee the best clustering you could have found from every possible initialization.

So k-means is useful when the geometry matches the assumption: clusters are roughly compact around Euclidean centers after sensible scaling. It becomes misleading when different feature units dominate distance, clusters are elongated or nested, outliers drag centroids, or the chosen KK answers a different question than the one you meant to ask.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let the dataset be

X={x1,,xn},xiRd.X=\{x_1,\ldots,x_n\},\qquad x_i\in\mathbb R^d.

Choose a number of clusters KK. k-means keeps two kinds of variables:

ci{1,,K}andμ1,,μKRd,c_i \in \{1,\ldots,K\} \quad\text{and}\quad \mu_1,\ldots,\mu_K\in\mathbb R^d,

where cic_i is the cluster assigned to point xix_i, and μk\mu_k is the centroid of cluster kk.

The objective is the within-cluster sum of squares:

J(c,μ)=i=1nxiμci22.J(c,\mu)=\sum_{i=1}^n \lVert x_i-\mu_{c_i}\rVert_2^2.

Assignment Step

If the centroids are fixed, point xix_i contributes only one term to the objective. The best assignment is therefore

ci=argmink{1,,K}xiμk22.c_i = \arg\min_{k\in\{1,\ldots,K\}} \lVert x_i-\mu_k\rVert_2^2.

This is the Voronoi step: every point joins the region of its nearest centroid.

Move Step

Now freeze the assignments. For one cluster, define

Ck={i:ci=k}.C_k=\{i:c_i=k\}.

The part of the objective that depends on μk\mu_k is

Jk(μk)=iCkxiμk22.J_k(\mu_k)=\sum_{i\in C_k}\lVert x_i-\mu_k\rVert_2^2.

Differentiate with respect to μk\mu_k:

μkJk=2iCk(μkxi).\nabla_{\mu_k}J_k = 2\sum_{i\in C_k}(\mu_k-x_i).

Set this to zero:

2Ckμk2iCkxi=0,2|C_k|\mu_k-2\sum_{i\in C_k}x_i=0,

so

μk=1CkiCkxi.\mu_k = \frac{1}{|C_k|} \sum_{i\in C_k}x_i.

The centroid moves to the mean of its assigned points.

What Is Guaranteed

The assignment step cannot increase JJ because it chooses the nearest centroid for each point. The move step cannot increase JJ because the mean minimizes squared distance for fixed assignments. Since there are only finitely many assignments, the algorithm eventually reaches a state where the assignments stop changing.

The catch is local optimality. Different initial centroids can lead to different final clusters. Also, the Euclidean norm makes feature scaling part of the model. If one coordinate is measured in kilometers and another in millimeters, the larger numeric scale can dominate the clustering unless preprocessing is chosen deliberately.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

X = np.array([
    [0.18, 0.72], [0.22, 0.62], [0.28, 0.78], [0.34, 0.60], [0.30, 0.36],
    [0.68, 0.34], [0.74, 0.43], [0.82, 0.31], [0.78, 0.62], [0.88, 0.50],
])
mu = np.array([[0.12, 0.52], [0.90, 0.78]])

def assign(X, mu):
    squared = ((X[:, None, :] - mu[None, :, :]) ** 2).sum(axis=2)
    return squared.argmin(axis=1), squared.min(axis=1).sum()

def move(X, c, mu):
    new_mu = mu.copy()
    for k in range(len(mu)):
        rows = X[c == k]
        if len(rows):
            new_mu[k] = rows.mean(axis=0)
    return new_mu

c0, before = assign(X, mu)
mu1 = move(X, c0, mu)
after = ((X - mu1[c0]) ** 2).sum()
c1, after_reassign = assign(X, mu1)

print("assignments:", c0.tolist())
print("before move:", round(before, 4))
print("moved centroids:", np.round(mu1, 3).tolist())
print("after move:", round(after, 4))
print("after next assign:", round(after_reassign, 4), c1.tolist())

The code mirrors the math. assign computes nearest-centroid labels and the current squared-error objective. move replaces each centroid by the mean of the points assigned to it. The last line shows the next assignment step because k-means is a loop, not a single centroid update.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

The lab below asks for the invariant before it shows the numbers.

Choose an initialization case, inspect the starting centroids, then predict whether one assignment-plus-move step will decrease, increase, or leave unchanged the within-cluster sum of squares. After reveal, compare the locked ledger with the arrows: points are assigned to nearest centroids, centroids move to cluster means, and the objective falls unless the centroids were already at those means.

Use the bad-seed case as the warning. The objective can improve while the clustering is still not the clustering you hoped for.

Live Concept Demo

Explore k-means Clustering

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what k-means Clustering should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

k-means is alternating minimization: assign points to the nearest centroid, move centroids to cluster means, and watch the within-cluster squared error fall.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change k-means Clustering should make visible.

Visual Inquiry

Make the image answer a mathematical question

k-means is alternating minimization: assign points to the nearest centroid, move centroids to cluster means, and watch the within-cluster squared error fall.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make k-means Clustering easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2020CS229 Notes: K-means, Mixtures of Gaussians and the EM AlgorithmStanford CS229

Supports the k-means distortion objective, assignment step, centroid update step, and the connection to alternating minimization before EM.

Open source
book · 2023An Introduction to Statistical Learning, Chapter 12James, Witten, Hastie, Tibshirani, and Taylor

Supports k-means as an unsupervised clustering method, within-cluster variation, random initialization, local optima, multiple starts, and the need to choose K.

Open source
book · 2009The Elements of Statistical Learning, Chapter 14Hastie, Tibshirani, and Friedman

Supports centroid-based clustering, within-cluster sum of squares, iterative relocation, and the sensitivity of clustering to geometry and preprocessing.

Open source
documentation · 2026scikit-learn User Guide: K-meansscikit-learn developers

Implementation-context source for inertia, initialization sensitivity, multiple restarts, and practical scaling/performance caveats.

Open source

Claim Review

k-means is alternating minimization: assign points to the nearest centroid, move centroids to cluster means, and watch the within-cluster squared error fall.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources4 references

cs229-2020-kmeans-em-notes, james-2023-islr-unsupervised-learning, hastie-2009-esl-unsupervised-learning, sklearn-2026-kmeans-user-guide

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Substantively reviewedk-means alternates between assigning each point to its nearest centroid and moving each centroid to the mean of its assigned points, monotonically decreasing the within-cluster sum of squares for the current run while remaining sensitive to K, initialization, scaling, and non-spherical cluster structure.Claim metadata: source checked

The sources support the exact two-step algorithm and the within-cluster-sum-of-squares objective. ISLR/ESL/scikit-learn support the caveats that initialization, choice of K, scaling, and cluster shape matter.

Sources: CS229 Notes: K-means, Mixtures of Gaussians and the EM Algorithm, An Introduction to Statistical Learning, Chapter 12, The Elements of Statistical Learning, Chapter 14, scikit-learn User Guide: K-meansThe lab is a two-dimensional exact-distance witness with K=2. It does not cover k-means++, mini-batch k-means, clustering consistency, non-Euclidean variants, categorical data, density-based clusters, or model-based Gaussian mixtures.A bounded review summary is present; still check caveats and exact reference scope.

Checked Stanford CS229 k-means/EM notes, ISLR unsupervised-learning chapter, ESL unsupervised-learning chapter, and current scikit-learn k-means user-guide context for the distortion/inertia objective, nearest-centroid assignment step, centroid-as-mean update, monotone per-run improvement, random initialization/local optima, multiple restarts, and preprocessing/geometry caveats. GPT Pro/Oracle publication critique remains pending because 127.0.0.1:51672 refused connection.

Reviewer: codex-local-source-review; reviewed 2026-07-02

Practice Loop

Try the idea before it explains itself

k-means is alternating minimization: assign points to the nearest centroid, move centroids to cluster means, and watch the within-cluster squared error fall.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in k-means Clustering.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded research drawerClose
Conceptk-means ClusteringMachine Learning
Runnable code comparisonk-means Clustering runnable code 1X = np.array([Prediction before revealk-means Clustering interactive demoManipulate one control and predict the visible change.
Grounded room questionWhat is the smallest example that makes k-means Clustering click without losing the math?Local snapshot ready

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptMachine Learning

k-means Clustering

Attached question

What is the smallest example that makes k-means Clustering click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - k-means Clustering Selected item key: recorded for copy. Context: Machine Learning Page anchor: recorded for copy. Open question: What is the smallest example that makes k-means Clustering click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

View it in context
concept/concept-notebook/machine-learning/clustering-k-means concept:machine-learning/clustering-k-means