Before you start
Implement k-nearest-neighbours classification with Euclidean distance.
For every row of X_test, find the k closest rows of X_train and return
the most common label among them.
Two ties have to be resolved, and the tests check both:
X_train comes first.np.argsort(..., kind="stable") handles the first, since it keeps the
original order of equal elements.
Try to avoid a Python loop over training points. The full distance matrix is
one broadcast: X_test[:, None, :] - X_train[None, :, :].
def knn_predict(X_train, y_train, X_test, k):
Input
X_train = np.array([[0.0], [1.0], [4.0], [5.0]])
y_train = np.array([0, 0, 1, 1])
knn_predict(X_train, y_train, np.array([[0.5], [4.5]]), k=1)
Output
array([0, 1])
Reasoning
0.5 is the same distance from 0.0 and 1.0, so the lower index, 0.0, is chosen, with label 0. 4.5 is the same distance from 4.0 and 5.0, and 4.0 comes first, with label 1.
Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell