UMAP:构建局部图,再优化布局
UMAP
计算局部隶属度、模糊并集及完整低维交叉熵优化,明确数值与解释边界。
umap先构建加权邻域,再安排位置
六份档案的测量坐标是 (0,0), (1,0), (3,1), (9,4), (11,4), (14,6)。我们希望用一维排列保留重要的局部联系。直线投影是一种选择;UMAP 走另一条路:构建按局部尺度调整的近邻连接,合成加权图,再移动低维点来表达这张图。
这是两个计算阶段。只算出图,还没有得到嵌入。本章完整教学程序两步都做:先构造小图,再优化所有显示坐标。经过 100 次接受的更新,完整边交叉熵从约 6.889781 降到 3.209096。
图和目标来自 UMAP 框架,但这里明确采用一个小型变体:精确近邻搜索、一维输出、固定曲线指数、外部提供初始化,以及全梯度下降。它没有复现 umap-learn 的全部默认设置。原始工作用几何与拓扑来说明构造动机;本例实际使用的表示,是由点对连接组成的加权图。作者论文,2020 年修订版
局部隶属度不是归一化概率表
拟合局部距离尺度
为每条观测选出 k 条最近的其他记录。本章约定不包括自身,k 就是保留的数量,邻居集合记为 Nᵢ。输入坐标互异时,ρᵢ 是最近的正距离。选取正尺度 σᵢ,使其满足:
最近邻的隶属度为一,超出局部偏移后按指数衰减。σ 增大时,隶属度向保留的其他邻居扩展。目标固定的是局部隶属度总量,不是香农熵。这与 t-SNE 的困惑度不同,行和通常也不是一。尺度构造可见论文的实际算法。
对于本程序严格位于可行区间内部的搜索,距离为 ρ 的并列邻居数 m 必须小于 log₂ k。σ 趋于零时,总量趋于 m;σ 趋于无穷时,总量趋于 k。如果 m 已经太大,有限正尺度无法满足方程,程序会拒绝该情形,不暗中指定一个尺度。选取 k 个邻居时,边界距离并列按原始行号决定;这不同于保留全部并列者。教学版本排除重复输入坐标。
合并两个方向
不同局部尺度可能使 uᵢⱼ 与 uⱼᵢ 不同。模糊并集把它们合并:
结果对称且介于零与一之间。补集形式类似于两个独立边提议至少有一个存在的概率,用来定义这里选定的组合规则;它没有证明实际独立性,也没有把测量数据变成经过校准的概率模型。任意一个方向的隶属度为一,合成边便为一;两个 0.4 合成 0.64,而不是 0.8。之后不做全局归一化。固定版本官方解释
低维图采用另一条隶属度曲线
低维坐标使用一条共享的递减曲线。一般曲线族有正参数 a、b;本实现固定 b = 1,接受外部指定的 a:
求和将每个无序点对计一次,包括 μ = 0 的非边。这是多个二元交叉熵之和,不是在全部点对上定义一个类别分布。论文的模糊集合散度另外包含只依赖 μ 的项,去掉该常数后,最小化位置不变。若把两个方向都计入,目标和梯度会加倍。与 t-SNE 不同,低维 q 没有共享归一化分母。论文定义 10 及优化部分
吸引项阻止强边两端分得太远,另一项阻止弱边或非边靠得太近。去掉其中任意一项,就不能再说优化的是这个完整目标。对一个标量点对,记 δ = yᵢ−yⱼ,并固定 b = 1。当 δ 非零时:
对两个对数直接求导,就得到这个作用项;将它加到坐标 i 的梯度,再从 j 的梯度中减去。因此总梯度和为零,与平移不变性一致。对于孤立的自由点对,若 0 < μ < 1,最佳间距平方为 (1−μ)/(aμ),此时 q 等于 μ。但整张图一般无法同时实现每个点对各自偏好的距离。
δ = 0 时,q = 1。若 μ < 1,交叉熵为无穷;若 μ = 1,该点对的损失和梯度都为零。程序分别处理这两种情况。它使用上面的对数表达式,避免从一减去一个极接近一的 q 值。但这仍是浮点算术:试探中的下溢或溢出可能使该候选不可用。
从图到坐标的完整计算
用 Python 3.10+ 运行下面的标准库程序。输入是 4–12 条互异记录,各含 1–4 个对齐的整数特征,范围 [-100,100];外部提供的初始标量坐标也必须是该范围内的有限数。其他限制是 3 ≤ k < n、0.01 ≤ a ≤ 100、0–200 次更新额度,以及 (0,10] 内的初始步长;拒绝布尔值。这些是明确的教学限制。尤其要注意,这里的 k 计数其他记录,不能假定它等于某个 API 内部包含自身的邻居数约定。
memberships 与 objective 是服务于验证后计算的内部辅助函数。尺度搜索最多执行 80 次区间扩张和 80 次二分,局部总量容差为 1e-10。图并集结果只为容纳浮点舍入误差而截到 [0,1],这个截取不是额外的学习参数。
坐标优化采用完整解析梯度,将拒绝的步长减半,并要求满足系数为 1e-4 的 Armijo 下降。每次更新最多试 40 个候选。每个候选重新居中,不改变点对距离。没有使用负采样,也没有自动拟合 min_dist 曲线。
import math
def memberships(distances):
"""Internal helper: k selected positive neighbor distances, no self entry."""
rho = min(distances); target = math.log2(len(distances))
shifted = tuple(d-rho for d in distances)
if sum(d==0 for d in shifted) >= target:
raise ValueError('nearest-distance ties make this local mass target infeasible')
def at(beta):
row = tuple(math.exp(-beta*d) for d in shifted)
return row,math.fsum(row)
lo,hi = 0.0,1.0
for _ in range(80):
if at(hi)[1] <= target: break
hi *= 2
else: raise ArithmeticError('local scale bracket not found')
for _ in range(80):
beta = (lo+hi)/2;row,total=at(beta)
if abs(total-target)<=1e-10:return row,rho,1/beta
if total>target:lo=beta
else:hi=beta
raise ArithmeticError('local mass tolerance not reached')
def objective(y, graph, a):
"""Full unordered-pair binary cross entropy with b=1; None if undefined."""
n=len(y);terms=[];g=[0.0]*n;q=[[0.0]*n for _ in y]
if not all(math.isfinite(v) for v in y):return None
for i in range(n):
for j in range(i):
mu=graph[i][j];delta=y[i]-y[j]
if delta==0:
if mu<1:return None
q[i][j]=q[j][i]=1.0
continue
square=delta*delta;scaled=a*square
if square==0 or not math.isfinite(scaled):return None
value=math.log1p(scaled)
if mu<1:value-=(1-mu)*(math.log(a)+2*math.log(abs(delta)))
force=2*(a*delta/(1+scaled)-(1-mu)/delta)
if not math.isfinite(value) or not math.isfinite(force):return None
terms.append(value);g[i]+=force;g[j]-=force
q[i][j]=q[j][i]=1/(1+scaled)
try:loss=math.fsum(terms)
except OverflowError:return None
if not math.isfinite(loss) or not all(map(math.isfinite,g)):return None
return loss,tuple(g),tuple(tuple(row) for row in q)
def fit_umap(points, initial, k=3, a=1, steps=100, rate=1):
if type(points) not in (list,tuple) or not 4<=len(points)<=12:
raise ValueError('provide 4 to 12 points')
if any(type(row) not in (list,tuple) for row in points):raise ValueError('point rows required')
n=len(points);d=len(points[0])
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('integer input features in [-100,100] required')
xs=tuple(tuple(row) for row in points)
if len(set(xs))!=n:raise ValueError('this example excludes duplicate input coordinates')
if type(k) is not int or not 3<=k<n:raise ValueError('k counts other records: 3 <= k < n')
if type(initial) not in (list,tuple) or len(initial)!=n:raise ValueError('one initial scalar per record')
if any(type(x) not in (int,float) or not -100<=x<=100 for x in initial):
raise ValueError('finite initial values in [-100,100] required')
if type(a) not in (int,float) or not .01<=a<=100:raise ValueError('a must lie in [0.01,100]')
if type(rate) not in (int,float) or not 0<rate<=10:raise ValueError('rate must lie in (0,10]')
if type(steps) is not int or not 0<=steps<=200:raise ValueError('integer steps in 0..200 required')
sq=tuple(tuple(sum((u-v)**2 for u,v in zip(x,z)) for z in xs) for x in xs)
neighbors=tuple(tuple(sorted((j for j in range(n) if j!=i),key=lambda j:(sq[i][j],j))[:k]) for i in range(n))
directed=[[0.0]*n for _ in xs];rhos=[];sigmas=[]
for i,ids in enumerate(neighbors):
weights,rho,sigma=memberships(tuple(math.sqrt(sq[i][j]) for j in ids))
for j,w in zip(ids,weights):directed[i][j]=w
rhos.append(rho);sigmas.append(sigma)
graph=tuple(tuple(min(1.0,max(0.0,directed[i][j]+directed[j][i]-directed[i][j]*directed[j][i]))
for j in range(n)) for i in range(n))
center=math.fsum(initial)/n;y=tuple(float(v-center) for v in initial)
result=objective(y,graph,a)
if result is None:raise ValueError('initial embedding has undefined or unrepresentable objective')
loss,grad,q=result;trace=[(y,loss,0.0)];status='step-limit'
for _ in range(steps):
if max(map(abs,grad))<=1e-10:status='stationary';break
try:norm2=math.fsum(g*g for g in grad)
except OverflowError:norm2=float('inf')
if not math.isfinite(norm2):status='numerical-gradient';break
eta=float(rate)
for _ in range(40):
proposal=tuple(x-eta*g for x,g in zip(y,grad))
center=math.fsum(proposal)/n;proposal=tuple(x-center for x in proposal)
trial=objective(proposal,graph,a)
if trial is not None and trial[0]<=loss-1e-4*eta*norm2:break
eta/=2
else:status='line-search-failed';break
y=proposal;loss,grad,q=trial;trace.append((y,loss,eta))
return {'embedding':y,'neighbors':neighbors,'rhos':tuple(rhos),'sigmas':tuple(sigmas),
'directed':tuple(tuple(row) for row in directed),'graph':graph,'q':q,
'loss':loss,'gradient':grad,'trace':tuple(trace),
'steps_completed':len(trace)-1,'status':status}
if __name__=='__main__':
xs=((0,0),(1,0),(3,1),(9,4),(11,4),(14,6))
r=fit_umap(xs,(-3,-2,-1,1,2,3))
print('cross entropy:',format(r['trace'][0][1],'.6f'),'->',format(r['loss'],'.6f'))
print('embedding:',tuple(round(x,4) for x in r['embedding']))
print('directed row masses:',tuple(round(sum(row),6) for row in r['directed']))
print('symmetric edge mass:',format(sum(map(sum,r['graph']))/2,'.6f'))
print('completed:',r['steps_completed'],r['status'])
实际输出:
cross entropy: 6.889781 -> 3.209096
embedding: (-2.2451, -2.0526, -1.8194, 1.7832, 2.0488, 2.2852)
directed row masses: (1.584963, 1.584963, 1.584963, 1.584963, 1.584963, 1.584963)
symmetric edge mass: 5.955514
completed: 100 step-limit
所有有向行和约等于 log₂ 3,即 1.584963;对称边总量约为 5.955514,显然不为一。输出坐标已经移动,这是优化后的布局,不只是邻域报告。
trace 保留初始模型,以及被接受的坐标、损失和步长。step-limit 记录工作量;stationary 表示最大梯度分量绝对值不超过 1e-10;没有合格候选时,line-search-failed 保留最后接受的状态。如果梯度范数平方无法表示,numerical-gradient 会在更新前停止。初始目标未定义或无法表示时抛出 ValueError,非法试探会被拒绝,不作为结果返回。程序不声称能够检测每一次浮点精度损失。
报告损失不必趋于零。即使一个点对可以自由移动,分数型 μ 在 q = μ 时仍有正的二元熵;整张图还有几何相容限制。目标非凸,下降与小梯度都不能认证全局最优表示。
设 n 为记录数,d 为特征数,k 为保留邻居数,每行至多进行 A 次局部尺度求值,尝试 T 次更新,每次至多求值 B 个候选,工作量为 O(n²d + n² log(n+1) + Ank + BTn²),其中 A ≤ 160、B ≤ 40。稠密输入和图数组占 O(n²) 空间,坐标轨迹另占 O(Tn)。这是明确计算全部点对的教学成本,不代表生产 UMAP 的近似近邻搜索或采样优化成本。
邻域、显示曲线与解释,需要分别选择
k 会改变图。小邻域可能看不到区域间的连接,大邻域可能连起区域,却丢失更细的结构。没有一个普遍适用的 k 能揭示正确类别。输入特征缩放和距离函数,在布局开始前就决定了谁是邻居。应同时比较图的变化与图片。固定参数指南讨论了邻域尺度的取舍。
min_dist 不是这个目标中的硬约束。普通 UMAP 中,min_dist 参与确定拟合的低维曲线参数 a、b。曲线表达偏好的局部排列,并没有要求每一对输出坐标至少相隔 min_dist。本实现直接接受 a,固定 b = 1,因此没有 min_dist 参数,也不复现通常的曲线拟合。改变 a 保留输入图,却改变距离表达隶属度的方式。
完整目标与采样优化器处在不同实现层面。官方 UMAP 使用近邻搜索和优化近似,包括负采样。本章计算全部点对,使吸引与排斥贡献可以逐项检查,不是在用看似相同的参数名预测某次库运行的数值结果。官方构造与算法
一张图不是拓扑证书。局部流形假设为图构造提供动机,但有限数据、测量噪声、距离选择与优化都会影响结果。一个看似独立的岛屿,不能证明生物类别、因果机制或稳定人群边界。自适应局部尺度也意味着显示密度不是原始采样密度的直接估计。应回到原始测量,并结合适当的外部证据检验结论。
在这个目标里,图的非连通分量之间没有吸引边,排斥可能继续把它们推远,最终相对位置不是经过校准的全局距离。一维例子还会牺牲一些较高维显示也许能保留的关系。非参数拟合为这些记录提供坐标,本程序没有新记录变换。库中的 transform 功能属于另一套算法,需要单独定义参照和评估方式。
检查图和损失到底表示什么
1. 两个方向的隶属度都为 0.4,合并后是多少?全图必须和为一吗?
答案: 并集为 0.4 + 0.4 − 0.4 × 0.4 = 0.64,不做全局归一化。实际例子中,无序边总量约为 5.955514。将这些隶属度当成一个类别概率分布,会定义出不同目标。
2. 一个点对有 μ = 1/4、a = b = 1,什么间距最小化它的损失?
答案: 令导数为零,间距平方为 (1−1/4)/(1/4) = 3,所以绝对间距为 √3,q = 1/4。最小交叉熵是参数为 1/4 的正伯努利熵,不是零。这只是在计算一个自由点对,不保证全图各边能同时达到各自最优。
3. 某行选择三个邻居,其中两个并列最近,尺度搜索能达到 log₂ 3 吗?
答案: 不能。无论正尺度取什么值,这两个隶属度始终为一,所以行和至少为二,而目标 log₂ 3 约为 1.585。程序拒绝该行。增加搜索次数不会改变可行性条件;改变邻域或数值约定,就是改变模型。
4. 为什么 μ 小于一时拒绝重合点对,而 μ 等于一时允许?
答案: 重合使 q = 1。μ 小于一时,非边项具有正权重,并含有发散的 −log(1−q);μ = 1 时,该项权重为零,剩余损失为 −log q = 0。程序在后一种情况采用合法极限值,前一种情况返回不可用候选,不暗中给距离加偏移。
分别理解理论与实现
McInnes、Healy 和 Melville 的作者论文连接了局部度量近似、模糊并集和低维匹配目标。工作最早以 2018 年 arXiv 预印本出现,本章引用的修订版日期为 2020 年 9 月。研究图构造与优化时,应将它们和“某幅地图保留了多少全局结构”这类更广泛的主张分开。
固定官方解释提供了理解局部连通性、模糊边并集与布局的易读路线。可以对照输出点对分布全局归一化的 t-SNE,以及为不同目标使用图特征向量的谱聚类。看起来相似的图,可能在优化不同数学量。
先判断,再看解释
图中两个方向的隶属度均为 0.4,采用哪个对称边目标?
学习目标
- 计算局部尺度隶属度和对称模糊并集,不将它们当作全局归一化表。
- 推导并真正优化含吸引与排斥的完整低维边交叉熵。
- 区分邻域尺度、软布局参数、数值限制与语义解释。
先修与延伸
查看知识关联图 →参考文献
- UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction — arXiv v3
Leland McInnes; John Healy; James Melville · 2018 - How UMAP Works — official release-0.5.7 documentation
UMAP developers - Basic UMAP Parameters — official release-0.5.7 documentation
UMAP developers
版本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 项测试通过。对 exp(-1/sigma) 的二次方程独立核对距离 1、2、3 的局部尺度;3 个小图以点对比较排名、重建局部权重/总量及显式伯努利 OR 状态核验,不只重复并集表达式。
- 两张独立的三点/四点合成图,通过枚举完整伯努利图状态,以 70 位 Decimal 求负对数联合似然的期望;7 个坐标导数用该整图期望、步长 1e-16 的中心差分核对,区别于实现的点对解析作用项。单边解析最优核对间距平方三时 q=1/4,并检查单位/分数边权的重合情况及次正规距离拒绝。
- 核验 100 次真实坐标更新及实现的 Armijo 检查、平移/反射、改变 a 时输入图不变、输入复制和 12 类非法配置。测试桩强制拒绝全部 40 个候选并制造梯度范数平方溢出,审查失败状态保留;这些是注入控制流检查,不是自然数值反例。
- 完整原创双语具有相同可运行 Python、五行实际输出、四显示式、六锚点和四已答练习;严格 MDX/KaTeX 及 React 实际 HTML 通过,四数学注解对应。完成固定 Humanizer 文风复读,关联路由均采用真实目录 ID。
- 保持 written,仅 AI 作者检查。有界标量全梯度变体完成图到布局的完整计算,固定 b=1、外部提供 a/初始坐标,不拟合 min_dist、不用负采样,严格定义 k 计数其他记录并明确重合/数值定义域。说明非凸性、省略的常数熵、非归一化隶属度、全点对成本、非连通分量位置及解释边界;不声称完整生产 UMAP 等价、拓扑保证、基准、人类审校或全站验收。
- Root 完整复读双语及程序,核对四公式与四答案,重跑八项作者测试及严格 MDX/KaTeX/React HTML;两语四显示式、六标准锚点一致。无需修订,冻结哈希匹配。
- 独立尺度协变检查令 a=s²、初始坐标 Y/s、步长 eta/s²,s 取 0.5、2、3。三条完整 12 次更新轨迹保持图、损失、隶属度及状态,13 个接受状态的坐标与梯度符合反向/正向缩放,容差 3e-9;用于检查图到布局的联动,不重复作者高精度导数参照。
- 复核最近邻并列可行性、k 计数其他记录、非归一化并集、省略常数熵、b=1 范围、重合极限、仅保留接受步骤及非凸解释;不声称生产 UMAP 等价或拓扑保证。
- 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
- 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。
核对的来源位置:
- UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction — arXiv v3 · Actually opened arXiv v3 abstract/history and the 63-page author PDF. History identifies first submission 9 February 2018 and v3 submission 18 September 2020; PDF cover says 21 September 2020. Read Definition 10 on physical page 12 for fuzzy-set divergence; practical graph construction on pages 14–15 for positive-neighbor rho and mass log2(k); Algorithms 1–3 on pages 18–19 and optimization on pages 20–21 for fuzzy union, scale search, binary cross entropy and the smooth a,b curve fitted using min-dist. Appendix C, pages 56–57, explicitly contrasts global normalization and provides the same union/curve family. Read the negative-sampling discussion on pages 20–22, without adopting its general performance claims. No proof audit of the full topology framework or visual PDF inspection; no source examples, code or figures copied.
- How UMAP Works — official release-0.5.7 documentation · Actually read the downloaded raw official release-0.5.7 doc/how_umap_works.rst at /tmp/aiwiki-next-umap/source-release-0.5.7-how_umap_works.rst, particularly lines 335–365 local connectivity; 400–420 probabilistic union; 444–521 layout, Bernoulli interpretation, full edge divergence and forces; 525–558 approximation, curve family, negative sampling and spectral initialization. Parent downloaded this pinned tag and resolved its commit with GitHub API; I read the resulting local file. Earlier web attempts with a nonexistent tag lacking the release- prefix and a ReadTheDocs version URL failed. No library code execution or automatic curve fit claimed.
- Basic UMAP Parameters — official release-0.5.7 documentation · Actually read downloaded fixed doc/parameters.rst lines 118–192 on n_neighbors and scale tradeoff, plus lines 194–207 on min_dist. Did not carry over the guide’s literal minimum-allowed-distance wording: the original smooth curve objective supplies a preference, not a hard pairwise inequality. Read the nearby basic_usage model representation to identify its separate spread option but omitted that unnecessary claim from this draft. Parameter plots and source example datasets were not reproduced.
- UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction — arXiv v3 · Root independently read the arXiv v3 submission history (2018-02-09 initial, 2020-09-18 v3), author PDF cover (2020-09-21), Definition 10 lines 413–439, positive-neighbor scale equation lines 519–529, Algorithms 2–3 lines 662–679, fixed entropy term and negative sampling lines 688–729, and fitted soft curve/Algorithm 5 lines 732–764. No audit of the full topology proof or benchmark claims.
- How UMAP Works — official release-0.5.7 documentation · Root independently read the downloaded official release-0.5.7 how_umap_works.rst: local connectivity lines 335–365; union 400–420; full edge divergence/forces and approximate optimizer 444–558. Checked full-pair scalar teaching objective is explicitly distinguished from negative-sampled library optimization.
- Basic UMAP Parameters — official release-0.5.7 documentation · Root independently read fixed parameters.rst lines 118–125 and 176–207. Local/global neighborhood tradeoff retained; literal minimum-allowed-distance wording not adopted because the original fitted smooth curve is not a hard pairwise constraint.
相关主题