Feature-Weighted Euclidean KNN Classifier

Quick Overview

Implement a k-nearest-neighbor classifier in NumPy that uses a per-feature weighted Euclidean distance. It tests vectorized distance computation, input validation, deterministic tie-breaking for both neighbors and votes, and the cost of brute-force search.

Feature-Weighted Euclidean KNN Classifier

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement k-nearest-neighbor classification with a diagonal weighted Euclidean distance $$d(x, y) = \sqrt{\sum_j w_j (x_j - y_j)^2}$$ This is equivalent to plain Euclidean distance after scaling each feature by $\sqrt{w_j}$. Write three functions that return a distance matrix, the k nearest neighbors per query, and majority-vote labels. - `weighted_euclidean_distances(X, Y, weights)` returns a `(len(X), len(Y))` float matrix. - `weighted_kneighbors(X_train, X_query, weights, k)` returns `(distances, indices)`, each of shape `(n_query, k)`, sorted ascending by distance. Equal distances break to the lower training index. Indices are `int64`. - `weighted_knn_predict(X_train, y_train, X_query, weights, k)` returns an unweighted majority vote over the k neighbors. Vote ties go to the smallest label. Raise `ValueError` for negative or non-finite weights, a weights length not equal to the feature count, mismatched feature counts, `k` outside `[1, n_train]`, or a `y_train` length mismatch. Two examples: ```python X = [[0, 0], [1, 1]] Y = [[3, 4]] weights = [1, 4] weighted_euclidean_distances(X, Y, weights) # [[sqrt(73)], [sqrt(40)]] since 1*9 + 4*16 = 73 and 1*4 + 4*9 = 40 X_train = [[1, 0], [0, 1], [-1, 0], [2, 2]] X_query = [[0, 0]] weighted_kneighbors(X_train, X_query, weights=[4, 1], k=3) # distances [[1, 2, 2]], indices [[1, 0, 2]] ``` ```hint Equal distances The tie rule only works if two equal distances come out bit-for-bit equal and the sort keeps equal keys in index order. Check both the floating-point arithmetic and the `kind` argument of `np.argsort`. ``` ```hint Vote ties Think about the order of the classes in your count array and which index `np.argmax` returns when two counts are equal. ``` ### Constraints & Assumptions - Weights are 1-D with one entry per feature. A weight of `0` means the feature is ignored. - Labels may be any sortable values (for example, integers). - Brute-force search is acceptable: `n_train` and `n_query` are at most a few hundred. ### What a Strong Answer Covers - A vectorized weighted distance computation and why it matches Euclidean distance on rescaled features. - Validation that covers every listed `ValueError` case. - Neighbor ordering that stays deterministic when distances are equal, with `int64` indices. - A majority vote that works for any sortable labels and applies the smallest-label tie rule. - The time and memory cost of brute-force search. ### Follow-up Questions - How would you learn the weights instead of hand-setting them? - How does this generalize to a full Mahalanobis metric? - How would you avoid the O(n·m·d) memory of the broadcast difference tensor?

Overview: Implement a k-nearest-neighbor classifier in NumPy that uses a per-feature weighted Euclidean distance. It tests vectorized distance computation, input validation, deterministic tie-breaking for both neighbors and votes, and the cost of brute-force search.

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

Implement k-nearest-neighbor classification with a diagonal weighted Euclidean distance

d(x,y)=∑jwj(xj−yj)2d(x, y) = \sqrt{\sum_j w_j (x_j - y_j)^2}

This is equivalent to plain Euclidean distance after scaling each feature by wj\sqrt{w_j}. Write three functions that return a distance matrix, the k nearest neighbors per query, and majority-vote labels.

  • weighted_euclidean_distances(X, Y, weights) returns a (len(X), len(Y)) float matrix.
  • weighted_kneighbors(X_train, X_query, weights, k) returns (distances, indices) , each of shape (n_query, k) , sorted ascending by distance. Equal distances break to the lower training index. Indices are int64 .
  • weighted_knn_predict(X_train, y_train, X_query, weights, k) returns an unweighted majority vote over the k neighbors. Vote ties go to the smallest label.

Raise ValueError for negative or non-finite weights, a weights length not equal to the feature count, mismatched feature counts, k outside [1, n_train], or a y_train length mismatch.

Two examples:

X = [[0, 0], [1, 1]]
Y = [[3, 4]]
weights = [1, 4]
weighted_euclidean_distances(X, Y, weights)
# [[sqrt(73)], [sqrt(40)]]   since 1*9 + 4*16 = 73 and 1*4 + 4*9 = 40

X_train = [[1, 0], [0, 1], [-1, 0], [2, 2]]
X_query = [[0, 0]]
weighted_kneighbors(X_train, X_query, weights=[4, 1], k=3)
# distances [[1, 2, 2]], indices [[1, 0, 2]]

Constraints & Assumptions

  • Weights are 1-D with one entry per feature. A weight of 0 means the feature is ignored.
  • Labels may be any sortable values (for example, integers).
  • Brute-force search is acceptable: n_train and n_query are at most a few hundred.

What a Strong Answer Covers Guidance

  • A vectorized weighted distance computation and why it matches Euclidean distance on rescaled features.
  • Validation that covers every listed ValueError case.
  • Neighbor ordering that stays deterministic when distances are equal, with int64 indices.
  • A majority vote that works for any sortable labels and applies the smallest-label tie rule.
  • The time and memory cost of brute-force search.

Follow-up Questions Guidance

  • How would you learn the weights instead of hand-setting them?
  • How does this generalize to a full Mahalanobis metric?
  • How would you avoid the O(n·m·d) memory of the broadcast difference tensor?