Neural Mastery
← Back to Practice

K-Means: Centroid Update Step

Difficulty: Medium · Concept: K-Means & Hierarchical Clustering

K-Means: One Assignment Step implemented the assign half of Lloyd's algorithm — nearest-centroid lookup. This is the other half: update — given the current assignments, recompute each centroid as the mean of the points now assigned to it. Together, these two steps are the entire K-Means loop.

The genuine edge case a plain "average the points" implementation misses: a cluster can end up with zero points assigned to it (a bad random initialization, or a centroid that got pushed somewhere no point is closer to). Averaging zero points is a division by zero — a real implementation has to decide what happens then, and the standard, sane choice is: leave that centroid exactly where it was, rather than crash or silently produce nan.

Your task: implement kmeans_update_step(points, assignments, k, old_centroids). assignments[i] is the cluster index (0 to k-1) for points[i]. Return a list of k new centroid positions.

Implement it yourself
assert kmeans_update_step([[0, 0], [2, 0], [4, 4], [6, 4]], [0, 0, 1, 1], 2, [[0, 0], [5, 5]]) == [[1.0, 0.0], [5.0, 4.0]] assert kmeans_update_step([[1, 1], [2, 2]], [0, 0], 2, [[0, 0], [9, 9]]) == [[1.5, 1.5], [9, 9]] assert kmeans_update_step([[3, 3], [7, 7]], [0, 1], 2, [[0, 0], [0, 0]]) == [[3.0, 3.0], [7.0, 7.0]] assert kmeans_update_step([[1], [3], [5]], [0, 0, 0], 1, [[0]]) == [[3.0]]

Next: Sigmoid Activation From Scratch

Last updated Sep 5, 2026Edit this pageReport an issue