Sparse Pegasos SVM with Scaled Weights
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement `SparsePegasosSVM`, a bias-free linear SVM trained by Pegasos SGD on CSR (or dense) input with labels in {-1, +1}. Store the weights as `w = a * v`, a scalar times a vector, so each step costs O(nnz of the row). Also implement `primal_objective` and `top_features` as module-level functions.
The interface:
```python
class SparsePegasosSVM:
def __init__(self, lam=0.01, epochs=5, seed=0): ...
def fit(self, X, y): ... # sets coef_ and returns self
def decision_function(self, X): ...
def predict(self, X): ...
def primal_objective(X, y, w, lam): ...
def top_features(coef, feature_names, k): ...
```
Requirements:
- `fit`: per epoch, visit rows in `rng.permutation(n)` order, using one `np.random.default_rng(seed)` for the whole fit. The global step `t` starts at 1 and `eta = 1/(lam*t)`. Compute the margin `y_i * x_i·w` first, then apply `w *= (1 - eta*lam)`, then, if the margin is < 1, apply `w += eta*y_i*x_i`. Store `coef_` with shape `(d,)`, matching dense Pegasos to `rtol=1e-7`. Handle a zero shrink factor (at `t=1`) and a tiny `a`.
- Duplicate CSR entries are summed. Do not mutate the input.
- `decision_function` returns a 1-D array `X @ coef_`. `predict` returns `1` where the score is ≥ 0, else `-1`.
- `primal_objective` returns the float `lam/2*||w||² + mean(max(0, 1 - y*Xw))`.
- `top_features` returns `(pos, neg)`: the names of the k largest coefficients in descending order and the names of the k smallest in ascending order, with ties broken by the smaller index and `k` clipped to `[0, d]`.
Example:
```python
X = scipy.sparse.csr_matrix([[1.0, 0.0, 2.0]])
y = [1]
SparsePegasosSVM(lam=0.5, epochs=1).fit(X, y).coef_ # [2.0, 0.0, 4.0]
SparsePegasosSVM(lam=0.5, epochs=2).fit(X, y).coef_ # [1.0, 0.0, 2.0]
top_features([0.5, -1.0, 0.5, 2.0, -1.0, 0.0], list("abcdef"), 2)
# (['d', 'a'], ['b', 'e'])
```
```hint Updating v
If w = a * v and w must gain some vector on the row's columns, work out what v has to gain. Then check which value of a that formula needs: the one from before the shrink or after it.
```
```hint The first step
Evaluate the shrink factor 1 - eta*lam at t = 1 and follow what it does to a and to anything you later divide by a.
```
```hint Sparse pitfalls
NumPy's v[idx] += ... does not accumulate repeated indices, and np.lexsort treats its last key as the primary one. Both affect whether your results are exact.
```
### Constraints & Assumptions
- `X` has shape `(n, d)` and is a SciPy sparse matrix or a dense array. It may hold duplicate stored entries.
- `y` has length `n` with values in {-1, +1}.
- `lam > 0`, `epochs` is an integer, and `seed` fixes the visit order.
- Apart from occasional O(d) maintenance, each training step must cost O(nnz of the row).
- `coef_` must agree with a dense Pegasos run that uses the same visit order to `rtol=1e-7`.
### What a Strong Answer Covers
- How `w = a * v` turns the shrink into one scalar update, and the exact change to `v` that reproduces the dense hinge step.
- The step order (margin, shrink, update), with one step counter and one generator across all epochs.
- Handling the zero shrink factor at `t = 1` and keeping `a` from underflowing.
- Sparse input handling: summing duplicates on a copy, and 1-D outputs from `decision_function` and `predict`.
- Tie-breaking and `k` clipping in `top_features`, plus the time and memory cost of training.
### Follow-up Questions
- Pegasos has an optional projection of w onto the ball of radius ${1/\sqrt{\lambda}}$. How would you add it without giving up O(nnz) steps?
- How would you add a bias term, and should it be regularized?
- How would you change `fit` to use mini-batches, and which weights should the margins in a batch use?
- How would you choose `lam` and the number of epochs, and how would you use `primal_objective` to decide when to stop?
Overview: Implement a bias-free linear SVM trained with Pegasos stochastic gradient descent on sparse CSR input, storing the weights as a scalar times a vector so each step costs time proportional to the row's nonzeros. Tests exact update ordering, numerical edge cases, sparse matrix handling and tie-aware feature ranking.