---
title: k-means (Lloyd's algorithm) with given initial centroids
url: https://gurkanozkan.ai/learn/coding/mle-k-means-lloyd-s-algorithm-with-given-initial-centroids-10/
markdown: https://gurkanozkan.ai/learn/coding/mle-k-means-lloyd-s-algorithm-with-given-initial-centroids-10.md
kind: coding
difficulty: Medium
topics:
  - Clustering
  - NumPy
  - From scratch
json: https://gurkanozkan.ai/api/learn/coding/mle-k-means-lloyd-s-algorithm-with-given-initial-centroids-10.json
robots: noindex
---

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

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

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

## Examples

Each call and the value it should give.

```python
>>> 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
```

## Hints

1. Compute all squared distances via broadcasting; assign to the nearest centroid.
2. Ties go to the lowest centroid index; update each centroid as the mean of its points.
3. Empty centroids keep their previous value; stop when assignments stop changing.

## Reference solution

```python
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.*
