t-SNE:先拟合邻域概率,再移动地图
t-SNE
构造困惑度亲和概率并真正优化小嵌入,检查梯度、停止规则与图形解释边界。
tsne把有限的地图空间留给邻近关系
六件展品有两个测量特征:(0,0), (1,0), (0,1), (8,8), (9,8), (8,9)。一维显示不可能保留它们之间的全部距离。有限的空间应该优先照顾哪些关系?
t-SNE 将邻近关系转成概率,再移动显示点,让第二个概率分布接近第一个。坐标是优化变量,不是对某个隐藏物理位置的预测。
本章完整例子将二维观测压到一维:拟合局部概率尺度、构造对称目标、计算 Student-t 地图目标,并更新每个显示坐标。经过 100 次接受的更新,KL 目标从约 0.621114 降到 0.000438。这个小优化使用明确提供的初始化,以浮点数计算全部点对,便于逐步检查;不加入原优化器中的加速技巧。
van der Maaten 与 Hinton 在 2008 年论文中提出 t-SNE,发展了随机近邻嵌入。关键变化是把显示空间的相似度改为重尾函数,并使用对称的输入概率。原论文
两个概率分布,一个非凸目标
每条观测有自己的邻域尺度
对每条输入观测,将欧氏距离平方转换成其他记录上的条件分布,自身概率为零。取正的精度参数 βᵢ,它等于 1/(2σᵢ²),其中 σᵢ 是标准差,定义:
这里使用自然对数;若用二为底的熵,再以二取幂,会得到相同困惑度。困惑度是平滑的有效邻居数,不是硬性保留的边数,也不是簇数。精度越大,一行分布就越集中于较近观测。为达到相同困惑度,不同行通常需要不同精度。论文第 2 节
对参数求导,可以得到一个有用的搜索检查。令 D 表示当前行分布下的距离平方,则 dH/dβ = −β Var(D),因此精度增加时,熵不增。β = 0 时,这一行在 n−1 条其他记录上均匀分布;若有 m 条记录并列最近,β 趋于无穷时的极限分布便在这 m 条记录上均匀分布。因此严格位于两端之间的目标需要满足 m < 困惑度 < n−1。程序要求每一行都符合这个条件,不会用更多迭代假装解决不可达目标。
数值计算时,先从所有距离平方中减去该行最小值,再取指数。这个偏移在归一化后相消,使最大指数值为一,避免整个分母消失。熵通过 log(sum(weights)) + beta × mean(shifted_distance) 计算。很小的单项概率仍可能下溢;实现不是任意精度算术。
移动地图之前,先对称化
联合输入分布将两个方向平均,再除以观测数:
w 与 q 的表达式用于非对角元素,程序将对角权重设为零。P、Q 都在有序点对上归一化,因此同一条边的两个方向都计入。优化期间 P 固定。与输入高斯的逐行尺度不同,Q 使用一个全局分母。
Student-t 权重随距离衰减得比高斯权重慢,让相似程度较低的观测可以在地图上相隔更远,同时仍有不可忽视的相互作用。这有助于缓解拥挤,但不能让所有高维构型都忠实地塞进一维或二维。
目标及其梯度为:
pᵢⱼ = 0 的项贡献为零。理解梯度时,可将 C 写为常数减去 log wᵢⱼ 的加权和,再加 log Z,其中 Z 是所有非对角权重之和。前一项求导给出 P 加权的吸引;共同归一化项求导给出 Q 加权的排斥。对称性与点对的两个方向提供系数四。若求导时把 Q 的分母当常数,就会遗漏目标的一部分。论文第 3 节及附录 A
若某点对的目标质量高于地图质量,它的梯度贡献在下降更新中倾向于将两点拉近,但其他点对与全局分母也会影响结果。坐标上的目标非凸。较低目标值说明对这个固定 P 的拟合较好,不是语义准确性或全局最优证书。
真正优化一个小嵌入
用 Python 3.10+ 运行下面的标准库程序。fit_tsne 接受 3–12 条观测,每条含 1–4 个对齐的整数特征,范围为 [-100,100];每条记录对应一个同范围的有限初始标量坐标。还需给出严格位于可行区间内部的困惑度、0–200 次更新额度,以及不超过 100 的正初始步长。布尔值被拒绝。这些限制便于查看完整计算,并不是 t-SNE 的一般要求。conditional 与 objective 是内部辅助函数,输入由 fit_tsne 准备。
每行精度搜索最多进行 80 次区间扩张和 80 次二分,要求熵绝对误差不超过 1e-10。不满足最近距离并列数要求时抛出 ValueError;找不到数值搜索区间或达不到容差时抛出 ArithmeticError。
地图更新采用 Armijo 下降检查;未满足时将候选步长减半,每步最多试 30 次:
每个候选都重新居中到均值为零。平移不改变点对距离,因此这消去的是冗余坐标方向,不改变实数运算下的目标。检查针对普通的固定 P 目标;这里没有早期夸大、动量、逐坐标自适应增益或负采样。
import math
def conditional(distances, perplexity):
"""Internal helper: squared integer distances to other records only."""
nearest = min(distances)
shifts = tuple(d-nearest for d in distances)
if sum(d == nearest for d in distances) >= perplexity:
raise ValueError('perplexity must exceed every nearest-distance tie count')
target = math.log(perplexity)
def at(beta):
w = tuple(math.exp(-beta*d) for d in shifts)
z = math.fsum(w)
p = tuple(v/z for v in w)
entropy = math.log(z)+beta*math.fsum(a*d for a,d in zip(p,shifts))
return p,entropy
lo, hi = 0.0, 1.0
for _ in range(80):
if at(hi)[1] <= target: break
hi *= 2
else: raise ArithmeticError('perplexity bracket not found')
for _ in range(80):
beta = (lo+hi)/2
p,h = at(beta)
if abs(h-target) <= 1e-10: return p,beta,h
if h > target: lo = beta
else: hi = beta
raise ArithmeticError('perplexity tolerance not reached')
def objective(y, p):
"""Internal helper: ordered-pair KL and its analytic 1D gradient."""
n = len(y)
w = tuple(tuple(0.0 if i==j else 1/(1+(y[i]-y[j])**2)
for j in range(n)) for i in range(n))
z = math.fsum(v for row in w for v in row)
q = tuple(tuple(v/z for v in row) for row in w)
loss = math.fsum(p[i][j]*(math.log(p[i][j])-math.log(q[i][j]))
for i in range(n) for j in range(n) if p[i][j]>0)
grad = tuple(4*math.fsum((p[i][j]-q[i][j])*w[i][j]*(y[i]-y[j])
for j in range(n) if i!=j) for i in range(n))
return loss,grad,q
def fit_tsne(points, initial, perplexity=2.5, steps=100, rate=10):
if type(points) not in (list,tuple) or not 3<=len(points)<=12:
raise ValueError('provide 3 to 12 points')
if any(type(row) not in (list,tuple) for row in points):
raise ValueError('each point must be a list or tuple')
d = len(points[0]); n = len(points)
if not 1<=d<=4 or any(len(row)!=d for row in points):
raise ValueError('use 1 to 4 aligned features')
if any(type(x) is not int or abs(x)>100 for row in points for x in row):
raise ValueError('coordinates must be integers in [-100,100]')
if type(initial) not in (list,tuple) or len(initial)!=n:
raise ValueError('one initial scalar coordinate per point required')
if any(type(x) not in (int,float) or not -100<=x<=100 for x in initial):
raise ValueError('initial coordinates must be finite numbers in [-100,100]')
if type(perplexity) not in (int,float) or not 1<perplexity<n-1:
raise ValueError('perplexity must satisfy 1 < perplexity < n-1')
if type(steps) is not int or not 0<=steps<=200:
raise ValueError('steps must be an integer in 0..200')
if type(rate) not in (int,float) or not 0<rate<=100:
raise ValueError('rate must be finite in (0,100]')
xs = tuple(tuple(row) for row in points)
distances = tuple(tuple(sum((a-b)**2 for a,b in zip(x,z)) for z in xs) for x in xs)
rows, betas, entropies = [], [], []
for i in range(n):
ids = tuple(j for j in range(n) if j!=i)
ps,b,h = conditional(tuple(distances[i][j] for j in ids),perplexity)
row = [0.0]*n
for j,v in zip(ids,ps): row[j]=v
rows.append(tuple(row));betas.append(b);entropies.append(h)
p = tuple(tuple((rows[i][j]+rows[j][i])/(2*n) for j in range(n)) for i in range(n))
center = math.fsum(initial)/n
y = tuple(float(x-center) for x in initial)
loss,grad,q = objective(y,p)
trace = [(y,loss,0.0)]
status = 'step-limit'
for _ in range(steps):
if max(map(abs,grad)) <= 1e-10:
status = 'stationary'; break
norm2 = math.fsum(g*g for g in grad)
step = float(rate)
for _ in range(30):
candidate = tuple(x-step*g for x,g in zip(y,grad))
center = math.fsum(candidate)/n
candidate = tuple(x-center for x in candidate)
new_loss,new_grad,new_q = objective(candidate,p)
if new_loss <= loss-1e-4*step*norm2: break
step /= 2
else:
status = 'line-search-failed'; break
y,loss,grad,q = candidate,new_loss,new_grad,new_q
trace.append((y,loss,step))
return {'embedding':y,'p':p,'q':q,'conditionals':tuple(rows),
'betas':tuple(betas),'entropies':tuple(entropies),
'loss':loss,'gradient':grad,'trace':tuple(trace),
'steps_completed':len(trace)-1,'status':status}
if __name__ == '__main__':
xs = ((0,0),(1,0),(0,1),(8,8),(9,8),(8,9))
r = fit_tsne(xs,(-.3,-.2,-.1,.1,.2,.3))
print('KL:',format(r['trace'][0][1],'.6f'),'->',format(r['loss'],'.6f'))
print('embedding:',tuple(round(x,4) for x in r['embedding']))
print('row perplexities:',tuple(round(math.exp(h),6) for h in r['entropies']))
print('completed:',r['steps_completed'],r['status'])
stuck = fit_tsne(xs,(0,)*6)
print('coincident start:',stuck['steps_completed'],stuck['status'],format(stuck['loss'],'.6f'))
实际输出如下:
KL: 0.621114 -> 0.000438
embedding: (-2.6488, -2.5459, -2.5459, 2.5057, 2.6175, 2.6174)
row perplexities: (2.5, 2.5, 2.5, 2.5, 2.5, 2.5)
completed: 100 step-limit
coincident start: 0 stationary 0.692635
trace 保存初始坐标与损失,以及每个被接受的更新和实际步长。step-limit 表示指定工作量完成;stationary 表示检查时最大梯度分量的绝对值不超过 1e-10,不代表找到最好嵌入。30 个候选都不满足条件时,line-search-failed 保留最后接受的模型,不返回被拒绝的试探点。即使更新额度为零,输入概率仍会完整计算并接受验证。
全重合初始化中,每个坐标差都为零,所以显示的梯度公式恰好为零,KL 约为 0.692635,比非重合运行更差。这个实际例子把停止规则与最优证书的区别说清了。主运行最终形成两个紧凑组,但没有恢复各输入三角形内部的全部距离。
设 n 为记录数,d 为特征数,每行最多进行 A 次概率求值,尝试 T 次地图更新,每次最多求值 B 个候选,程序需要 O(n²(d+A+BT)) 算术工作;其中 A ≤ 160、B ≤ 30。稠密概率数组占 O(n²) 空间,保留优化轨迹另占 O(Tn)。浮点计算、有界教学数据和完整轨迹,都是这个实现与可扩展近似求解器的区别。
把图当作拟合出来的表示来读
改变困惑度,会改变 P。不同困惑度运行的损失,对应不同目标分布。仅比较更小的最终 KL,不能选出更有用的地图。同样,只缩放部分输入特征,也可能在优化开始之前改变邻域结构。
地图距离没有校准成输入距离。局部尺度会随观测调整,优化也会牺牲一些关系来保留另一些。图上密集的组,不能单独证明原始采样密度更高。空白、簇面积、分离岛屿间的距离,都不应被读成全部原始关系的定量说明。应检查对应的输入记录和邻域指标,并比较合理的设置与初始化。
嵌入不会发现经过验证的类别。按标签给地图上色有助于调查,却不会让一幅符合标签的图自动成为独立验证。查看最终评测标签后再挑选预处理或参数,也使用了这些信息。若地图启发某个科学或业务结论,应回到原始测量,并用合适的留出证据检验它。
优化器也很重要。原论文和现代库包含额外程序。早期夸大暂时增加吸引项的目标权重,其迭代不是本章同一个归一化 P 目标上的下降步骤。固定版本 scikit-learn API列出了初始化、早期夸大、学习率,以及精确法与 Barnes–Hut 方法。不同库还可能使用不同学习率约定。本程序明确使用自己的约定,并计算全部点对。
这种非参数拟合为给定记录分配坐标,没有训练一个能将任意未来记录映射到显示空间的通用函数。加入数据重新拟合,可能移动已有点。另行定义变换方法或参数化模型,需要自己的定义与评估。
解释地图之前,先检查概率
1. 某行距离平方是 1、1、4,困惑度能达到 1.5 吗?
答案: 在有限正精度构造下不能。两条最近记录并列,即使精度趋于无穷,熵仍为 log 2,困惑度仍为 2。程序拒绝不高于并列数的目标。精度为 log(2)/3 时,行概率为 (0.4,0.4,0.2),困惑度约为 2.872。
2. 对称概率为什么除以 2n?
答案: n 行条件概率各自和为一,因此在有序非对角点对上求两个方向的总和,会得到 2n。除以 2n 才使联合概率总和为一。只除以二,质量总和仍为 n,会改变目标与梯度的归一化。
3. 初始地图点全部为零,返回 stationary 算成功最优吗?
答案: 因为全部坐标差为零,梯度也为零;但实际例子的 KL 约为 0.692635,而非重合初始化达到约 0.000438。因此停止条件不能证明最好拟合,更不用说表示是否有用。
4. 候选步无法降损失,或两次运行改变了困惑度,怎样比较才成立?
答案: 一个候选只有在同一个 P 下满足规定下降条件,才能进入轨迹;试探额度耗尽后保留最后接受的坐标。改变困惑度会改变 P,因此最终 KL 不是在共同目标上的直接竞赛。还应比较邻域行为、预期用途与优化诊断。
从邻域目标到可用的可视化
t-SNE 原论文区分了输入概率构造、Student-t 输出模型和梯度计算。当实现将全点对计算替换为更快近似、或改变优化日程时,这个区分仍然有用。其非凸性讨论也解释了:可重复的初始化是实验的一部分,不是唯一答案的证明。原始文章
可以对照寻找线性方差保留表示的 PCA,以及构造另一种加权邻域图和低维目标的 UMAP。开展 t-SNE 实验时,固定 TSNE 文档让实现选择可查。记录这些选择,并在地图旁保留原始观测。
先判断,再看解释
地图初始坐标全部重合且梯度为零,证明了什么?
学习目标
- 推导条件和对称邻域概率,解释最近距离并列时可达到的困惑度。
- 对全局归一化的 Student-t 目标求导,检查真实坐标更新。
- 区分数值停止、固定目标拟合与地图的语义解释。
先修与延伸
查看知识关联图 →参考文献
- Visualizing Data using t-SNE
Laurens van der Maaten; Geoffrey Hinton · 2008 - TSNE — scikit-learn 1.7 API
scikit-learn developers · 2025
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- 8 项测试通过。一行概率 (0.4,0.4,0.2) 有独立闭式精度 log(2)/3,以 1e-9 容差核验;另将 9 行熵直接从概率重算。前向双数对无序边 KL 表达式求导,核对 4 次损失/梯度及 24 个梯度项;求导贯穿全局归一化,不重复显示的解析梯度式。
- 100 次接受更新均与独立求导梯度及 Armijo 条件核对。全重合初始化提供实际较差驻点;另测平移/反射、零步、概率归一化、输入保全及 12 类非法/不可行配置。失败桩将 30 个候选损失设为无穷,检查 line-search-failed 与最后接受模型保留;这是注入控制流检查,不是自然数据反例。
- 完整原创双语含相同完整 Python、五行实际输出、四显示式、六稳定锚点和四已答练习;严格 MDX/KaTeX 及 React 实际 HTML 通过,四项数学注解一致。完成 Humanizer 文风复读,目录链接使用真实 ID。
- 保持 written,仅 AI 作者检查。全点对浮点模型真正将有界整数特征向量优化成一维嵌入,并非只计算邻域;省略早期夸大、动量和近似求解器。明确概率搜索与优化限制/状态、下溢范围、非凸性、非参数范围及 O(n²(d+A+BT)) 工作/O(n²+Tn) 存储;不声称全局最优、原距离校准、语义标签、人类审校、生产基准或全站验收。
- Root 完整复读双语、完整程序、四公式与四已答习题;重跑八项作者测试及严格 MDX/KaTeX/实际 React HTML,两语四显示式、六标准锚点与四答案一致。无修订要求,最终五 SHA 匹配冻结清单。
- 独立复数解析对数距离展开,在三种拟合目标分布上核对九个目标配置及 45 个偏导。不构造 Q,也不传播双数导数;与正文梯度的差异低于 2e-10,总梯度符合平移不变性。
- 六点全重合起点上,沿组间分离方向的独立二次展开系数为 -2.1934987588;实际小步降低 KL 并匹配该系数,确认 stationary 标记下仍可局部改进。另复核可行困惑度并列、受限数值搜索、仅保留接受步骤的轨迹、非参数范围和改变 P 后的比较。
- 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
- 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。
核对的来源位置:
- Visualizing Data using t-SNE · Actually opened the original 27-page JMLR PDF. Header on printed page 2579 records submitted May, revised September and published November 2008. Read section 2, pp.2581–2582, for Gaussian conditional probabilities, self exclusion, entropy/perplexity and local scales; sections 3.1 and 3.3, pp.2583–2586, for symmetrization and the Student-t output kernel; the section 4 optimization passage on p.2588 for early exaggeration omitted from the basic pseudocode; section 6.2, pp.2598–2599, for nonconvexity and general-purpose dimensionality-reduction limitations; Appendix A, pp.2600–2601, for ordered-pair normalization and the complete gradient. Some extracted derivative notation is awkward, so the draft independently derives the log-normalizer gradient and tests it with forward automatic differentiation. No source examples, code, figures or benchmark claims are reproduced; text reading only, no visual PDF audit.
- TSNE — scikit-learn 1.7 API · Actually read fixed /1.7 API rendered 1.7.2: lines 620–646 signature, nonconvexity, perplexity, early exaggeration and learning-rate conventions; 676–693 initialization, different local minima and exact versus Barnes–Hut methods; 777–791 historical references. The teaching program has its own stricter input/perplexity limits and uses a full-gradient Armijo optimizer without claiming to reproduce this API. No sklearn run, universal library learning-rate conversion or performance comparison.
- Visualizing Data using t-SNE · Root independently opened original 27-page JMLR PDF. Read entropy/perplexity and local variance discussion lines 144–161; Student-t joint probabilities §3.3 lines 331–344; Appendix A pp.2600–2601, lines 862–936, KL, ordered-pair normalization and both point directions in differentiation. Some extracted derivative notation is awkward; verified the authored gradient independently by complex perturbations of a log-distance expansion. No original figures, benchmarks or whole-paper reading claimed.
- TSNE — scikit-learn 1.7 API · Root independently opened fixed /1.7/ API displaying 1.7.2. Read signature line 620; early exaggeration and learning-rate conventions lines 642–646, including the implementation-specific factor-four wording; iteration/stopping parameters lines 649–664. Did not transfer a library-specific rate convention or optimizer guarantee to the separate Armijo teaching program.
相关主题