Distance-Weighted KNN Regression and Probabilities

Quick Overview

Implement inverse-distance-weighted k-nearest neighbours in NumPy for regression, class probabilities and classification, including a special rule for neighbours at zero distance. It tests vectorised distance computation, numerically safe weighting, deterministic tie-breaking and correct accumulation of weights per class.

Distance-Weighted KNN Regression and Probabilities

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement inverse-distance-weighted KNN using Euclidean distance. `inverse_distance_weights(distances)` normalises `1/d` per row so weights sum to 1. If a row contains any zero distance, those zero-distance neighbours share the weight equally and all others get 0. Use these weights in `weighted_knn_regress` (weighted mean target), `weighted_knn_predict_proba` (summed weight per class) and `weighted_knn_classify` (argmax label). Each of the three takes `(X_train, y_train, X_query, k)`. Example: ```python inverse_distance_weights([[1, 2, 4], [0, 3, 0]]) # [[4/7, 2/7, 1/7], [0.5, 0.0, 0.5]] X = [[10,0,1], [0,0,0], [10,0,3]] y = [7, 1, 3] weighted_knn_predict_proba(X, y, [[10,0,0]], k=2) # [[0.0, 0.25, 0.75]] # columns = classes [1, 3, 7] ``` ```hint Exact matches Decide each row's case from a boolean mask of zero distances before you divide anything. ``` ```hint Scattering weights into classes The same class can appear more than once among a query's neighbours. Check that the way you add weights into the probability matrix counts every occurrence. ``` ### Constraints & Assumptions - `inverse_distance_weights` accepts a 1-D row or 2-D array and returns the same shape. - Distance ties when selecting neighbours break to the lower training index. - Probability output has shape `(n_query, n_classes)` with columns in sorted order of `np.unique(y_train)`. Classify ties go to the smallest label. - Raise `ValueError` if inputs are not 2-D, feature counts differ, or `k` is outside the range 1 to `n_train` inclusive. ### What a Strong Answer Covers - Vectorised Euclidean distances and a stable neighbour selection that sends distance ties to the lower training index. - The zero-distance rule implemented without producing `inf` or `NaN`, with every row normalised to sum to 1 for both 1-D and 2-D input. - Probability columns aligned to the sorted classes, repeated classes in a neighbour set accumulated correctly, and argmax ties resolved to the smallest label. - The required `ValueError` checks. - The time and memory cost of the pairwise distance computation. ### Follow-up Questions - Why not just add a small epsilon to distances instead of the zero-distance rule? - How would you scale this to large training sets? - How does feature scaling affect inverse-distance weighting?

Overview: Implement inverse-distance-weighted k-nearest neighbours in NumPy for regression, class probabilities and classification, including a special rule for neighbours at zero distance. It tests vectorised distance computation, numerically safe weighting, deterministic tie-breaking and correct accumulation of weights per class.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement inverse-distance-weighted KNN using Euclidean distance. inverse_distance_weights(distances) normalises 1/d per row so weights sum to 1. If a row contains any zero distance, those zero-distance neighbours share the weight equally and all others get 0. Use these weights in weighted_knn_regress (weighted mean target), weighted_knn_predict_proba (summed weight per class) and weighted_knn_classify (argmax label). Each of the three takes (X_train, y_train, X_query, k).

Example:

inverse_distance_weights([[1, 2, 4], [0, 3, 0]])
# [[4/7, 2/7, 1/7], [0.5, 0.0, 0.5]]

X = [[10,0,1], [0,0,0], [10,0,3]]
y = [7, 1, 3]
weighted_knn_predict_proba(X, y, [[10,0,0]], k=2)
# [[0.0, 0.25, 0.75]]   # columns = classes [1, 3, 7]

Constraints & Assumptions

  • inverse_distance_weights accepts a 1-D row or 2-D array and returns the same shape.
  • Distance ties when selecting neighbours break to the lower training index.
  • Probability output has shape (n_query, n_classes) with columns in sorted order of np.unique(y_train) . Classify ties go to the smallest label.
  • Raise ValueError if inputs are not 2-D, feature counts differ, or k is outside the range 1 to n_train inclusive.

What a Strong Answer Covers Guidance

  • Vectorised Euclidean distances and a stable neighbour selection that sends distance ties to the lower training index.
  • The zero-distance rule implemented without producing inf or NaN , with every row normalised to sum to 1 for both 1-D and 2-D input.
  • Probability columns aligned to the sorted classes, repeated classes in a neighbour set accumulated correctly, and argmax ties resolved to the smallest label.
  • The required ValueError checks.
  • The time and memory cost of the pairwise distance computation.

Follow-up Questions Guidance

  • Why not just add a small epsilon to distances instead of the zero-distance rule?
  • How would you scale this to large training sets?
  • How does feature scaling affect inverse-distance weighting?