v9.1.1
Menu

K-Means Assignment Step

easyFREEClusteringMachine Learning 2

Implement the assignment step of the K-Means algorithm.

Given data points and current centroids, assign each point to the nearest centroid using Euclidean distance.

Return a list of cluster assignments (0-indexed centroid indices). If a point is equidistant from multiple centroids, assign it to the one with the smallest index.

Example

Input
X = [[1, 0], [2, 0], [8, 0], [9, 0]]
centroids = [[1.5, 0], [8.5, 0]]
Output
[0, 0, 1, 1]
Reasoning
  • X holds n=4n = 4 points in d=2d = 2 dimensions, all on the horizontal axis; centroids holds k=2k = 2 cluster centres, at (1.5,0)(1.5, 0) and (8.5,0)(8.5, 0). The answer gives, for each point, the index of its closest centre.
  • The Euclidean distance between a point xx and a centre cc is ∥x−c∥=∑j=1d(xj−cj)2\lVert x - c \rVert = \sqrt{\sum_{j=1}^{d} (x_j - c_j)^2}.
  • Point (1,0)(1, 0): distance to centre 0 is (1−1.5)2+02=0.5\sqrt{(1-1.5)^2 + 0^2} = 0.5, distance to centre 1 is (1−8.5)2=7.5\sqrt{(1-8.5)^2} = 7.5. Centre 0 is closer, so its label is 00.
  • Point (2,0)(2, 0): distances 0.50.5 and 6.56.5, label 00. Point (8,0)(8, 0): distances 6.56.5 and 0.50.5, label 11. Point (9,0)(9, 0): distances 7.57.5 and 0.50.5, label 11.
  • Collecting the labels in the order the points appear gives [0, 0, 1, 1]: a list of nn integers, one per point, each between 00 and k−1k-1.
  • Notice the tie rule: a point exactly halfway between two centres, such as 55 between 00 and 1010 (both at distance 55), takes the smaller index, 00.

Constraints

  • X: 2D list of data points (n x d)
  • centroids: 2D list of centroid positions (k x d)
  • Return list of n integers (cluster assignments, 0-indexed)

Learn this in

More from Machine Learning 2

solution.py

Test results

Sign in to run your code against the test cases.