Assign Points to Nearest Centroid
~15 mincode completion
Implement assign_clusters(X, centroids) that returns the cluster label for each point.
Examples
Two clear clusters
- Input
- assign_clusters([[0, 0], [0.1, 0.1], [10, 10], [10.1, 9.9]], [[0, 0], [10, 10]])
- Output
- [0, 0, 1, 1]
Point equidistant picks lower index (argmin)
- Input
- assign_clusters([[5, 0]], [[0, 0], [10, 0]])
- Output
- [0]
3 centroids
- Input
- assign_clusters([[1, 0], [5, 0], [9, 0]], [[0, 0], [5, 0], [10, 0]])
- Output
- [0, 1, 2]
Hints
Hint 1
gives the magnitude in one call; pick the axis deliberately.
Hint 2
Watch for this: computed squared dist not euclidean.
Requirements
X: Data matrix of shape (n, d)centroids: Centroid matrix of shape (k, d)Return Integer array of shape (n,) with cluster indices in [0, k).
Use a fully vectorised implementation without Python loops
Constraints
Vectorised implementation only, no Python loops
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Try similar problems(1)
Where this shows up
~15 min
••
1 employer weight this skill
1 health and bio company. Top match scores 87.
Python
import numpy as np
def assign_clusters(X: np.ndarray, centroids: np.ndarray) -> np.ndarray:
"""
Assign each data point to the nearest centroid.
Args:
X: Data matrix of shape (n, d)
centroids: Centroid matrix of shape (k, d)
Returns:
Integer array of shape (n,) with cluster indices in [0, k).
"""
# YOUR CODE HERE
pass