Vectorized LOOCV for Choosing k in KNN

Quick Overview

Implement leave-one-out cross-validation for a k-nearest neighbors classifier that scores every k up to k_max from one distance matrix and one sort per row, then picks the best k. It tests vectorized NumPy, cumulative vote counting, self-exclusion with duplicate points and deterministic tie rules.

Vectorized LOOCV for Choosing k in KNN

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `loo_knn_accuracies(X, y, k_max)`, which returns the leave-one-out KNN classification accuracy (Euclidean distance, majority vote) for every k in 1..`k_max` as a float array of shape `(k_max,)`. Compute the Euclidean distance matrix once and sort each row once. Also implement `select_k(X, y, k_max)`, which returns the smallest k (as an `int`) with the highest accuracy. The functions must follow these rules: - A point is never its own neighbour, but duplicate points at distance 0 are valid neighbours. - Distance ties break to the lower index. Vote ties break to the smallest label in sorted order. Labels may be strings. - A 1-D `X` is treated as a single feature column. - Raise `ValueError` if `len(y) != len(X)`, if `k_max` is not an integer (a Python or NumPy integer; `bool` does not count), or if `k_max` is outside `1 <= k_max <= n - 1`. ```python X = [[0], [1], [2], [10], [11], [12]] y = [0, 0, 0, 1, 1, 1] loo_knn_accuracies(X, y, 5) # array([1. , 1. , 1. , 0.5, 0. ]) select_k(X, y, 5) # 1 ``` ```hint Shared neighbour lists For a fixed point, its k + 1 nearest neighbours are its k nearest plus one more point. Look for a way to get the vote counts for every k from a single pass over each sorted row. ``` ```hint Leaving the point out The point has to drop out of its own neighbour list while a duplicate at distance 0 stays in. Think about what to change in the distance matrix before sorting so that both rules hold, and which sort guarantees the lower-index tie rule. ``` ### Constraints & Assumptions - `X` has shape `(n, d)`, or `(n,)` for a single feature. Values are finite. - `y` holds `n` labels of any sortable type. - `k_max` satisfies `1 <= k_max <= n - 1`. - The `(n, n)` distance matrix and the intermediate arrays used to build it fit in memory. Scaling past that is a follow-up. ### What a Strong Answer Covers - One distance matrix and one stable sort per row, with self-exclusion that keeps duplicate points as neighbours - Vote counts for every k built from the shared sorted neighbour list, without a separate leave-one-out pass per k - The distance-tie, vote-tie and smallest-k rules, each enforced explicitly in the code - Input validation, label encoding that works for string labels, and the 1-D case - Time and memory cost, and which term dominates as n grows ### Follow-up Questions - Your distance computation uses $O(n^2 d)$ memory. How would you scale to large n? - How would you extend this to distance-weighted voting? - Why can LOOCV accuracy be a noisy criterion for selecting k?

Overview: Implement leave-one-out cross-validation for a k-nearest neighbors classifier that scores every k up to k_max from one distance matrix and one sort per row, then picks the best k. It tests vectorized NumPy, cumulative vote counting, self-exclusion with duplicate points and deterministic tie rules.

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

Implement loo_knn_accuracies(X, y, k_max), which returns the leave-one-out KNN classification accuracy (Euclidean distance, majority vote) for every k in 1..k_max as a float array of shape (k_max,). Compute the Euclidean distance matrix once and sort each row once. Also implement select_k(X, y, k_max), which returns the smallest k (as an int) with the highest accuracy.

The functions must follow these rules:

  • A point is never its own neighbour, but duplicate points at distance 0 are valid neighbours.
  • Distance ties break to the lower index. Vote ties break to the smallest label in sorted order. Labels may be strings.
  • A 1-D X is treated as a single feature column.
  • Raise ValueError if len(y) != len(X) , if k_max is not an integer (a Python or NumPy integer; bool does not count), or if k_max is outside 1 <= k_max <= n - 1 .
X = [[0], [1], [2], [10], [11], [12]]
y = [0, 0, 0, 1, 1, 1]
loo_knn_accuracies(X, y, 5)  # array([1. , 1. , 1. , 0.5, 0. ])
select_k(X, y, 5)            # 1

Constraints & Assumptions

  • X has shape (n, d) , or (n,) for a single feature. Values are finite.
  • y holds n labels of any sortable type.
  • k_max satisfies 1 <= k_max <= n - 1 .
  • The (n, n) distance matrix and the intermediate arrays used to build it fit in memory. Scaling past that is a follow-up.

What a Strong Answer Covers Guidance

  • One distance matrix and one stable sort per row, with self-exclusion that keeps duplicate points as neighbours
  • Vote counts for every k built from the shared sorted neighbour list, without a separate leave-one-out pass per k
  • The distance-tie, vote-tie and smallest-k rules, each enforced explicitly in the code
  • Input validation, label encoding that works for string labels, and the 1-D case
  • Time and memory cost, and which term dominates as n grows

Follow-up Questions Guidance

  • Your distance computation uses O(n2d)O(n^2 d) memory. How would you scale to large n?
  • How would you extend this to distance-weighted voting?
  • Why can LOOCV accuracy be a noisy criterion for selecting k?