Run one iteration of k-means
k-means alternates two steps: give every point to its nearest centroid, then move each centroid to the mean of its points.
Write kmeans_step(X, centroids) that does one full iteration and returns (labels, new_centroids). labels is a list of ints. Ties go to the lower centroid index. If a centroid gets no points, keep it where it was.
def kmeans_step(X, centroids)Understand the idea
k-means groups points around centres by repeating two steps. First, each point joins its nearest centroid. Second, each centroid moves to the average of the points that joined it. Think of shops moving to the middle of their regular customers. Squared distance is enough for choosing the nearest, since the square root does not change the order. Worked example, 1D: X = [0, 1, 9, 10], centroids [0, 5]. Point 0 is nearest centroid 0. Point 1 is 1 from centroid 0 and 4 from centroid 1, so centroid 0. Points 9 and 10 go to centroid 1. New centroids: mean(0, 1) = 0.5 and mean(9, 10) = 9.5. Labels [0, 0, 1, 1]. A point exactly halfway goes to the lower index. If a centroid gets no points, it has no mean, so leave it where it was instead of moving it to zero. Rule: assign by argmin of squared distance, then centroid = mean of its members. k-means is used to cluster embeddings and build vector index partitions.