Memory-Bounded Chunked KNN Prediction

Quick Overview

Implement brute-force k-nearest-neighbour classification that processes queries in fixed-size chunks so only one chunk's distance matrix is in memory, with uniform or distance weighting. It tests vectorized NumPy, deterministic tie rules, exact-match handling and reasoning about peak memory.

Memory-Bounded Chunked KNN Prediction

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Implement brute-force KNN classification that processes `X_query` in contiguous chunks of at most `chunk_size` rows. Only one chunk's distance matrix may be materialised at a time, and the results must be identical for every `chunk_size`. Write these four functions: ```python def chunk_bounds(n_queries, chunk_size): ... def chunked_kneighbors(X_train, X_query, k, chunk_size): ... def chunked_predict_proba(X_train, y_train, X_query, k, chunk_size, weights="uniform"): ... def chunked_knn_predict(X_train, y_train, X_query, k, chunk_size, weights="uniform"): ... ``` Requirements: - `chunk_bounds(n_queries, chunk_size)` returns a list of `(start, stop)` tuples covering `[0, n_queries)` in order. The last chunk may be shorter, and `0` queries give `[]`. - `chunked_kneighbors` returns `(distances, indices)`, each of shape `(m, k)`: Euclidean distances in ascending order, with distance ties going to the lower training index. - `chunked_predict_proba` returns one row per query whose columns follow the sorted `np.unique(y_train)` and whose entries sum to 1. With `weights="uniform"` every neighbour has weight 1. With `weights="distance"` the weights are `1/d`, but if any neighbour of a query has `d == 0`, only those zero-distance neighbours vote, with weight 1 each. - `chunked_knn_predict` returns the highest-probability class for each query, with ties going to the smallest label. - Raise `ValueError` for `chunk_size < 1`, `k` outside `[1, n_train]`, feature arrays that are not 2-D or whose feature counts differ, or `weights` other than `"uniform"` and `"distance"`. Example: ```python chunk_bounds(10, 4) # [(0, 4), (4, 8), (8, 10)] X = [[0.0], [1.0], [2.0], [10.0], [11.0]] y = ["b", "a", "b", "c", "c"] Q = [[0.4], [10.6], [5.0]] chunked_predict_proba(X, y, Q, k=3, chunk_size=2) # [[1/3, 2/3, 0], [0, 1/3, 2/3], [1/3, 2/3, 0]] columns: a, b, c chunked_knn_predict(X, y, Q, k=3, chunk_size=2) # ['b', 'c', 'b'] ``` ```hint What one output row depends on Before writing the loop, list the inputs that a single query's output row depends on. That tells you what the chunk loop may share between chunks and why the chunk size cannot change the answer. ``` ```hint Exact matches Decide how a zero distance is handled before any division happens, and decide it per query: one query in a chunk can have an exact match while the others in the same chunk do not. ``` ```hint Counting votes Several neighbours of one query can share a label, so the same (query, class) cell receives more than one weight. Check that the NumPy operation you use to add them actually accumulates repeated indices. ``` ### Constraints & Assumptions - `X_train` has shape `(n_train, d)`, `X_query` has shape `(m, d)`, and `y_train` has one label per training row. - Labels are values that `np.unique` can sort, such as strings or integers. ### What a Strong Answer Covers - Chunk bounds that cover every query exactly once, including the short last chunk and the zero-query case. - An argument for why the output does not depend on `chunk_size`, and code that keeps only one chunk's distances in memory. - Neighbour selection in ascending distance with the lower-index tie rule. - Distance weighting with the per-query exact-match rule, votes accumulated into sorted class columns, and the smallest-label tie rule for predictions. - Validation of every listed input error, plus time and peak memory as functions of `chunk_size`. ### Follow-up Questions - How would you pick `chunk_size` from a memory budget? - How can you avoid the 3-D broadcast tensor entirely? - How would you speed up the top-`k` selection for large `n_train`?

Overview: Implement brute-force k-nearest-neighbour classification that processes queries in fixed-size chunks so only one chunk's distance matrix is in memory, with uniform or distance weighting. It tests vectorized NumPy, deterministic tie rules, exact-match handling and reasoning about peak memory.

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

Implement brute-force KNN classification that processes X_query in contiguous chunks of at most chunk_size rows. Only one chunk's distance matrix may be materialised at a time, and the results must be identical for every chunk_size.

Write these four functions:

def chunk_bounds(n_queries, chunk_size): ...
def chunked_kneighbors(X_train, X_query, k, chunk_size): ...
def chunked_predict_proba(X_train, y_train, X_query, k, chunk_size, weights="uniform"): ...
def chunked_knn_predict(X_train, y_train, X_query, k, chunk_size, weights="uniform"): ...

Requirements:

  • chunk_bounds(n_queries, chunk_size) returns a list of (start, stop) tuples covering [0, n_queries) in order. The last chunk may be shorter, and 0 queries give [] .
  • chunked_kneighbors returns (distances, indices) , each of shape (m, k) : Euclidean distances in ascending order, with distance ties going to the lower training index.
  • chunked_predict_proba returns one row per query whose columns follow the sorted np.unique(y_train) and whose entries sum to 1. With weights="uniform" every neighbour has weight 1. With weights="distance" the weights are 1/d , but if any neighbour of a query has d == 0 , only those zero-distance neighbours vote, with weight 1 each.
  • chunked_knn_predict returns the highest-probability class for each query, with ties going to the smallest label.
  • Raise ValueError for chunk_size < 1 , k outside [1, n_train] , feature arrays that are not 2-D or whose feature counts differ, or weights other than "uniform" and "distance" .

Example:

chunk_bounds(10, 4)  # [(0, 4), (4, 8), (8, 10)]

X = [[0.0], [1.0], [2.0], [10.0], [11.0]]
y = ["b", "a", "b", "c", "c"]
Q = [[0.4], [10.6], [5.0]]
chunked_predict_proba(X, y, Q, k=3, chunk_size=2)
# [[1/3, 2/3, 0], [0, 1/3, 2/3], [1/3, 2/3, 0]]   columns: a, b, c
chunked_knn_predict(X, y, Q, k=3, chunk_size=2)
# ['b', 'c', 'b']

Constraints & Assumptions

  • X_train has shape (n_train, d) , X_query has shape (m, d) , and y_train has one label per training row.
  • Labels are values that np.unique can sort, such as strings or integers.

What a Strong Answer Covers Guidance

  • Chunk bounds that cover every query exactly once, including the short last chunk and the zero-query case.
  • An argument for why the output does not depend on chunk_size , and code that keeps only one chunk's distances in memory.
  • Neighbour selection in ascending distance with the lower-index tie rule.
  • Distance weighting with the per-query exact-match rule, votes accumulated into sorted class columns, and the smallest-label tie rule for predictions.
  • Validation of every listed input error, plus time and peak memory as functions of chunk_size .

Follow-up Questions Guidance

  • How would you pick chunk_size from a memory budget?
  • How can you avoid the 3-D broadcast tensor entirely?
  • How would you speed up the top- k selection for large n_train ?