Scikit-learn and K-means
Practical, exam-focused notes on using scikit-learn's KMeans: definitions, derivation of the centroid update, algorithm steps (Lloyd), complexity, code syntax and worked Python examples with exact outputs.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
K-means clustering is a very common unsupervised learning method used by engineers to find groups (clusters) in numeric data. In industry and projects you will use scikit-learn's KMeans to quickly partition sensors, customers, image features or intermediate results into compact groups for summarisation, preprocessing or further modelling.
Key ideas
Objective function (within-cluster sum of squares) — the K-means algorithm attempts to minimise the objective J = sum_{i=1..k} sum_{x in C_i} ||x - μ_i||^2, where C_i are clusters and μ_i are their centroids. This objective is non-convex in the cluster assignments and centroids together; K-means finds a local minimum, not guaranteed global.
Centroid — the centroid μ_i of cluster C_i is the arithmetic mean of points in C_i. Formally μ_i = (1/|C_i|) sum_{x in C_i} x. This choice follows from minimising the sum of squared distances (see derivation below).
Lloyd's algorithm (standard K-means iterative procedure) — repeatedly apply these two steps until convergence:
- Assignment step: assign each point x to the cluster with the nearest centroid (by Euclidean distance).
- Update step: recompute each centroid μ_i as the mean of points assigned to cluster i. Stop when assignments do not change, or when centroids move less than a threshold, or max iterations reached.
K-means++ initialization — to reduce poor local minima, K-means++ chooses initial centres probabilistically: first pick one centre uniformly at random, then for each remaining centre choose a point x with probability proportional to D(x)^2, where D(x) is the distance from x to the nearest already-chosen centre. This gives better initial seeds in expectation.
Assumptions and limitations:
- K-means uses Euclidean distance and minimises variance in each cluster — it prefers roughly spherical clusters of similar size.
- Requires specifying k (number of clusters) beforehand. Common ways to choose k include the elbow method on inertia and the silhouette score (higher is better).
- Sensitive to scale: features must be standardised (z-score) or scaled if on different units.
- Sensitive to outliers, as centroids are means.
- Converges to a local minimum; results depend on initialization.
Convergence and complexity:
- Lloyd's algorithm decreases the objective every iteration and stops at a local minimum in a finite number of steps, but worst-case number of iterations can be large.
- Time complexity (typical) per run: O(n · k · d · t) where n = number of points, k = clusters, d = features, t = iterations. Memory O(n · d).
What to draw for an exam diagram: draw a 2D scatter plot of points, mark initial centroids as large crosses (label c1, c2, ...), draw straight-line Voronoi boundaries if needed, colour points by assignment, draw arrows from points to their centroid. After one iteration redraw new centroids and show movement vectors from old to new centroids.
Derivation of centroid update (commonly asked): Problem: For fixed cluster C, find μ that minimises f(μ) = sum_{x in C} ||x - μ||^2. Write f(μ) = sum_x (xᵀx - 2 xᵀμ + μᵀμ) = const - 2 (sum_x x)ᵀ μ + |C| μᵀ μ. Take gradient ∇_μ f = -2 sum_x x + 2 |C| μ. Set ∇_μ f = 0 ⇒ μ = (1/|C|) sum_x x. So the mean minimises the squared error.
Formulas
J = Σ_{i=1..k} Σ_{x ∈ C_i} ||x - μ_i||^2 — J is the K-means objective (sum of within-cluster squared Euclidean distances). Applies for Euclidean K-means. Units: squared feature units.
μ_i = (1/|C_i|) Σ_{x ∈ C_i} x — centroid is arithmetic mean of points in cluster C_i. μ_i has same units as features; applies when minimising J.
||x - μ|| = sqrt(Σ_{j=1..d} (x_j - μ_j)^2) — Euclidean distance between point and centroid. Units: same as feature units.
Time complexity ≈ O(n · k · d · t) — n: number of points, k: clusters, d: dimensions, t: number of iterations.
Syntax to remember (scikit-learn KMeans usage):
from sklearn.cluster import KMeans
KMeans(n_clusters=k, init='k-means++'|'random', n_init=10, max_iter=300, tol=1e-4, random_state=None)
km.fit(X) — fit model to data X (n_samples × n_features)
labels = km.labels_ — cluster label per sample after fit
centers = km.cluster_centers_ — array of centroids
labels = km.predict(X) — assign labels for new data X
labels = km.fit_predict(X) — fit then return labels
inertia = km.inertia_ — final value of the objective J (sum of squared distances). Units: squared feature units; not normalised by number of samples.
Worked examples
- Manual one-iteration example (typical short exam question) Data points: A(1,1), B(2,1), C(4,3), D(5,4). Let k = 2 and initial centroids c1 = (1,1), c2 = (5,4). Step 1 — assignment by Euclidean distance (show distances):
- d(A,c1) = ||(1,1)-(1,1)|| = 0; d(A,c2) = sqrt((1-5)^2+(1-4)^2) = sqrt(16+9)=5. So A→c1.
- d(B,c1) = sqrt((2-1)^2+(1-1)^2)=1; d(B,c2)=sqrt((2-5)^2+(1-4)^2)=sqrt(9+9)=sqrt(18)=4.242. B→c1.
- d(C,c1)=sqrt((4-1)^2+(3-1)^2)=sqrt(9+4)=sqrt(13)=3.606; d(C,c2)=sqrt((4-5)^2+(3-4)^2)=sqrt(1+1)=1.414. C→c2.
- d(D,c1)=sqrt((5-1)^2+(4-1)^2)=sqrt(16+9)=5; d(D,c2)=sqrt((5-5)^2+(4-4)^2)=0. D→c2. Assignments: C1 = {A,B}, C2 = {C,D}. Step 2 — update centroids (means):
- μ1 = mean of A(1,1) and B(2,1) = ((1+2)/2, (1+1)/2) = (1.5, 1.0).
- μ2 = mean of C(4,3) and D(5,4) = ((4+5)/2, (3+4)/2) = (4.5, 3.5). Final answer after one iteration: new centroids μ1 = (1.5, 1.0) and μ2 = (4.5, 3.5).
- Python program (simple 2-cluster dataset). This program uses scikit-learn's KMeans; random_state fixed to guarantee reproducible output.
Code:
import numpy as np
from sklearn.cluster import KMeans
# Define dataset explicitly (no external input)
X = np.array([
[1.0, 1.0],
[1.0, 2.0],
[2.0, 1.0],
[2.0, 2.0],
[8.0, 8.0],
[8.0, 9.0],
[9.0, 8.0],
[9.0, 9.0]
])
km = KMeans(n_clusters=2, init='k-means++', n_init=10, random_state=0)
labels = km.fit_predict(X)
centers = km.cluster_centers_
print('labels =', labels.tolist())
print('centers =', np.round(centers, 3).tolist())
print('inertia =', float(np.round(km.inertia_, 3)))
Sample exact output produced by the above program:
labels = [0, 0, 0, 0, 1, 1, 1, 1] centers = [[1.5, 1.5], [8.5, 8.5]] inertia = 4.0
(Explanation: the four points near (1,1) form cluster 0 with centroid (1.5,1.5); the four points near (8,8) form cluster 1 with centroid (8.5,8.5). The inertia is 4.0 because each point is at squared distance 0.5 from its centroid, 8 points × 0.5 = 4.0.)
- Program showing fit_predict and retrieving attributes (small variation):
import numpy as np
from sklearn.cluster import KMeans
X = np.array([[0.,0.],[0.,1.],[1.,0.],[10.,10.],[10.,11.],[11.,10.]])
km = KMeans(n_clusters=2, random_state=42)
labels = km.fit_predict(X)
print('labels =', labels.tolist())
print('cluster_centers =', np.round(km.cluster_centers_, 3).tolist())
print('inertia =', float(np.round(km.inertia_, 3)))
Exact sample output:
labels = [1, 1, 1, 0, 0, 0] cluster_centers = [[10.333, 10.333], [0.333, 0.333]] inertia = 2.667
(You should get the same output when running with scikit-learn >=0.22 and random_state=42.)
Common mistakes
- Using K-means for non-spherical clusters (e.g., concentric rings, different density) — results are misleading.
- Confusing k (number of clusters) with number of classes: K-means is unsupervised; clusters do not necessarily equal ground-truth classes.
- Misinterpreting cluster labels as ordered categories (labels are arbitrary indices).
- Forgetting to set random_state for reproducible outputs in assignments and for deterministic exam/program answers.
For your exam
Types of questions you will see:
- Definitions: define K-means, centroid, inertia, K-means++.
- Short notes: discuss assumptions and limitations; when to standardise.
- Derivations: derive why centroid is the mean (take derivative and set to zero). Draw the diagram of assignments and centroid updates.
- Numerical: one-iteration or two-iteration K-means by hand on 2D points; compute inertia.
- Programming: short programs using scikit-learn to fit KMeans and print centroids, labels, inertia; explain parameters.
What a full-marks answer includes:
- Correct definitions with bold terms, clear assumptions (Euclidean, numeric data), and step-by-step derivation where required.
- For numerical problems: distances computed, assignments listed, means shown with arithmetic, and final centroids/inertia with correct numeric rounding and units if any.
- For programming: code that runs, fixed random_state for reproducibility, and exact printed output or explanation of non-determinism.
Quick check
- What is minimised by K-means?
- Give the formula for the centroid of cluster C.
- Why should you scale features before K-means?
Answers: 1) The within-cluster sum of squared Euclidean distances (inertia). 2) μ = (1/|C|) Σ_{x∈C} x. 3) Because Euclidean distance is sensitive to feature scale; unscaled features distort cluster shapes.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?