K-Means Update Step
Implement the update step of the K-Means algorithm.
Given data points, current assignments, and the number of clusters , compute new centroids as the mean of all points assigned to each cluster.
Return the new centroids as a 2D list. If a cluster has no points, keep its centroid at the origin: a list of integer zeros (e.g. [0, 0] for 2D points, not [0.0, 0.0]).
Round each centroid coordinate to 4 decimal places.
Example
X = [[1, 0], [3, 0], [8, 0], [10, 0]] assignments = [0, 0, 1, 1] k = 2
[[2.0, 0.0], [9.0, 0.0]]
Xholds points in dimensions, all lying on the horizontal axis (every second coordinate is ).assignmentslabels each point with its cluster: the first two belong to cluster , the last two to cluster . Withkthe result must contain exactly two centroids.- The new centroid of cluster is the coordinate-wise mean of its members: , where is the set of points labelled .
- Cluster has , so .
- Cluster has , so .
- Rounded to 4 decimal places these stay
[[2.0, 0.0], [9.0, 0.0]]; they print as decimals because a mean is a division. - Notice each centroid sits exactly midway between its two points, and the old centroid positions play no role. Had no point been labelled , would be the origin instead.
Constraints
- X: 2D list of data points (n x d)
- assignments: list of n cluster indices (0 to k-1)
- k: number of clusters
- Return 2D list of k centroids, each rounded to 4 decimal places
- Empty clusters get centroid at origin