Condensed Nearest Neighbor Prototype Selection
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `one_nn_predict(X_train, y_train, X_query)`, which returns the label of each query's nearest training row. Then implement `condensed_nearest_neighbor(X, y, order=None)` (Hart's CNN), which returns the indices of a subset whose 1-NN rule classifies every training point correctly.
Example:
```python
X = [[0.0], [4.0], [5.0]]
y = [0, 0, 1]
condensed_nearest_neighbor(X, y)
# [0, 2, 1] pass 1 adds 2, pass 2 adds 1
X = [[-1.0], [1.0], [0.0]]
y = [0, 1, 1]
condensed_nearest_neighbor(X, y, order=[1, 0, 2])
# [1, 0, 2] x = 0 ties between points 0 and 1, and index 0 wins
```
```hint Tie-breaking inside the store
The store grows in insertion order, but distance ties must go to the lowest training index. Check that your nearest-member search does not simply return the first match in the store.
```
```hint Tracing the first example
Point 1 is classified correctly in pass 1. Ask what changes for it once point 2 has joined the store.
```
### Constraints & Assumptions
- Distance is squared Euclidean. Distance ties go to the lowest training index, not the earliest store insertion.
- `order` is a permutation of `range(n)` and defaults to `0..n-1`. The store is seeded with `order[0]`.
- Visit samples in `order`. Append a misclassified sample to the store immediately. Repeat full passes until a pass adds nothing.
- Return an integer `np.ndarray` of indices in insertion order. Empty input returns an empty array.
- 1-D `X` is treated as a single feature column. Labels are arbitrary integers.
### What a Strong Answer Covers
- A vectorized 1-NN predictor using squared Euclidean distance and the lowest-index tie rule.
- The CNN loop as specified: the seed, the visiting order, skipping stored samples, immediate absorption, and repeated passes until a clean one.
- A nearest-store-member search that breaks distance ties by training index even though the store is kept in insertion order.
- Why the loop terminates, why a clean pass makes the store consistent, and when no consistent subset exists.
- The cost of a pass and the worst-case number of passes.
### Follow-up Questions
- Why does the result depend on the visiting order, and how would you reduce that sensitivity?
- CNN tends to keep noisy points near the class boundary. How would you address that?
- What is the cost of each pass, and how would you speed it up?
- What happens when two identical points carry different labels?
Overview: Implement a 1-nearest-neighbor predictor and Hart's condensed nearest neighbor algorithm, which keeps a subset of training points that still classifies the whole training set correctly. It tests greedy prototype selection, repeated passes until nothing changes, and exact tie-breaking by training index.