Cosine-Distance KNN Classifier for Embeddings
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `normalize_rows(X)`, `cosine_distances(A, B)` and a `CosineKNNClassifier` with `fit`, `kneighbors`, `predict_proba` and `predict`. Normalise rows to unit L2 norm and compute all distances with a single matrix multiplication (no Python loops over pairs).
Requirements:
- `normalize_rows` leaves all-zero rows as zero.
- Distance is `1 - cos`, clipped to `[0, 2]` (a zero vector has distance `1` to everything).
- `fit` raises `ValueError` if `len(X) != len(y)` and sets `classes_` to the sorted unique labels.
- `kneighbors(X_query, k=None)` returns `(distances, indices)`, each `(m, k)`, ascending by distance. Equal distances break to the lower training index.
- `k < 1` or `k > n_train` raises `ValueError`.
- `predict_proba` returns uniform vote fractions, shape `(m, n_classes)`, columns ordered as `classes_`. `predict` returns the argmax label (vote ties go to the smallest label).
Example:
```python
cosine_distances([[1,0],[0,2],[1,1],[-2,0]], [[3,0]])
# [[0.0], [1.0], [0.2929], [2.0]]
m = CosineKNNClassifier(k=2).fit([[1,0],[0,1]], [7, 3])
m.predict_proba([[1,1]]) # [[0.5, 0.5]] (classes_ = [3, 7])
m.predict([[1,1]]) # [3]
```
```hint One product for every pair
Once both sides have unit rows, think about which single NumPy expression gives the full query-by-train similarity matrix, and what a zero row must look like after normalising.
```
```hint Deterministic ordering
Check whether the default `np.argsort` keeps equal values in index order, and how `np.argmax` picks among equal maxima.
```
### Constraints & Assumptions
- Inputs are finite float arrays. Labels may be ints or strings.
- Results must match `sklearn` brute-force cosine KNN to about 1e-6.
- Distances must come from matrix operations, with no Python loop over query-train pairs.
### What a Strong Answer Covers
- Normalisation that handles zero-norm rows without dividing by zero, and distances computed with one matrix product and clipped to `[0, 2]`.
- Input validation in `fit` and `kneighbors` that raises `ValueError` for a length mismatch and for `k` outside `[1, n_train]`.
- Deterministic output: a stable sort for distance ties, `predict_proba` columns in `classes_` order, and vote ties resolved to the smallest label.
- Vectorised vote counting whose rows sum to 1.
- The time and memory cost of the `(m, n)` distance matrix.
### Follow-up Questions
- How would you scale this to millions of embeddings?
- How would you add distance-weighted voting?
- Why clip distances to `[0, 2]`?
Overview: Implement a cosine-distance k-nearest-neighbour classifier for embedding vectors in NumPy, with row normalisation, fully vectorised distances and deterministic tie-breaking. It tests vectorised linear algebra, numerical edge cases such as zero vectors and clipping, and careful handling of class order and vote ties.