v9.1.1
Menu

K-Means Update Step

mediumPROClusteringMachine Learning 2

Implement the update step of the K-Means algorithm.

Given data points, current assignments, and the number of clusters kk, 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 dd integer zeros (e.g. [0, 0] for 2D points, not [0.0, 0.0]).

Round each centroid coordinate to 4 decimal places.

Example

Input
X = [[1, 0], [3, 0], [8, 0], [10, 0]]
assignments = [0, 0, 1, 1]
k = 2
Output
[[2.0, 0.0], [9.0, 0.0]]
Reasoning
  • X holds n=4n = 4 points in d=2d = 2 dimensions, all lying on the horizontal axis (every second coordinate is 00). assignments labels each point with its cluster: the first two belong to cluster 00, the last two to cluster 11. With k =2= 2 the result must contain exactly two centroids.
  • The new centroid of cluster cc is the coordinate-wise mean of its members: μc=1∣Sc∣∑x∈Scx\mu_c = \frac{1}{|S_c|}\sum_{x \in S_c} x, where ScS_c is the set of points labelled cc.
  • Cluster 00 has S0={(1,0),(3,0)}S_0 = \{(1,0), (3,0)\}, so μ0=(1+32,0+02)=(2,0)\mu_0 = \left(\frac{1+3}{2}, \frac{0+0}{2}\right) = (2, 0).
  • Cluster 11 has S1={(8,0),(10,0)}S_1 = \{(8,0), (10,0)\}, so μ1=(8+102,0+02)=(9,0)\mu_1 = \left(\frac{8+10}{2}, \frac{0+0}{2}\right) = (9, 0).
  • 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 11, μ1\mu_1 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

Learn this in

More from Machine Learning 2

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.