KNN Distance-Based Anomaly Detector

Quick Overview

Implement a k-nearest-neighbour anomaly detector in NumPy that scores points by their distance to the k-th nearest or the mean of the k nearest training points and flags those above a percentile threshold. It tests vectorized distance computation, self-exclusion during fitting, and input validation.

KNN Distance-Based Anomaly Detector

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `KNNAnomalyDetector(k=5, method="kth", percentile=95.0)` with `fit(X)`, `score_samples(Q)` and `predict(Q)`. A point's score is its Euclidean distance to its k-th nearest training point (`"kth"`) or the mean distance to its k nearest training points (`"mean"`). Points scoring strictly above a percentile threshold of the training scores are outliers. Requirements: - `fit` sets `X_` and `train_scores_` and returns `self`. When scoring the training points, each point excludes only itself, so exact duplicates still count at distance 0. - `threshold_ = float(np.percentile(train_scores_, percentile))`, using NumPy's default linear interpolation. - `score_samples` uses all training points (no self-exclusion) and returns an array of shape `(n_queries,)`. - `predict` returns an int array: `1` if the score is `>` `threshold_`, else `0`. - `fit` raises `ValueError` if `X` is not 2-D, `method` is not in `{"kth", "mean"}`, or `k` is not an int with `1 <= k <= n_train - 1`. Example: ```python X = [[0.0], [1.0], [2.0], [10.0]] KNNAnomalyDetector(k=2, method="kth").fit(X).score_samples([[1.5], [20.0]]) # [0.5, 18.0] KNNAnomalyDetector(k=2, method="mean").fit(X).score_samples([[1.5], [20.0]]) # [0.5, 14.0] det = KNNAnomalyDetector(k=1, percentile=50.0).fit(X) det.train_scores_ # [1.0, 1.0, 1.0, 8.0], threshold_ = 1.0 det.predict([[1.5], [3.0], [3.5], [20.0]]) # [0, 0, 1, 1] ``` ```hint The training diagonal In `fit` you compare the training set with itself. Look at what the diagonal of that distance matrix holds before you sort each row. ``` ```hint One reduction for both paths `fit` and `score_samples` differ only in the distance matrix they start from. Once each row is sorted, a single helper can turn the first k columns into either score. ``` ### Constraints & Assumptions - The training set has at most a few hundred points, so a dense $O(n \cdot m)$ pairwise distance matrix is fine. - All values are finite floats. - `Q` has the same number of features as `X`. ### What a Strong Answer Covers - Self-exclusion in `fit` that still counts exact duplicates at distance 0, and why the training scores need it. - The `"kth"` and `"mean"` reductions over the k smallest distances, with the logic shared between `fit` and `score_samples`. - A threshold from `np.percentile` with the default interpolation and a strict `>` comparison in `predict`. - Input validation in `fit` (2-D `X`, a valid `method`, an integer `k` in range) that raises `ValueError`. - The time and memory cost of the dense distance computation. ### Follow-up Questions - How would you scale this to millions of training points? - Why does feature scaling matter here, and what would you do about it? - How does this compare to LOF when clusters have different densities?

Overview: Implement a k-nearest-neighbour anomaly detector in NumPy that scores points by their distance to the k-th nearest or the mean of the k nearest training points and flags those above a percentile threshold. It tests vectorized distance computation, self-exclusion during fitting, and input validation.

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

Implement KNNAnomalyDetector(k=5, method="kth", percentile=95.0) with fit(X), score_samples(Q) and predict(Q). A point's score is its Euclidean distance to its k-th nearest training point ("kth") or the mean distance to its k nearest training points ("mean"). Points scoring strictly above a percentile threshold of the training scores are outliers.

Requirements:

  • fit sets X_ and train_scores_ and returns self . When scoring the training points, each point excludes only itself, so exact duplicates still count at distance 0.
  • threshold_ = float(np.percentile(train_scores_, percentile)) , using NumPy's default linear interpolation.
  • score_samples uses all training points (no self-exclusion) and returns an array of shape (n_queries,) .
  • predict returns an int array: 1 if the score is > threshold_ , else 0 .
  • fit raises ValueError if X is not 2-D, method is not in {"kth", "mean"} , or k is not an int with 1 <= k <= n_train - 1 .

Example:

X = [[0.0], [1.0], [2.0], [10.0]]
KNNAnomalyDetector(k=2, method="kth").fit(X).score_samples([[1.5], [20.0]])   # [0.5, 18.0]
KNNAnomalyDetector(k=2, method="mean").fit(X).score_samples([[1.5], [20.0]])  # [0.5, 14.0]

det = KNNAnomalyDetector(k=1, percentile=50.0).fit(X)
det.train_scores_   # [1.0, 1.0, 1.0, 8.0], threshold_ = 1.0
det.predict([[1.5], [3.0], [3.5], [20.0]])  # [0, 0, 1, 1]

Constraints & Assumptions

  • The training set has at most a few hundred points, so a dense O(n⋅m)O(n \cdot m) pairwise distance matrix is fine.
  • All values are finite floats.
  • Q has the same number of features as X .

What a Strong Answer Covers Guidance

  • Self-exclusion in fit that still counts exact duplicates at distance 0, and why the training scores need it.
  • The "kth" and "mean" reductions over the k smallest distances, with the logic shared between fit and score_samples .
  • A threshold from np.percentile with the default interpolation and a strict > comparison in predict .
  • Input validation in fit (2-D X , a valid method , an integer k in range) that raises ValueError .
  • The time and memory cost of the dense distance computation.

Follow-up Questions Guidance

  • How would you scale this to millions of training points?
  • Why does feature scaling matter here, and what would you do about it?
  • How does this compare to LOF when clusters have different densities?