Update Centroids

~15 mincode completion

Implement update_centroids(X, labels, k) that returns the new centroid matrix of shape (k, d).

Examples

Two clusters: centroids at their means

Input
update_centroids([[0, 0], [2, 0], [10, 0], [12, 0]], [0, 0, 1, 1], 2)
Output
[[1, 0], [11, 0]]

All points in one cluster

Input
update_centroids([[1, 1], [3, 3], [5, 5]], [0, 0, 0], 1)
Output
[[3, 3]]

Hints

Hint 1

The reduction runs down the columns, so pass .

Hint 2

Watch for this: mean over wrong axis.

Requirements

  • X: Data matrix of shape (n, d)

  • labels: Cluster assignment array of shape (n,), values in [0, k)

  • k: Number of clusters

  • Return Centroid matrix of shape (k, d).

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

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 update_centroids(X: np.ndarray, labels: np.ndarray, k: int) -> np.ndarray:
    """
    Compute new centroids as the mean of assigned points.

    Args:
        X:      Data matrix of shape (n, d)
        labels: Cluster assignment array of shape (n,), values in [0, k)
        k:      Number of clusters

    Returns:
        Centroid matrix of shape (k, d).
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.