t-SNE Joint Probabilities with Perplexity Search
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `joint_probabilities(X, perplexity, tol=1e-5, max_iter=200)` for data `X` of shape `(n, d)`. For each point `i`, binary-search a precision `beta_i` so the conditional distribution over the other points has the target perplexity. Return the tuple `(P, conditional, betas)`.
The function must follow these rules:
- `conditional[i, j] ∝ exp(-beta_i * D[i, j])` for `j != i`, using squared Euclidean `D` (no 1/2 factor). Rows sum to 1 and the diagonal is 0.
- Entropy is in bits (`log2`). Stop when `|H_i - log2(perplexity)| < tol` or after `max_iter` steps.
- Start each search at `beta = 1.0`. The returned `betas` (shape `(n,)`, all `> 0`) must reproduce `conditional` exactly.
- `P = (conditional + conditional.T) / (2 * n)`: symmetric, sums to 1, zero diagonal.
- The computation stays numerically stable for large distances (no underflow to all-zero rows).
For example:
```python
X = 3.0 * np.eye(4) # all pairwise distances equal
P, cond, betas = joint_probabilities(X, 3.0)
# cond off-diagonal: 1/3 everywhere
# P off-diagonal: 1/12 everywhere
```
```hint Searching for beta
Entropy moves in one direction as beta grows. Think about how to search when you have only a lower bound on beta so far.
```
```hint Large distances
When every distance in a row is large, `exp(-beta * D[i, j])` can be 0 for all j. Look for a change to the row that leaves the normalized probabilities the same.
```
### Constraints & Assumptions
- 2 ≤ n ≤ 500
- 1 < `perplexity` ≤ n - 1
- All entries of `X` are finite.
### What a Strong Answer Covers
- A per-row search justified by the monotone relation between beta and entropy, including the phase where no upper bound on beta is known yet.
- Entropy in bits, with the self term excluded from each row and `0 * log 0` treated as 0.
- A numerically stable row computation that cannot produce an all-zero row.
- Stored betas that are exactly the ones used for the stored rows, including rows that stop at `max_iter`.
- Correct symmetrization, plus the time and memory cost in terms of n, d and the number of search steps.
### Follow-up Questions
- Why search over entropy rather than perplexity directly, and why is binary search valid?
- How would you scale this to ${10^6}$ points?
- Why symmetrize into `P` instead of using the conditionals directly?
Overview: Implement the input side of t-SNE: for each point, binary-search a Gaussian precision so its conditional distribution reaches a target perplexity, then symmetrize the rows into joint probabilities. It tests bisection on a monotone function, entropy in bits and numerically stable probability rows.