Homework · Runs in your browser
k-means and PCA from scratch in pure Python
Build the pieces of k-means and a two-column PCA with nothing but the standard library. Edit starter.py, then run the tests. In the browser runner, press Run tests. In Colab or on your own machine, put starter.py and test_starter.py in one folder and run pytest. Nothing needs installing except pytest.
Hints:
- Points and centres are lists of numbers. Use squared Euclidean distance (the helper sq_dist is given). When two centres are equally near, pick the lower index.
- update_centers moves each centre to the mean of the points assigned to it. A centre with no points stays where it was.
- kmeans repeats: assign, record the inertia of that assignment (with the centres used for it), update. Stop when the centres do not change. Do not change the list of starting centres you were given. The lesson example (points 1, 2, 4, 9, 10, 12 with centres 1 and 2) gives histories 217, 40.48 and 9.33.
- next_center is the k-means++ draw. Weights are squared distances to the nearest existing centre. Walk through the points in order, add up the weights, and return the first point whose running total is strictly greater than u times the total weight. If all weights are zero, return the first point.
- covariance_2d divides by n - 1. For the lesson points (8,18), (9,19), (10,21), (10,22), (11,20), (12,20) it gives rows (2, 1) and (1, 2).
- pca_2d has a closed form for a 2 by 2 symmetric matrix with entries a, b, b, d: the eigenvalues are (a + d)/2 plus or minus sqrt(((a - d)/2)^2 + b^2). For b not equal to 0, the vector (b, lambda1 - a) points along the first component; for b equal to 0 it is the first axis if a is at least d, otherwise the second. Normalise it to length 1 and flip it so that its first non-zero entry is positive.
- project centres the points (subtract the column means) and takes the dot product with the direction.
Running the tests needs JavaScript. You can still read the starter code below and run it on your own machine with pytest.
Tab inserts 4 spaces. To move on with the keyboard, press Esc, then Tab. Shift+Tab always moves back.
Show a solution
Try it yourself first. This site is static, so the solution is sent to your browser with the page; it is hidden here, not secret.
import math
def sq_dist(a, b):
return sum((x - y) ** 2 for x, y in zip(a, b))
def assign(points, centers):
"""Index of the nearest centre (squared Euclidean distance) for each point; ties go to the lowest index."""
return [min(range(len(centers)), key=lambda j: (sq_dist(p, centers[j]), j)) for p in points]
def update_centers(points, labels, centers):
"""Each centre moves to the mean of its points; a centre with no points stays where it is."""
new = []
for j, old in enumerate(centers):
rows = [p for p, lab in zip(points, labels) if lab == j]
new.append([sum(col) / len(rows) for col in zip(*rows)] if rows else list(old))
return new
def inertia(points, centers, labels):
"""Sum of squared distances from each point to its assigned centre."""
return sum(sq_dist(p, centers[lab]) for p, lab in zip(points, labels))
def kmeans(points, centers, max_iter=100):
"""Lloyd's loop from the given starting centres.
Each pass assigns, records the inertia of that assignment, and updates.
Stop when the centres no longer change. Return (centers, labels, history).
"""
centers = [list(c) for c in centers]
history = []
for _ in range(max_iter):
labels = assign(points, centers)
history.append(inertia(points, centers, labels))
new = update_centers(points, labels, centers)
if new == centers:
break
centers = new
return centers, labels, history
def next_center(points, centers, u):
"""The k-means++ draw. Weight each point by its squared distance to the nearest centre.
Walk through the points in order, keeping a running total of the weights, and
return the first point whose running total exceeds u * (total weight), where
0 <= u < 1. If every weight is zero, return the first point.
"""
weights = [min(sq_dist(p, c) for c in centers) for p in points]
total = sum(weights)
if total == 0:
return points[0]
running = 0.0
for p, w in zip(points, weights):
running += w
if running > u * total:
return p
return points[-1]
def covariance_2d(points):
"""Covariance matrix [[var_x, cov_xy], [cov_xy, var_y]] of two-column points, dividing by n - 1."""
n = len(points)
mx = sum(p[0] for p in points) / n
my = sum(p[1] for p in points) / n
a = sum((p[0] - mx) ** 2 for p in points) / (n - 1)
d = sum((p[1] - my) ** 2 for p in points) / (n - 1)
b = sum((p[0] - mx) * (p[1] - my) for p in points) / (n - 1)
return [[a, b], [b, d]]
def pca_2d(points):
"""Return (eigenvalues, first_component, ratios) for two-column points.
Eigenvalues are in descending order, the component is a unit vector whose
first non-zero entry is positive, and ratios are the eigenvalues over their sum.
"""
(a, b), (_, d) = covariance_2d(points)
mid, gap = (a + d) / 2, math.sqrt(((a - d) / 2) ** 2 + b * b)
lam1, lam2 = mid + gap, mid - gap
if b != 0:
v = (b, lam1 - a)
else:
v = (1.0, 0.0) if a >= d else (0.0, 1.0)
norm = math.hypot(*v)
v = [c / norm for c in v]
first = next(c for c in v if abs(c) > 1e-12)
if first < 0:
v = [-c for c in v]
total = lam1 + lam2
return [lam1, lam2], v, [lam1 / total, lam2 / total]
def project(points, direction):
"""Scores of the centred points along a direction (a dot product per point)."""
n = len(points)
mean = [sum(col) / n for col in zip(*points)]
return [sum((x - m) * c for x, m, c in zip(p, mean, direction)) for p in points]
Show the tests (test_starter.py)
import math
from starter import assign, covariance_2d, inertia, kmeans, next_center, pca_2d, project, update_centers
LESSON = [[8, 18], [9, 19], [10, 21], [10, 22], [11, 20], [12, 20]]
LINE = [[1], [2], [4], [9], [10], [12]]
R2 = math.sqrt(2)
def close(a, b, tol=1e-9):
return len(a) == len(b) and all(math.isclose(x, y, abs_tol=tol) for x, y in zip(a, b))
def test_assign_picks_the_nearest_centre():
assert assign([[0], [4], [9]], [[1], [8]]) == [0, 0, 1], "4 is 3 from the centre 1 and 4 from the centre 8"
def test_assign_uses_euclidean_distance_in_two_dimensions():
assert assign([[0, 0]], [[3, 0], [2, 2]]) == [1], "squared distances are 9 and 8, even though the sums of absolute differences are 3 and 4"
def test_assign_sends_ties_to_the_lowest_index():
assert assign([[5]], [[3], [7]]) == [0]
assert assign([[5]], [[7], [3]]) == [0], "the tie goes to index 0 whichever centre sits there"
def test_update_moves_each_centre_to_the_mean():
new = update_centers([[0, 0], [2, 4], [10, 2], [20, 20]], [0, 0, 0, 1], [[5, 5], [5, 5]])
assert new == [[4, 2], [20, 20]], "the mean of (0,0), (2,4), (10,2) is (4,2); a median would give (2,2)"
def test_update_keeps_a_centre_with_no_points():
assert update_centers([[0], [2]], [0, 0], [[9], [100]]) == [[1], [100]], "an empty cluster keeps its old centre"
def test_inertia_sums_squared_distances():
assert inertia([[0], [2], [10]], [[1], [9]], [0, 0, 1]) == 3
assert inertia([[0, 0]], [[3, 4]], [0]) == 25, "squared distance, not distance"
def test_kmeans_reproduces_the_lesson_example():
centers, labels, history = kmeans(LINE, [[1], [2]])
assert close([c[0] for c in centers], [7 / 3, 31 / 3])
assert labels == [0, 0, 0, 1, 1, 1]
assert close(history, [217, 1012 / 25, 28 / 3]), "J is recorded at each assignment, before the update"
def test_kmeans_never_raises_the_inertia():
pts = [[0, 0], [0, 1], [1, 0], [5, 5], [6, 5], [5, 6], [9, 0], [10, 1], [9, 2], [3, 8]]
centers, labels, history = kmeans(pts, [[0, 0], [5, 5], [9, 0]])
assert all(a >= b - 1e-12 for a, b in zip(history, history[1:]))
assert len(history) >= 2 and history[0] > history[-1]
assert math.isclose(history[-1], inertia(pts, centers, labels)), "the last entry is the inertia of the final clustering"
def test_kmeans_stops_at_once_when_nothing_moves():
centers, labels, history = kmeans([[0], [1], [10], [11]], [[0.5], [10.5]])
assert history == [1.0] and labels == [0, 0, 1, 1] and centers == [[0.5], [10.5]]
def test_kmeans_runs_until_the_centres_stop_moving():
pts = [[0], [1], [3], [7], [15], [31], [63], [127]]
centers, labels, history = kmeans(pts, [[0], [1]])
assert len(history) == 4 and labels == [0, 0, 0, 0, 0, 0, 1, 1], "four passes, not a fixed number"
assert close([c[0] for c in centers], [9.5, 95.0]) and close(history[-1:], [2751.5])
def test_kmeans_respects_max_iter():
centers, labels, history = kmeans(LINE, [[1], [2]], max_iter=1)
assert len(history) == 1 and close([c[0] for c in centers], [1, 37 / 5]), "one pass: assign, then update"
def test_kmeans_does_not_modify_the_starting_centres():
start = [[1], [2]]
kmeans(LINE, start)
assert start == [[1], [2]]
def test_next_center_weights_by_squared_distance():
pts, centers = [[0], [1], [3]], [[0]] # weights 0, 1, 9; total 10
assert next_center(pts, centers, 0.05) == [1]
assert next_center(pts, centers, 0.2) == [3], "with plain distances (0, 1, 3) the draw at 0.2 would be [1]"
def test_next_center_needs_a_running_total_strictly_above_the_target():
pts, centers = [[0], [1], [3]], [[0]]
assert next_center(pts, centers, 0.09) == [1]
assert next_center(pts, centers, 0.1) == [3], "the running total 1 does not exceed the target 1.0"
def test_next_center_never_returns_an_existing_centre():
assert next_center([[0], [1], [3]], [[0]], 0.0) == [1], "a point with weight 0 cannot be drawn"
def test_next_center_with_all_weights_zero():
assert next_center([[1], [2]], [[1], [2]], 0.5) == [1], "every point is already a centre, so return the first point"
def test_covariance_divides_by_n_minus_one():
assert close(sum(covariance_2d(LESSON), []), [2, 1, 1, 2])
def test_pca_on_the_lesson_example():
values, v, ratios = pca_2d(LESSON)
assert close(values, [3, 1]) and close(v, [1 / R2, 1 / R2]) and close(ratios, [0.75, 0.25])
def test_pca_sign_convention_for_negative_correlation():
values, v, ratios = pca_2d([[x, -y] for x, y in LESSON])
assert close(values, [3, 1]) and close(v, [1 / R2, -1 / R2]), "first non-zero entry positive"
def test_pca_axis_aligned_data():
wide = [[-2, 0], [0, 1], [0, -1], [2, 0]]
values, v, ratios = pca_2d(wide)
assert close(values, [8 / 3, 2 / 3]) and close(v, [1, 0]) and close(ratios, [0.8, 0.2])
values, v, ratios = pca_2d([[y, x] for x, y in wide])
assert close(v, [0, 1]), "when the second column has more variance, the first component is the second axis"
def test_project_centres_before_projecting():
scores = project(LESSON, [1 / R2, 1 / R2])
assert close([s * R2 for s in scores], [-4, -2, 1, 2, 1, 2])
def test_pca_with_unequal_variances_and_correlation():
pts = [[x + 7, y + 3] for x, y in [(-3, -2), (-1, 0), (0, 0), (1, 2), (3, 0)]]
cov = covariance_2d(pts)
assert close(sum(cov, []), [5, 2, 2, 2])
values, v, ratios = pca_2d(pts)
assert close(values, [6, 1]) and close(ratios, [6 / 7, 1 / 7])
assert close(v, [2 / math.sqrt(5), 1 / math.sqrt(5)]), "the eigenvector for eigenvalue 6 is (2, 1) / sqrt(5)"
sv = [cov[0][0] * v[0] + cov[0][1] * v[1], cov[1][0] * v[0] + cov[1][1] * v[1]]
assert close(sv, [6 * c for c in v]), "Sigma v = lambda v"
def test_next_center_uses_the_nearest_of_all_centres():
pts, centers = [[0], [1], [10], [12]], [[0], [10]] # weights 0, 1, 0, 4; total 5
assert next_center(pts, centers, 0.1) == [1]
assert next_center(pts, centers, 0.3) == [12], "distance to the newest centre alone would give a different draw"