Vectorized Random Forest Proximity Matrix
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `proximity_matrix(leaves)` where `leaves` has shape `(n_samples, n_trees)` and holds integer leaf ids (for example the output of a fitted forest's `apply`). Return an `N x N` `float64` array whose entry `(i, j)` is the fraction of trees in which samples `i` and `j` land in the same leaf. Avoid Python loops over sample pairs.
Example:
```text
Input: leaves = [[0, 1],
[0, 2],
[1, 1]]
Output: [[1.0, 0.5, 0.5],
[0.5, 1.0, 0.0],
[0.5, 0.0, 1.0]]
```
Samples 0 and 1 share a leaf in tree 0 only, samples 0 and 2 share a leaf in tree 1 only, and samples 1 and 2 never share a leaf.
Leaf ids are only comparable within a tree (column):
```text
Input: leaves = [[5, 7],
[7, 5]]
Output: [[1.0, 0.0],
[0.0, 1.0]]
```
The two samples swap ids between the trees, but within each tree their ids differ, so they never share a leaf.
```hint Pairs as a product
Think of each (tree, leaf) pair as a binary feature of a sample. What does the dot product of two samples' feature vectors count?
```
```hint Ids across trees
Leaf id 5 in tree 0 and leaf id 5 in tree 1 are different leaves. Make sure your encoding cannot mix them up.
```
### Constraints & Assumptions
- Output is symmetric, values in `[0, 1]`, diagonal all `1.0`, entries are multiples of `1 / n_trees`.
- Result must be invariant to relabeling leaf ids within any tree.
- Non-2-D input or `n_trees == 0` raises `ValueError`. `n_samples == 0` returns a `(0, 0)` array.
- Leaf ids are arbitrary non-negative integers (not necessarily contiguous).
### What a Strong Answer Covers
- An encoding that keeps leaf ids from different trees apart and is invariant to relabeling within a tree.
- A vectorized way to count shared leaves for all pairs at once, such as a sparse indicator product or a per-tree broadcast comparison.
- Correct normalization, dtype and output properties (symmetric, unit diagonal, multiples of `1 / n_trees`).
- The specified input validation and empty-input behavior.
- Time and memory cost as functions of N and the number of trees.
### Follow-up Questions
- How does memory scale, and what would you do if $N = 10^6$?
- How would you compute out-of-bag proximities?
- What are proximities used for in practice?
Overview: Compute a random forest proximity matrix from per-tree leaf ids, where each entry is the fraction of trees that place two samples in the same leaf, without looping over sample pairs. Tests sparse one-hot encoding, matrix products and memory reasoning at scale.