Predict with distance-weighted k nearest neighbours
Why it matters Retrieval-based predictors (kNN-LM, embedding lookups) average neighbour labels the same way.
k-NN regression averages the targets of the k closest training points, giving closer points more say.
Write knn_regress(X_train, y_train, X_test, k). For each test row take the k nearest training rows (Euclidean; ties broken by lower index, use a stable sort) and return the weighted mean of their targets with weight 1 / (distance + 1e-9).
def knn_regress(X_train, y_train, X_test, k)Example
train [[0], [1], [3]] with y [0, 10, 30], test [[1]], k = 2 gives about 10.0, because the exact match dominates.
Understand the idea
k-nearest-neighbour regression predicts a number by looking at the k training points closest to the query and averaging their targets. Closer points should count more, so each neighbour gets weight 1 / distance. It is like guessing a flat's rent from the nearest few flats, trusting the one next door the most. Worked example: train x = [0, 2, 6], y = [0, 20, 60], query 1.5, k = 2. Distances are 1.5, 0.5 and 4.5. The two nearest are x = 2 (distance 0.5, weight 2) and x = 0 (distance 1.5, weight about 0.667). The prediction is (2 * 20 + 0.667 * 0) / (2 + 0.667) = 40 / 2.667 = 15. Rule: compute Euclidean distances, take the k smallest with a stable sort so equal distances keep the lower index, set w_i = 1 / (d_i + 1e-9), and return sum(w_i y_i) / sum(w_i). The tiny 1e-9 avoids dividing by zero when the query matches a training point exactly. Used in: simple tabular baselines, filling missing values, and retrieval-based prediction on embeddings.
Shapes and data flow
T (m, 1, d) - X (1, n, d) -> d (m, n) argsort[:, :k] -> idx (m, k), y[idx] (m, k) -> out (m,)