Noise Features vs KNN Accuracy: Cross-Validated k-NN From Scratch in NumPy
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `noise_feature_accuracy(X, y, noise_counts, k=5, seed=0)`. For each count `c` in `noise_counts`, append `c` uniform noise columns to `X` and compute the 5-fold cross-validated accuracy of a standardized k-NN classifier. Return a `float64` array of mean fold accuracies, in the order of `noise_counts`.
The noise and the folds follow these conventions, where `n` is the number of rows in `X`:
```python
# Noise: one draw, shared across all counts (count c uses the first c columns)
noise = np.random.default_rng(seed).uniform(0.0, 1.0, size=(max(noise_counts), n)).T
X_aug = np.hstack([X, noise[:, :c]])
# Folds: sample i belongs to fold i % 5 (no shuffling)
# Score = unweighted mean of the 5 fold accuracies
```
Scoring rules:
- Standardize per fold using the training-fold mean and population std (`ddof=0`). A zero std is replaced by `1`.
- Use Euclidean distance. On equal distances, the lower training index wins.
- Predict by majority vote among the `k` neighbors. Vote ties go to the smallest class label.
```hint Deterministic ties
Check which NumPy sort keeps equal keys in their original order, and what `argmax` returns when several entries share the maximum.
```
```hint Arbitrary labels
Votes are easiest to count when each label is first mapped to its position in a sorted array of the classes.
```
### Constraints & Assumptions
- Labels may be arbitrary integers (for example `{2, 5, 9}`).
- `0` is a valid count.
- The same `seed` must give identical results.
- Only NumPy is available.
### What a Strong Answer Covers
- One shared noise draw whose first `c` columns serve count `c`, and folds assigned by `i % 5` without shuffling.
- Standardization statistics computed on each training fold only, with the population std and the zero-std guard.
- The exact tie rules: lower training index for equal distances and smallest label for tied votes, with arbitrary integer labels.
- A `float64` array of unweighted fold means in the order of `noise_counts`, including the zero-count case.
- Why accuracy falls as noise columns are added, and what the brute-force distance computation costs.
### Follow-up Questions
- Why does accuracy fall as noise columns are added?
- How could you recover accuracy without removing columns by hand?
- Would the drop be smaller or larger if you skipped standardization?
Overview: Write a NumPy function that appends growing numbers of uniform noise columns to a dataset and measures the 5-fold cross-validated accuracy of a standardized k-nearest-neighbors classifier for each count. It tests from-scratch KNN with exact tie rules, leak-free scaling, and why irrelevant features hurt distance-based models.