Implement a KNN imputer with a NaN-aware Euclidean distance
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `KNNImputer(n_neighbors=5, weights="uniform")` with `fit`, `transform` and `fit_transform`. Each missing cell is filled with the mean of that feature over its k nearest training rows (donors), using a NaN-aware Euclidean distance.
The imputer must follow these rules.
- The distance between rows $a$ and $b$ uses only the set $C$ of features observed in both rows: $d(a, b) = \sqrt{\frac{p}{|C|} \sum_{j \in C} (a_j - b_j)^2}$, where $p$ is the number of features. It is undefined when $C$ is empty.
- The donors for feature $j$ are the training rows that observe $j$ and have a defined distance to the query row. Take the k closest, breaking ties by the lower training index. When fewer than k such rows exist, use all of them.
- With `weights="distance"`, each donor gets weight ${1/d}$. If any chosen donor has $d = 0$, only the zero-distance donors count, with equal weight.
- When a cell has no donors, fill it with the training column mean (an all-NaN training column gives `0.0`).
- Inputs are never mutated. A DataFrame input returns a DataFrame with the same columns and index; other array-likes return a NumPy array.
- `n_neighbors < 1`, or `weights` outside `{"uniform", "distance"}`, raises `ValueError` in `fit`.
- Only rows seen in `fit` act as donors.
The behavior follows `sklearn.impute.KNNImputer`, which you may not use. Where the two could differ, such as exact distance ties, the rules above decide.
Example:
```python
import numpy as np
nan = np.nan
train = [[0, 0], [1, 10], [4, 40], [10, nan]]
KNNImputer(n_neighbors=2).fit(train).transform([[2, nan], [nan, 25]])
# -> [[2.0, 5.0], [2.5, 25.0]]
```
For the first query, training rows 0 and 2 tie at distance $\sqrt{8}$, and row 0 wins because it has the lower index.
```hint Neighbors per feature
The rows nearest to a query may not observe the feature you are filling. Think about which training rows are eligible for each missing cell before you rank them.
```
```hint Undefined distances and ties
Some training rows share no observed feature with the query. Make sure they can never be chosen, and that equal distances stay in training-row order when you sort.
```
### What a Strong Answer Covers
- The NaN-aware distance with the $p / |C|$ rescaling, and an undefined distance when two rows share no observed feature
- Donor selection per missing feature: eligible rows only, the k closest with the lower-index tie rule, and the case of fewer than k donors
- Uniform and ${1/d}$ weighting, including the zero-distance case
- The fallback to the training column mean, no mutation of the inputs, and DataFrame columns and index preserved
- Parameter validation in `fit`, and the time and memory cost of the approach
### Follow-up Questions
- How would you scale this to a training set of millions of rows?
- Why should features be scaled before using this imputer?
- How would you avoid leakage when using this inside cross-validation?
Overview: Implement a k-nearest-neighbors imputer that fills missing cells from the closest training rows under a NaN-aware Euclidean distance. It tests donor selection per feature, tie and fallback rules, distance weighting, and how to scale the method and keep it free of leakage.