LearnCoding

k-means (Lloyd's algorithm) with given initial centroids

MediumClustering, NumPy, From scratch

Problem

Run Lloyd’s algorithm from init_centroids: - Assign each point to the nearest centroid by squared Euclidean distance (ties go to the lowest centroid index). - Recompute each centroid as the mean of its points. A centroid with no points keeps its previous value. - Stop when assignments do not change from the previous iteration, or after max_iter iterations. Return (centroids, labels).

Signature

def kmeans(X, init_centroids, max_iter: int = 100) -> tuple[np.ndarray, list[int]]: ...

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

>>> close(kmeans([[0.0],[1.0],[10.0],[11.0]], [[0.0],[10.0]]), ([[0.5],[10.5]], [0, 0, 1, 1]))
True

>>> close(kmeans([[0.0],[1.0],[10.0],[11.0]], [[0.0],[1.0]]), ([[0.5],[10.5]], [0, 0, 1, 1]))
True

Solve it in your own editor; nothing on this page runs code.

Hints

Compute all squared distances via broadcasting; assign to the nearest centroid.

Ties go to the lowest centroid index; update each centroid as the mean of its points.

Empty centroids keep their previous value; stop when assignments stop changing.

Reference solution

import numpy as np

def kmeans(X, init_centroids, max_iter=100):
    X = np.asarray(X, float)
    C = np.asarray(init_centroids, float).copy()
    labels = None
    for _ in range(max_iter):
        d = ((X[:, None, :] - C[None, :, :]) ** 2).sum(-1)
        new = d.argmin(axis=1)  # argmin picks lowest index on ties
        if labels is not None and np.array_equal(new, labels):
            break
        labels = new
        for j in range(len(C)):
            m = labels == j
            if m.any():
                C[j] = X[m].mean(axis=0)
    return C, labels.tolist()

What a strong solution covers

  • Vectorised distance matrix via broadcasting.
  • Correct convergence check and empty-cluster handling.
  • Discusses k-means++ initialisation, choosing k (elbow/silhouette), scaling features, and O(n·k·d) per iteration.

Common mistakes

  • dividing by zero for empty clusters
  • stopping on centroid equality with float noise.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.