t-SNE starts by turning distances into neighbour probabilities, with a separate Gaussian bandwidth for every point chosen to hit a target perplexity. Implement the input side and the objective.
conditional_p(X, perplexity, tol=1e-5, max_iter=200): for each row xi find σi such that
pj∣i=∑k=iexp(−∥xi−xk∥2/2σi2)exp(−∥xi−xj∥2/2σi2),pi∣i=0
has perplexity 2H(Pi)= perplexity, where H(Pi)=−∑jpj∣ilog2pj∣i. Search over the precision βi=1/(2σi2) by bisection: start at β=1 with bounds [0,∞); while ∣H−log2(perplexity)∣> tol and fewer than max_iter steps were taken, raise β if the entropy is too high (doubling it while the upper bound is infinite, otherwise moving to the midpoint) and lower it toward the midpoint with the lower bound if too low. Return the (N, N) matrix of pj∣i (row i holds Pi).
joint_p(P_cond): the symmetrised affinities pij=(pj∣i+pi∣j)/(2N).
tsne_kl(P, Y): the t-SNE objective KL(P∥Q)=∑i=jpijlog(pij/qij) with the Student-t low-dimensional affinities qij=(1+∥yi−yj∥2)−1/∑k=l(1+∥yk−yl∥2)−1, skipping terms with pij=0. Return a Python float.