NMF Topic Modeling with Top Keywords
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `nmf_multiplicative(X, n_components, n_iter=200, seed=0, W0=None, H0=None, eps=1e-10)`, which factorises a non-negative document-term matrix `X` (dense or `scipy.sparse`, shape `(n, m)`) as `X ≈ W @ H` using Lee-Seung multiplicative updates and returns `(W, H, losses)`. Also implement `top_keywords(H, vocabulary, n_top)`, which returns a list with one entry per row of `H`: the `n_top` highest-weighted vocabulary terms, in descending order of weight.
Algorithm, with `k = n_components`:
```python
# Initialisation (only if W0 or H0 is None; a provided W0/H0 overrides its draw)
rng = np.random.default_rng(seed)
scale = np.sqrt(X.mean() / k)
W = scale * rng.random((n, k)) # drawn first
H = scale * rng.random((k, m)) # drawn second
# Each iteration: update H first, then W using the new H
H = H * (W.T @ X) / (W.T @ W @ H + eps)
W = W * (X @ H.T) / (W @ H @ H.T + eps)
losses[it] = ||X - W @ H||_F^2 # squared Frobenius, after both updates
```
Requirements:
- Any negative entry in `X` raises `ValueError`.
- `losses` is a NumPy array of length `n_iter`. With `n_iter = 0` the function returns the initial factors and an empty array.
- Sparse and dense inputs give identical results. `W` has shape `(n, k)` and `H` has shape `(k, m)`.
- In `top_keywords`, ties are broken by the lowest column index.
Example:
```python
H = [[0.2, 0.9, 0.9, 0.1, 0.9],
[1.0, 1.0, 0.0, 0.5, 0.5]]
top_keywords(H, ["a", "b", "c", "d", "e"], 3)
# -> [["b", "c", "e"], ["a", "b", "d"]] ties broken by lowest index
```
```hint One path for both input types
The easiest way to make sparse and dense inputs agree exactly is to send them through the same arithmetic.
```
```hint Ties in the ranking
Not every sort keeps equal weights in their original column order. Check which sort guarantees it, and which direction of sorting keeps the lowest index first.
```
### Constraints & Assumptions
- `X` is a dense array or a `scipy.sparse` matrix of shape `(n, m)`: `n` documents by `m` vocabulary terms.
- A provided `W0` has shape `(n, k)` and a provided `H0` has shape `(k, m)`.
- `1 <= n_top <= len(vocabulary)`, and `len(vocabulary)` equals the number of columns of `H`.
### What a Strong Answer Covers
- Initialization that follows the stated draw order and the override rule for `W0` and `H0`.
- The update order inside an iteration and the point at which the loss is recorded.
- Handling of sparse input, negative entries and `n_iter = 0`.
- The tie rule in `top_keywords`.
- The cost per iteration, and what changes for a large sparse corpus.
### Follow-up Questions
- Why does the multiplicative update never increase the loss, and when can it stall?
- How would you make this scale to a large sparse corpus?
- Why might TF-IDF weighting or KL-divergence loss give better topics than raw counts with Frobenius loss?
Overview: Implement non-negative matrix factorization with Lee-Seung multiplicative updates on a document-term matrix, track the squared Frobenius loss, and extract the top keywords for each topic with a fixed tie rule. It tests numerical linear algebra, reproducible initialization and careful handling of sparse input.