Hamming and Jaccard Distance KNN

Quick Overview

Implement Hamming and Jaccard distances and a k-nearest-neighbor classifier built on them in NumPy. It tests vectorized pairwise distances, the empty-union edge case, deterministic tie-breaking for neighbors and votes, and input validation.

Hamming and Jaccard Distance KNN

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: easy

Interview Round: Other

Implement five functions for k-nearest-neighbor classification with two distances: - `hamming_distance(a, b)` and `jaccard_distance(a, b)` for two 1-D vectors. - `pairwise_distances(X, Y, metric="hamming")` for every row of `X` against every row of `Y`. - `knn_neighbors(X_train, X_query, k, metric="hamming")` for the k nearest training rows of each query. - `knn_predict(X_train, y_train, X_query, k, metric="hamming")` for majority-vote labels. Hamming is the fraction of mismatched positions (it works on categorical values such as strings). Jaccard treats any nonzero entry as 1 and returns ${1 - |A \cap B| / |A \cup B|}$. Example: ```python a = [1, 1, 0, 1, 0] b = [1, 0, 0, 1, 1] hamming_distance(a, b) # 0.4 (2 of 5 positions differ) jaccard_distance(a, b) # 0.5 (intersection 2, union 4) jaccard_distance([0, 0, 0], [0, 0, 0]) # 0.0 ``` ```hint Jaccard for many rows After binarizing, think about which matrix product of the two inputs counts the shared nonzero positions for every pair at once, and guard the pairs whose union is empty. ``` ### Constraints & Assumptions - Scalar distances return a Python `float`. Two all-zero vectors have Jaccard distance `0.0`. - `pairwise_distances` returns a float array of shape `(len(X), len(Y))`. A 1-D input is treated as a single row. - `knn_neighbors` returns `(indices, distances)`, each of shape `(n_query, k)`, sorted by ascending distance, with ties broken by lower training index. - `knn_predict` uses majority vote, with ties broken by smallest label, and its output dtype matches `y_train`. - Raise `ValueError` for an unknown metric, mismatched vector shapes or feature dimensions, or `k` outside `[1, n_train]`. ### What a Strong Answer Covers - Both metrics computed correctly, including categorical values for Hamming and binarization plus the empty-union case for Jaccard. - One vectorized pairwise matrix that the scalar functions and the neighbor search reuse. - Deterministic neighbor order and vote tie-breaking as specified, with the output dtype matching `y_train`. - Validation for every listed `ValueError` case. - The time and memory cost, and which metric's broadcast becomes the bottleneck. ### Follow-up Questions - How would you handle mixed numeric and categorical features? - Why can Jaccard be preferable to Hamming for sparse binary data? - How would you find Jaccard neighbors among millions of sparse rows without building a full distance matrix?

Overview: Implement Hamming and Jaccard distances and a k-nearest-neighbor classifier built on them in NumPy. It tests vectorized pairwise distances, the empty-union edge case, deterministic tie-breaking for neighbors and votes, and input validation.

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

Implement five functions for k-nearest-neighbor classification with two distances:

  • hamming_distance(a, b) and jaccard_distance(a, b) for two 1-D vectors.
  • pairwise_distances(X, Y, metric="hamming") for every row of X against every row of Y .
  • knn_neighbors(X_train, X_query, k, metric="hamming") for the k nearest training rows of each query.
  • knn_predict(X_train, y_train, X_query, k, metric="hamming") for majority-vote labels.

Hamming is the fraction of mismatched positions (it works on categorical values such as strings). Jaccard treats any nonzero entry as 1 and returns 1−∣A∩B∣/∣A∪B∣{1 - |A \cap B| / |A \cup B|}.

Example:

a = [1, 1, 0, 1, 0]
b = [1, 0, 0, 1, 1]
hamming_distance(a, b)                    # 0.4  (2 of 5 positions differ)
jaccard_distance(a, b)                    # 0.5  (intersection 2, union 4)
jaccard_distance([0, 0, 0], [0, 0, 0])    # 0.0

Constraints & Assumptions

  • Scalar distances return a Python float . Two all-zero vectors have Jaccard distance 0.0 .
  • pairwise_distances returns a float array of shape (len(X), len(Y)) . A 1-D input is treated as a single row.
  • knn_neighbors returns (indices, distances) , each of shape (n_query, k) , sorted by ascending distance, with ties broken by lower training index.
  • knn_predict uses majority vote, with ties broken by smallest label, and its output dtype matches y_train .
  • Raise ValueError for an unknown metric, mismatched vector shapes or feature dimensions, or k outside [1, n_train] .

What a Strong Answer Covers Guidance

  • Both metrics computed correctly, including categorical values for Hamming and binarization plus the empty-union case for Jaccard.
  • One vectorized pairwise matrix that the scalar functions and the neighbor search reuse.
  • Deterministic neighbor order and vote tie-breaking as specified, with the output dtype matching y_train .
  • Validation for every listed ValueError case.
  • The time and memory cost, and which metric's broadcast becomes the bottleneck.

Follow-up Questions Guidance

  • How would you handle mixed numeric and categorical features?
  • Why can Jaccard be preferable to Hamming for sparse binary data?
  • How would you find Jaccard neighbors among millions of sparse rows without building a full distance matrix?