Implement t-SNE Affinities, KL Divergence and Its Gradient in NumPy
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement five building blocks of t-SNE in NumPy: `conditional_probabilities`, `joint_probabilities`, `student_t_affinities`, `kl_divergence` and `tsne_gradient`. All matrices are dense `(n, n)` NumPy arrays with a zero diagonal, built from squared Euclidean distances.
The quantities to compute:
```python
# p_{j|i} = exp(-beta_i * d_ij) / sum_{k!=i} exp(-beta_i * d_ik)
# beta_i chosen so 2**H(P_i) == perplexity (H in bits)
# P_ij = (p_{j|i} + p_{i|j}) / (2n)
# w_ij = 1 / (1 + ||y_i - y_j||^2), Q_ij = w_ij / sum_{k!=l} w_kl
# KL(P||Q) = sum over P_ij > 0 of P_ij * log(P_ij / Q_ij) (natural log, float)
# grad_i = 4 * sum_j (exaggeration * P_ij - Q_ij) * w_ij * (y_i - y_j)
```
Here `X` is the `(n, D)` input data, `d_ij` is the squared distance between rows i and j of `X`, and `Y` is the `(n, d)` embedding. Implement these signatures:
```python
def conditional_probabilities(X, perplexity=30.0, tol=1e-5, max_iter=200): ...
def joint_probabilities(X, perplexity=30.0, tol=1e-5, max_iter=200): ...
def student_t_affinities(Y): ...
def kl_divergence(P, Q): ...
def tsne_gradient(P, Y, exaggeration=1.0): ...
```
For example, with two points one unit apart:
```python
P = [[0, .5], [.5, 0]]
Y = [[0.], [1.]]
tsne_gradient(P, Y, 1.0) # [[0.], [0.]]
tsne_gradient(P, Y, 12.0) # [[-11.], [11.]]
```
```hint Calibrating beta
Row entropy falls as beta grows, so a one-dimensional search per row works. You need an upper bracket before you can bisect, and the entropy can be computed from the row sum and the probability-weighted distance without taking the log of tiny probabilities.
```
```hint Vectorizing the gradient
Put the pairwise coefficients `(exaggeration * P_ij - Q_ij) * w_ij` into one matrix. The sum over j of that coefficient times `(y_i - y_j)` splits into a row-sum term and a matrix product.
```
```hint Testing the gradient
Compare against central differences of `kl_divergence(P, student_t_affinities(Y))` on a small random input, and think about which exaggeration value that comparison is valid for.
```
### Constraints & Assumptions
- 2 ≤ n ≤ 100, all inputs are finite and the points are distinct.
- Each row's measured perplexity must match the target within relative `1e-4`. The tolerance `tol` applies to the row entropy in bits.
- Conditional rows sum to 1. Joint `P` is symmetric and sums to 1. Every returned `(n, n)` matrix has a zero diagonal.
- `kl_divergence` uses the natural log and returns a float.
- `tsne_gradient` returns shape `(n, d)`. With `exaggeration=1.0` it must match finite differences of `kl_divergence(P, student_t_affinities(Y))`.
### Clarifying Questions to Ask
- What should `conditional_probabilities` return when the perplexity is larger than $n - 1$, so that no beta can reach it?
- Should the beta search stop only on the entropy tolerance, or also after `max_iter` steps, and which beta should it use in that case?
### What a Strong Answer Covers
- A per-row search on beta that relies on entropy being monotone in beta, finds an upper bracket when there is none, and measures entropy in bits.
- Numerical stability in the row exponentials and in the squared-distance computation.
- Correct normalization of each matrix: conditional rows without the self term, the joint P over 2n, and Q over all off-diagonal pairs.
- A vectorized gradient that matches the formula, checked against finite differences of the KL divergence, with a clear statement of when that check applies.
- Time and memory cost of the dense version in terms of n, the dimensions and the number of search steps.
### Follow-up Questions
- Why does the binary search subtract the row minimum distance before exponentiating?
- How would you scale this beyond a few thousand points?
- Why does the gradient sum to zero across points, and what role does early exaggeration play?
Overview: Implement the core pieces of t-SNE in NumPy: Gaussian affinities calibrated to a target perplexity by binary search, symmetrized joint probabilities, Student-t affinities in the embedding, the KL divergence and its gradient with early exaggeration. It tests numerical care, vectorized NumPy and checking an analytic gradient against finite differences.