This Machine Learning concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.
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.
Concept Structure
k-means Clustering
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learner Contract
What this page should let you do.
2 prerequisites listed; refresh them before leaning on the math or code.
Explain the mechanism, trace the main notation, and test one prediction in the live demo.
Read the intuition before the notation; the math should name a mechanism you already felt.
Follow this edge after making one prediction here; the next page should reuse the result, not restart the route.
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.01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
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 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:
- with centroids fixed, nearest-centroid assignment minimizes the current squared-distance cost;
- 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 answers a different question than the one you meant to ask.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let the dataset be
Choose a number of clusters . k-means keeps two kinds of variables:
where is the cluster assigned to point , and is the centroid of cluster .
The objective is the within-cluster sum of squares:
Assignment Step
If the centroids are fixed, point contributes only one term to the objective. The best assignment is therefore
This is the Voronoi step: every point joins the region of its nearest centroid.
Move Step
Now freeze the assignments. For one cluster, define
The part of the objective that depends on is
Differentiate with respect to :
Set this to zero:
so
The centroid moves to the mean of its assigned points.
What Is Guaranteed
The assignment step cannot increase because it chooses the nearest centroid for each point. The move step cannot increase 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
Code
Keep the implementation aligned with the notation so the algorithm is legible.
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
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
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.
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.
Start with the picture, metaphor, or geometric mechanism.
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.
Which visible object should carry the first intuition?
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.
Supports the k-means distortion objective, assignment step, centroid update step, and the connection to alternating minimization before EM.
Open sourceSupports k-means as an unsupervised clustering method, within-cluster variation, random initialization, local optima, multiple starts, and the need to choose K.
Open sourceSupports centroid-based clustering, within-cluster sum of squares, iterative relocation, and the sensitivity of clustering to geometry and preprocessing.
Open sourceImplementation-context source for inertia, initialization sensitivity, multiple restarts, and practical scaling/performance caveats.
Open sourceClaim 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.
Claims without a substantive review badge still need exact source-support review.
cs229-2020-kmeans-em-notes, james-2023-islr-unsupervised-learning, hastie-2009-esl-unsupervised-learning, sklearn-2026-kmeans-user-guide
Use equations, runnable code, and demos to check whether the source support is operational.
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-02Source support candidates
course-notes 2020CS229 Notes: K-means, Mixtures of Gaussians and the EM AlgorithmSupports the k-means distortion objective, assignment step, centroid update step, and the connection to alternating minimization before EM.
book 2023An Introduction to Statistical Learning, Chapter 12Supports k-means as an unsupervised clustering method, within-cluster variation, random initialization, local optima, multiple starts, and the need to choose K.
book 2009The Elements of Statistical Learning, Chapter 14Supports centroid-based clustering, within-cluster sum of squares, iterative relocation, and the sensitivity of clustering to geometry and preprocessing.
documentation 2026scikit-learn User Guide: K-meansImplementation-context source for inertia, initialization sensitivity, multiple restarts, and practical scaling/performance caveats.
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.
Before touching the demo, predict one visible change that should happen in k-means Clustering.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
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.Open the draft below to save one note and next action in this browser.
k-means Clustering
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
This draft stays in this browser, attached to the selected learning item.
- 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
- 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
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.
concept/concept-notebook/machine-learning/clustering-k-means
concept:machine-learning/clustering-k-means