KNN Class Probabilities with Laplace Smoothing
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `knn_predict_proba(X_train, y_train, X_query, k, alpha=0.0)`. For each query row, find its `k` nearest training rows by Euclidean distance and give each one a uniform vote. Return a float array of shape `(n_query, n_classes)` where $p_c = \frac{\text{count}_c + \alpha}{k + \alpha \cdot n_{\text{classes}}}$.
- Column `j` is the `j`-th class of `np.unique(y_train)` (sorted order, not appearance order). Classes with no votes still get a column.
- Distance ties break to the lower training index. A query identical to a training row counts that row as a neighbour.
- Raise `ValueError` if `k` is outside `[1, n_train]` or `alpha < 0`.
For example:
```python
X_train = [[0], [1], [2], [10], [11]]
y_train = [0, 0, 1, 2, 2]
knn_predict_proba(X_train, y_train, [[0.4]], k=3)
# -> [[2/3, 1/3, 0.0]]
knn_predict_proba(X_train, y_train, [[0.4]], k=3, alpha=1.0)
# -> [[3/6, 2/6, 1/6]]
```
```hint Picking the neighbours
Not every sort keeps equal keys in their original order. Choose one that makes the lower-index tie rule hold without extra work.
```
```hint Counting votes
Map each training label to its column index once, before any query is processed. Then check how NumPy handles repeated indices when you add votes into the count matrix.
```
### Constraints & Assumptions
- `X_train` is `(n_train, d)`, `X_query` is `(n_query, d)`, finite floats.
- `y_train` labels may be integers or strings (sortable).
- Each output row sums to 1 and is non-negative.
### What a Strong Answer Covers
- Column order taken from the sorted unique classes, with zero-vote classes kept as columns
- Neighbour selection that sends distance ties to the lower training index and keeps exact matches
- The smoothing formula applied so that every row is a valid distribution, plus both `ValueError` checks
- A vectorized implementation and its time and memory cost as the training set grows
### Follow-up Questions
- How would you add inverse-distance weighting to the votes?
- How does this scale to millions of training rows?
Overview: Implement k-nearest-neighbour class probabilities in NumPy with additive Laplace smoothing, returning one column per sorted class. Tests vectorized distance computation, deterministic tie-breaking, correct vote counting, and keeping every output row a valid probability distribution.