---
title: k-nearest-neighbour classifier
url: https://gurkanozkan.ai/learn/coding/mle-k-nearest-neighbour-classifier-11/
markdown: https://gurkanozkan.ai/learn/coding/mle-k-nearest-neighbour-classifier-11.md
kind: coding
difficulty: Easy
topics:
  - K-NN
  - NumPy
json: https://gurkanozkan.ai/api/learn/coding/mle-k-nearest-neighbour-classifier-11.json
robots: noindex
---

# k-nearest-neighbour classifier

Classify each test point by majority vote among its `k` nearest training points (Euclidean). Break distance ties by the lower training index, and vote ties by the smallest label.

## Signature

```python
def knn_predict(X_train, y_train: list, X_test, k: int) -> list: ...
```

## Examples

Each call and the value it should give.

```python
>>> knn_predict([[0.0],[1.0],[10.0]], ['a','a','b'], [[0.4],[9.0]], 1) == ['a', 'b']
True

>>> knn_predict([[0.0],[1.0],[10.0]], ['a','a','b'], [[9.0]], 3) == ['a']
True
```

## Hints

1. For each test point, compute vectorised distances to all training points.
2. Take the k nearest; break distance ties by lower training index.
3. Vote ties by the smallest label — keep it deterministic.

## Reference solution

```python
from collections import Counter
import numpy as np

def knn_predict(X_train, y_train, X_test, k):
    Xtr = np.asarray(X_train, float)
    out = []
    for x in np.asarray(X_test, float):
        d = ((Xtr - x) ** 2).sum(1)
        order = np.argsort(d, kind="stable")[:k]
        votes = Counter(y_train[i] for i in order)
        best = max(votes.values())
        out.append(min(l for l, c in votes.items() if c == best))
    return out
```

## What a strong solution covers

- Stable sort or argpartition plus deterministic tie handling.
- Complexity O(n_test · n_train · d).
- Mentions KD-trees/ANN for scale, feature scaling, and distance weighting.

## Common mistakes

- a non-stable sort giving nondeterministic neighbours
- forgetting to scale features (discussion point).
---

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