Back to topic
Optional
k-NN majority vote
NumPy: distances, k nearest, majority class. Self-check in the notebook.
- Version
- v1
- Minutes
- ~15
- Evidence
- Self-check in the notebook
Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.
Download the notebook and run it locally. Its environment requirements are listed inside.
Notebook contents
Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.
ML · k-NN: голосование большинства / k-NN majority vote
Activity version: 1 · Seed: n/a · Данные: 5 обучающих точек в , запрос , .
Ожидаемые числа
| Quantity | Value | Tolerance |
|---|---|---|
| nearest indices | 1, 0, 4 |
exact |
| distances | ≈ 0.14142136, 0.22360680, 0.92195445 |
abs ≤ 1e-5 |
| prediction | 0 |
exact |
Самопроверка в ноутбуке
Не влияет на mastery.
import numpy as np
X_train = np.array([[0.0, 0.0], [0.1, 0.0], [1.0, 1.0], [1.1, 0.9], [0.0, 1.0]])
y_train = np.array([0, 0, 1, 1, 0])
x = np.array([0.2, 0.1])
k = 3
d = np.linalg.norm(X_train - x, axis=1)
idx = np.argsort(d)[:k]
votes = y_train[idx]
vals, counts = np.unique(votes, return_counts=True)
pred = vals[np.argmax(counts)]
print("dists", d)
print("nn", idx, "votes", votes, "pred", pred)
assert list(idx) == [1, 0, 4]
assert pred == 0
assert np.allclose(d[idx], [0.14142136, 0.22360680, 0.92195445], atol=1e-5)
print("OK: k-NN majority vote")
Самопроверка в ноутбуке
- три ближайших — индексы 1,0,4
- класс 0 побеждает 2:1