Who Counts as a Neighbour?

Classic MLHard+30 XP+30

Who Counts as a Neighbour?

t-SNE & UMAP showed t-SNE's core habit: friends stay together. Before t-SNE draws anything, it writes down who counts as whose neighbour in the original data, as a table of numbers. The flat picture is then arranged so that its own neighbours match that table. In this problem you build the table.

Step 1: each point picks its neighbours. For point iii, every other point jjj gets a weight that shrinks as the squared distance between them grows. How fast it shrinks is set by a width σi\sigma_iσi​ that belongs to point iii:

wij=exp⁡ ⁣(−∥xi−xj∥22σi2),pj∣i=wij∑k≠iwikw_{ij} = \exp\!\left(-\frac{\lVert x_i - x_j \rVert^2}{2\sigma_i^2}\right), \qquad p_{j \mid i} = \frac{w_{ij}}{\sum_{k \ne i} w_{ik}}wij​=exp(−2σi2​∥xi​−xj​∥2​),pj∣i​=∑k=i​wik​wij​​

You can read pj∣ip_{j|i}pj∣i​ as the chance that iii picks jjj as its neighbour. A point never picks itself, and each point's chances add up to 1.

Step 2: choose each width by perplexity. One shared width would be unfair. A point in a dense crowd and a point out on its own need very different reach. So each point gets the width that gives it the same effective number of neighbours, called the perplexity:

Perpi=2Hi,Hi=−∑j≠ipj∣ilog⁡2pj∣i\text{Perp}_i = 2^{H_i}, \qquad H_i = -\sum_{j \ne i} p_{j \mid i} \log_2 p_{j \mid i}Perpi​=2Hi​,Hi​=−j=i∑​pj∣i​log2​pj∣i​

Any term with pj∣i=0p_{j|i} = 0pj∣i​=0 counts as 0. If iii spread its chances evenly over 3 neighbours, its perplexity would be exactly 3. A wider σi\sigma_iσi​ spreads the chances out and raises the perplexity. A narrower one concentrates them and lowers it. For every point, find the σi\sigma_iσi​ whose perplexity matches the target to within 10−910^{-9}10−9.

Step 3: make it symmetric. Point iii may like jjj more than jjj likes iii. t-SNE averages the two directions, and scales the result so the whole table adds up to 1:

Pij=pj∣i+pi∣j2n,Pii=0P_{ij} = \frac{p_{j \mid i} + p_{i \mid j}}{2n}, \qquad P_{ii} = 0Pij​=2npj∣i​+pi∣j​​,Pii​=0

Here nnn is the number of points.

Task: write neighbour_affinities(points, perplexity). It returns PPP as a list of nnn lists, with every entry rounded to 4 decimal places.

  • points is a list of points. Each point is a list of numbers, and all points have the same length.
  • The target perplexity can always be reached for every point.

Examples

points = [[0, 0], [1, 0], [3, 0]]
perplexity = 1.5
returns [[0.0, 0.2866, 0.0468], [0.2866, 0.0, 0.1667], [0.0468, 0.1667, 0.0]]
points = [[0, 0], [1, 0], [0, 2], [5, 5]]
perplexity = 2.0
returns [[0.0, 0.1498, 0.1211, 0.0058], [0.1498, 0.0, 0.1032, 0.0277], [0.1211, 0.1032, 0.0, 0.0925], [0.0058, 0.0277, 0.0925, 0.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run