Clustering
Update Centroids
Recompute each centroid as the mean of its assigned points (k-means update
step). A loop over points accumulates per-cluster sums and counts; a second
loop divides. Library: NumPy boolean indexing points[assignments==c].mean.
RESULT: updated centroid list [[cx0,cy0],[cx1,cy1]] (rounded).
By hand
With NumPy
points[assignments == c] selects rows for cluster c; .mean(axis=0)
averages along rows, giving the new centroid coordinates.
naive.py
points = [[1,2],[2,1],[1,3],[7,6],[8,7],[6,8]]
assignments = [0, 0, 0, 1, 1, 1]
k = 2
sums = [[0.0, 0.0], [0.0, 0.0]]
counts = [0, 0]
for i in range(len(points)):
c = assignments[i]
sums[c][0] = sums[c][0] + points[i][0]
sums[c][1] = sums[c][1] + points[i][1]
counts[c] = counts[c] + 1
centroids = []
for c in range(k):
cx = round(sums[c][0] / counts[c], 4)
cy = round(sums[c][1] / counts[c], 4)
centroids.append([cx, cy])
print('RESULT:', centroids)
library.py
import numpy as np
from dalib.display import set_display
set_display()
points = np.array([[1,2],[2,1],[1,3],[7,6],[8,7],[6,8]], dtype=float)
assignments = np.array([0, 0, 0, 1, 1, 1])
centroids = []
for c in range(2):
cluster_pts = points[assignments == c]
cx = round(float(cluster_pts[:, 0].mean()), 4)
cy = round(float(cluster_pts[:, 1].mean()), 4)
centroids.append([cx, cy])
print('cluster_sizes:', [int(np.sum(assignments == c)) for c in range(2)])
print('RESULT:', centroids)
cluster_sizes: [3, 3]
RESULT: [[1.3333, 2.0], [7.0, 7.0]]
Implementation notes
sums[c][0] = sums[c][0] + points[i][0]accumulates x-coordinates per cluster;sums[c][1]accumulates y-coordinates. One loop handles all k clusters without if/else by indexing sums and counts with the assignment.- After one assign+update cycle (this chapter), c0 moves from [1,1] to [1.3333,2.0] and c1 stays at [7.0,7.0] (already the true mean). A second cycle's assign step would produce the same assignments — convergence in 1.
- k-means does not guarantee the global optimum — initialization matters.
assign-to-centroidsandupdate-centroidsare the two steps of a single k-means iteration (assign, then update);kmeans-one-iterationcombines them; full k-means repeats this cycle until centroid change < tolerance.