NCA Metric Learning Before KNN: Compare Against a Scaled Euclidean Baseline in scikit-learn
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement three functions. `build_euclidean_knn_pipeline` and `build_nca_knn_pipeline` return unfitted scikit-learn `Pipeline`s, and `compare_nca_vs_euclidean` fits both on training data and reports their test accuracies.
```python
def build_euclidean_knn_pipeline(n_neighbors=3): ...
def build_nca_knn_pipeline(n_neighbors=3, n_components=None, random_state=0, max_iter=50): ...
def compare_nca_vs_euclidean(X_train, y_train, X_test, y_test, n_neighbors=3,
n_components=None, random_state=0, max_iter=50): ...
```
The pipelines and the comparison follow these rules:
- Euclidean pipeline steps, in order: `"scaler"` (`StandardScaler`), `"knn"` (`KNeighborsClassifier`, uniform weights, Euclidean metric).
- NCA pipeline steps, in order: `"scaler"`, `"nca"` (`NeighborhoodComponentsAnalysis`), `"knn"`.
- Pass `n_neighbors` to KNN and `n_components`, `random_state`, `max_iter` to NCA unchanged, so predictions match scikit-learn exactly.
- `compare_nca_vs_euclidean` returns a dict with three float values: `euclidean_accuracy`, `nca_accuracy`, and `improvement` (`nca_accuracy - euclidean_accuracy`).
- Accuracy is the fraction of test predictions equal to `y_test`. Inputs may be lists or arrays.
Example, on data with one informative feature and ten Gaussian noise features (80 training rows, 80 test rows):
```python
res = compare_nca_vs_euclidean(Xtr, ytr, Xte, yte, n_neighbors=3)
# res["nca_accuracy"] >= 0.9 and res["nca_accuracy"] > res["euclidean_accuracy"]
```
```hint Where each step learns
Think about which rows each pipeline step sees when you call `fit` on the whole pipeline, and which rows it sees at `predict` time.
```
```hint Counting matches
Compare the shape of `y_test` with the shape of the predictions before you count matches. A label column and a flat array do not compare the way you might expect.
```
### Constraints & Assumptions
- `X_train` and `X_test` are 2-D numeric data (lists of lists or NumPy arrays) with the same number of columns. `y_train` and `y_test` are 1-D class labels.
- Defaults: `n_neighbors=3`, `n_components=None` (NCA keeps every input dimension), `random_state=0`, `max_iter=50`.
- The example dataset has 80 training rows, 80 test rows and 11 features.
### What a Strong Answer Covers
- Both pipelines with the exact step names and order, and every parameter passed through unchanged.
- The scaler and the NCA transform learned from the training split only, by fitting them inside the pipeline.
- Each builder returning new, unfitted objects, so the two models share no fitted state.
- Accuracy computed elementwise on converted, flattened labels and returned as plain floats, with `improvement` equal to the NCA accuracy minus the Euclidean accuracy.
### Follow-up Questions
- How would you tune `n_neighbors` and `n_components` without touching the test set?
- How does NCA's training cost scale with the number of training rows, and what would you do with a million rows?
- When would NCA fail to beat the Euclidean baseline, or do worse than it?
- What does setting `n_components=2` give you besides a smaller model?
Overview: Build two scikit-learn pipelines, a scaled Euclidean KNN baseline and a version that learns a Neighborhood Components Analysis transform before the neighbor search, then compare their test accuracy. It tests pipeline construction, leak-free fitting, and why a learned metric helps KNN when most features are noise.