流形学习:画地图之前,先量清楚哪条路能走
Manifold learning
搭建小型 Isomap,观察邻域捷径,并区分谱计算准确与几何假设正确。
manifold-learning隔着弯道的空隙,和沿路走过去,是两种距离
站在一条 U 形步道的端点,对面端点隔着空隙只有两个单位远,但沿步道走过去需要六个单位。两个距离都合理,它们回答的是“允许怎样移动”这个不同的问题。
流形学习尝试为观测寻找低维坐标,保留某种选定的结构。一张照片可能有几千个像素值,主要变化却只来自视角等少数因素。记录坐标的数量叫环境维数,局部自由度的数量叫内在维数。内在维数很低,是需要调查的假设,不是数据量大就自动具备的性质。
本例在二维平面上放七个点,排成弯曲路径。我们建立邻域图,测量图上的路线,再从这些距离恢复坐标。只改一个半径,长路就变成捷径。数据足够小,你可以亲自找出是哪几条边改变了结果。
Tenenbaum、de Silva 和 Langford 的 Isomap 论文将邻域构建、最短路径与经典多维尺度分析(MDS)结合起来,表示由局部连接估计出的内在几何。原论文表 1
局部有坐标,不保证全局能摊成一张平面图
d 维流形局部类似 d 维欧氏空间中的区域:每个内部点附近,都可以用坐标图将一个邻域对应到该空间的开子集。光滑坐标图支持导数与切向方向。一条曲线即使弯入很多测量坐标,也只有一个局部方向;边界点则需要相应的边界坐标图。
对嵌入欧氏空间的光滑流形,内在测地距离在沿流形的分段光滑路径上取长度下确界:
环境空间中的直线段可能离开 M。只有样本点时,我们并不知道 M 上全部路径。Isomap 用邻域图中的路线代替它们。本程序对距离不超过闭半径 epsilon 的不同观测连无向边,边权取普通欧氏距离:
Floyd–Warshall 计算全部最短路。如果两点间没有路径,图就不连通,本实现停止,不凭空添桥。固定版本的 scikit-learn 指南同样将 Isomap 分成近邻搜索、最短路和特征分解三个阶段。固定 1.7.2 Isomap 指南
从距离转成内积
将图距离存入 D,对各元素平方,再从两侧中心化:
圆圈上标表示逐元素平方,不是矩阵乘积 DD。为什么中心化有用?假设 D 本来来自欧氏坐标,坐标按行放在 X 中。每个距离平方等于两个模长平方之和,再减两倍内积。乘 H 后,独立的模长项被消去,留下
所以欧氏距离平方矩阵给出一个半正定的中心化 Gram 矩阵。反过来,从 D 得到的 B 若半正定,就能对特征值开方恢复坐标。将特征对按特征值从大到小排列,保留正特征值时,第 i 条记录的 d 维坐标为
原论文注 17 给出中心化算子,表 1 给出坐标构造。对称 B 保留最大的正特征值,得到 Frobenius 范数下一个最优的秩至多为 d 的半正定近似。这次谱优化以已经选定的图为前提,不会优化邻域半径。原论文式 1、注 17 与表 1
图距离矩阵未必能被精确表示为欧氏距离。明显的负特征值提示这种不相容,不能硬对它们开平方当作坐标。程序报告负特征值数量,只拟合数值上可分辨的正方向;正方向不足则明确报错。完整保留一个重复特征值对应的空间时,换基只会旋转坐标,保留表示的几何。如果截断位置穿过这个并列块,最优的保留子空间也不唯一:同样最优的嵌入可以具有不同点对距离。在固定保留子空间内换符号或旋转,仍然保留几何。
把邻域图和谱都交出来
下面的完整 Python 3 程序只用标准库。教学输入范围为 3–12 个互异的二维点,坐标是绝对值不超过 1,000 的整数或浮点数,半径在 (0,10,000],输出维数是介于一与 n−1 的整数。布尔值、非有限数和形状错误的输入被拒绝。边界判断使用实际浮点距离作闭比较,不会悄悄扩大半径。
特征求解器执行 Jacobi 旋转,并检查特征对残差和正交性。数值检查不通过或迭代达到上限时停止。返回值包含图、Gram 矩阵、谱及两种误差,便于检查。这是小规模计算,不是可扩展的生产 Isomap,也没有样本外变换接口。
import math
def symmetric_eigen(matrix):
# Internal Jacobi solver for the small, finite symmetric Gram matrix.
n=len(matrix);a=[row[:] for row in matrix]
v=[[float(i==j) for j in range(n)] for i in range(n)]
scale=max(1.0,math.sqrt(sum(x*x for row in a for x in row)))
for _ in range(100*n*n):
p,q=max(((i,j) for i in range(n) for j in range(i+1,n)),key=lambda ij:abs(a[ij[0]][ij[1]]))
if abs(a[p][q])<=1e-13*scale:break
tau=(a[q][q]-a[p][p])/(2*a[p][q])
t=math.copysign(1.0,tau)/(abs(tau)+math.hypot(1.0,tau))
c=1/math.sqrt(1+t*t);s=t*c;off=a[p][q]
a[p][p]-=t*off;a[q][q]+=t*off;a[p][q]=a[q][p]=0.0
for k in range(n):
if k not in (p,q):
ap,aq=a[k][p],a[k][q]
a[k][p]=a[p][k]=c*ap-s*aq
a[k][q]=a[q][k]=s*ap+c*aq
vp,vq=v[k][p],v[k][q];v[k][p]=c*vp-s*vq;v[k][q]=s*vp+c*vq
else:raise ArithmeticError('Jacobi iteration limit reached')
order=sorted(range(n),key=lambda j:a[j][j],reverse=True)
eigenvalues=tuple(a[j][j] for j in order)
vectors=[]
for j in order:
col=[v[i][j] for i in range(n)];pivot=max(range(n),key=lambda i:abs(col[i]))
vectors.append(tuple(x if col[pivot]>=0 else -x for x in col))
residual=math.sqrt(sum((sum(matrix[i][j]*u[j] for j in range(n))-lam*u[i])**2
for lam,u in zip(eigenvalues,vectors) for i in range(n)))/scale
orthogonal=max(abs(sum(u[i]*w[i] for i in range(n))-float(j==k))
for j,u in enumerate(vectors) for k,w in enumerate(vectors))
if not residual<=1e-10 or not orthogonal<=1e-10:
raise ArithmeticError('eigenpair certificate failed')
return eigenvalues,tuple(vectors),residual,orthogonal
def isomap(points,radius,dimensions=1):
if type(points) not in (list,tuple) or not 3<=len(points)<=12:
raise ValueError('between three and twelve points required')
if any(type(p) not in (list,tuple) or len(p)!=2 for p in points):
raise ValueError('two coordinates per point required')
if any(type(x) not in (int,float) or abs(x)>1000 or not math.isfinite(x) for p in points for x in p):
raise ValueError('finite real coordinates with absolute value <= 1000 required')
x=tuple(tuple(float(v) for v in p) for p in points);n=len(x)
if len(set(x))!=n:raise ValueError('duplicate points are excluded in this teaching model')
if type(radius) not in (int,float) or not 0<radius<=10000 or not math.isfinite(radius):
raise ValueError('positive finite radius at most 10000 required')
if type(dimensions) is not int or not 1<=dimensions<n:raise ValueError('invalid output dimension')
ambient=tuple(tuple(math.dist(p,q) for q in x) for p in x)
edges=tuple((i,j,ambient[i][j]) for i in range(n) for j in range(i+1,n) if ambient[i][j]<=radius)
graph=[[0.0 if i==j else math.inf for j in range(n)] for i in range(n)]
for i,j,w in edges:graph[i][j]=graph[j][i]=w
for k in range(n):
for i in range(n):
for j in range(n):graph[i][j]=min(graph[i][j],graph[i][k]+graph[k][j])
if any(not math.isfinite(d) for row in graph for d in row):
raise ValueError('radius graph is disconnected; no automatic bridge is inserted')
squared=[[d*d for d in row] for row in graph]
means=[sum(row)/n for row in squared];grand=sum(means)/n
gram=[[-0.5*(squared[i][j]-means[i]-means[j]+grand) for j in range(n)] for i in range(n)]
values,vectors,residual,orthogonal=symmetric_eigen(gram)
tolerance=1e-10*max(1.0,max(abs(v) for v in values))
if values[dimensions-1]<=tolerance:raise ValueError('requested dimension exceeds resolved positive spectrum')
embedding=tuple(tuple(math.sqrt(values[k])*vectors[k][i] for k in range(dimensions)) for i in range(n))
error=sum((gram[i][j]-sum(a*b for a,b in zip(embedding[i],embedding[j])))**2 for i in range(n) for j in range(n))
norm=sum(a*a for row in gram for a in row)
distance_rmse=math.sqrt(sum((graph[i][j]-math.dist(embedding[i],embedding[j]))**2 for i in range(n) for j in range(i+1,n))/(n*(n-1)/2))
return dict(edges=edges,graph_distances=tuple(map(tuple,graph)),gram=tuple(map(tuple,gram)),
eigenvalues=values,embedding=embedding,relative_strain=math.sqrt(error/max(norm,1e-300)),
distance_rmse=distance_rmse,negative_eigenvalues=sum(v < -tolerance for v in values),
eigen_residual=residual,orthogonality_error=orthogonal)
if __name__=='__main__':
points=((0,2),(0,1),(0,0),(1,0),(2,0),(2,1),(2,2))
print('ambient endpoint distance:',math.dist(points[0],points[-1]))
for radius,dimension in [(1,1),(2,1),(3,2)]:
report=isomap(points,radius,dimension)
print('radius / dimensions:',radius,dimension,'edges:',len(report['edges']))
print('endpoint graph / embedding:',round(report['graph_distances'][0][-1],6),
round(math.dist(report['embedding'][0],report['embedding'][-1]),6))
print('strain / distance RMSE / negative spectrum:',round(report['relative_strain'],6),
round(report['distance_rmse'],6),report['negative_eigenvalues'])
try:isomap(points,0.9)
except ValueError as error:print('smaller radius:',error)
距离构建需要 O(n²) 工作,Floyd–Warshall 需要 O(n³)。本例 Jacobi 例程允许 O(n²) 次旋转,每次扫描 O(n²) 个非对角元素,因此这个求解器的最坏工作界是 O(n⁴)。存储为 O(n²)。不要把其他库更高效的求解器复杂度直接搬到这份实现上。
程序报告相对 strain:B 与嵌入 Gram 矩阵之间的 Frobenius 误差,除以 B 的 Frobenius 范数。距离 RMSE 则直接比较嵌入距离与图距离:
这是两个目标。谱构造优化的是 Gram 矩阵近似,不直接最小化这里的距离 RMSE,也不直接最小化原论文另行讨论的残差方差诊断。
看半径怎样造出捷径
ambient endpoint distance: 2.0
radius / dimensions: 1 1 edges: 6
endpoint graph / embedding: 6.0 6.0
strain / distance RMSE / negative spectrum: 0.0 0.0 0
radius / dimensions: 2 1 edges: 13
endpoint graph / embedding: 2.0 2.642636
strain / distance RMSE / negative spectrum: 0.628116 0.85936 3
radius / dimensions: 3 2 edges: 21
endpoint graph / embedding: 2.0 2.0
strain / distance RMSE / negative spectrum: 0.0 0.0 0
smaller radius: radius graph is disconnected; no automatic bridge is inserted
半径为一时,恰好有六条边,构成经过七条记录的一条路径。理想一维坐标是中心化的路径位置 −3、−2、−1、0、1、2、3,也可以整体镜像。其 Gram 矩阵只有一个非零特征值,为 28。端点在图和一维表示中都相距六。输出中的零误差经过六位小数舍入,实际计算使用浮点数。
半径为二时有十三条边,两个端点直接跨空隙相连,图距离变成二。新距离的 Gram 矩阵有三个明显负特征值,一维欧氏表示无法全部保留这些距离:嵌入端点距离约 2.643,距离 RMSE 约 0.859。
半径为三时图完全连接,最短路距离就是原始欧氏距离,两个输出维度可以在刚体变换意义下恢复平面几何。这时已经不是把路径展开。半径为 0.9 时,图不连通,程序报告问题。
另一个四点方环可以把这个区别算清楚。半径为一时,环图的中心化特征值是 2、2、0、−1。保留二维会收进整个正谱块;只保留一维则切开它。按 (0,0),(1,0),(1,1),(0,1) 输入方环,程序让原记录 0 与 2 相距二;将行循环重排为 (1,2,3,0) 后再映回原记录,这个距离可以变成零。但两个一维解的相对 strain 都是 sqrt(5)/3。变的是保留子空间,不只是同一条线的镜像。
七点步道是有限图教学例,不是证明带尖角折线满足光滑流形收敛定理的证据。它要展示的是局部连接选择本身。
嵌入求得很准,也可能表示了错误的距离
邻域要足够大,才能接通采样路径;又要足够小,才不会在相邻折叠之间抄近路。采样稀疏、噪声或密度不均会让两个要求冲突。原论文的收敛讨论依赖采样密度、曲率、分支间距和几何假设,不保证恢复任意点云。原论文收敛讨论与注 18
局部欧氏结构也不意味着全局欧氏距离几何。圆有局部一维坐标图,但将它打开成一条直线,需要切口,并改变部分关系。嵌入对图距离的误差很小,只说明图被表示得好,不说明图符合未知的生成过程。
缩放与距离选择发生在建图之前。改变某项测量单位,就可能改变边、最短路和全部最终坐标。应记录预处理、半径、连通性、保留的谱以及对邻近设置的敏感性。检查看似折叠处的真实邻居,不要只依赖一张整齐的二维图。
本例没有噪声模型、自动维数选择或未来点的预测规则。增加记录后重新拟合,可能改变全部嵌入。比较两次运行,需要按几何对齐,或比较点对距离等不变量;原始坐标轴翻转或旋转,未必是实质变化。
相信坐标之前,先检查几何
1. 为什么一种描述里端点相距二,另一种相距六?
答案:二是环境空间直线距离,六是半径为一的邻域图路线长度。嵌入针对后者,因为这张图定义了允许经过的路径。
2. 特征对残差极小,能证明邻域半径选对了吗?
答案:不能。它检查的是选定 Gram 矩阵的数值特征分解。被精确求解的矩阵,也可能来自含错误捷径的图。
3. 半径为二时的三个负特征值说明什么?
答案:超过声明的数值容差后,中心化图距离矩阵不是半正定的。这些距离无法被任意维数的欧氏坐标全部精确实现。丢弃负方向,得到的是带有可测误差的近似。
4. 第二次运行把全部一维坐标取负,几何丢失了吗?
答案:没有。镜像保留所有点对距离和内积。判断变化前应比较这些不变量,或先对齐坐标。不过,图真的改变时,几何本身也可能改变。
保留什么关系,决定了方法的区别
Isomap 的贡献,是由局部连接与图路线长度构造全局几何表示。邻域到图的步骤把它接到最短路径搜索;最后的中心化谱把它接到 PCA 和核 PCA。这些联系比把所有非线性图都叫作“展开流形”更能解释计算。
其他方法保留不同关系。固定版本指南通过局部重构权重和全局特征问题介绍局部线性嵌入;Isomap 则将估计出的全局路线距离送入 MDS。选择保留什么,属于模型定义,不只是实现快慢的区别。流形指南的 Isomap 与 LLE 小节
下一项有用实验,是移除弯道附近少数样本,比较图与嵌入怎样变化。报告连通性、捷径和失真,再问保留的坐标是否帮助下游任务。聚类评估解释了为什么嵌入图里好看的分组,本身还不是所需类别的证据。
先判断,再看解释
加入邻域捷径后,特征对残差极小,这说明什么?
学习目标
- 区分环境距离、图路线与假设流形上的测地距离。
- 推导双中心化,并从正特征对重建嵌入。
- 诊断捷径、不连通图和非欧氏图距离。
先修与延伸
查看知识关联图 →参考文献
- A Global Geometric Framework for Nonlinear Dimensionality Reduction
Joshua B. Tenenbaum; Vin de Silva; John C. Langford · 2000 - scikit-learn 1.7 — Manifold learning
scikit-learn 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.
- 6 项测试通过。六个路径模型核对精确图距离、中心化坐标外积及非零特征值闭式 n(n²−1)/12;三个完全图核对直接中心化坐标 Gram、独立二维散布多项式根及全部重建距离。
- 独立优先队列最短路核对四份图报告。四环循环矩阵 Fourier 计算给特征值 2、2、0、-1,相对 strain 1/3 和距离 RMSE sqrt(2/3)(sqrt(2)-1),不用另一份 Jacobi 实现来检查负谱与重复正特征空间。
- 核对六边变十三边的捷径、端点图距离六变二、三个负方向、不连通半径、未分辨输出秩、重复点、超大整数、非有限数、布尔值和输入保全。完整主程序十一行输出实际一致,显示零为浮点舍入。
- 完整双语对应六显示式、六标准锚点、四已答习题及相同完整 Python。共享错误阻断下严格 MDX/KaTeX 与实际 React HTML 通过。来源访问细节留元数据,按既定 Humanizer 规则保留具体几何与条件;written 等独立审查。
- 根据交叉审校,明确分段光滑路径,并区分完整保留重复特征空间的换基与截断穿过并列块。四环重排行回归给映回原记录的点对距离 2 对 0,两次最优相对 strain 均为 sqrt(5)/3。程序未改;双语和原 Fourier 测试已覆盖此例。
- 最终 6 项作者测试通过。独立枚举 75 条简单合法路径、计算 4 个精确 Leibniz 特征多项式,核对星形、2×3 网格和弯曲路径上的 8 次拟合。验证边与全部距离、锚点平移中心化 Gram、完整谱、负谱数量、保留特征方程、8 个最优 PSD 截断误差证书及距离 RMSE,不重写 Floyd、堆最短路、Jacobi、二维散布谱或 Fourier 环参照。
- 完整复读双语、代码、6 公式、4 已答练习及最终元数据;核对流形/图区别、光滑与采样条件、双中心化与正谱条件、半径边界、数值保护、有上限的特征求解器成本及原始诊断范围。独立严格 MDX/KaTeX 和真实 React HTML/MathML 通过 6 对应显示式、6 锚点和 4 答案。
- 完整正文、公式、代码和习题迁入;测试只读取正式MDX,删除临时目录回退及草稿跳过,状态断言更新为checked。没有修改算法或独立参照,最终记录绑定两语SHA。
- 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。
核对的来源位置:
- A Global Geometric Framework for Nonlinear Dimensionality Reduction · Actually read five-page original reprint text on the mirror. Title/authors begin at lines 57–60; earlier references and received date belong to the preceding article and are not attributed to Isomap. Science footer gives 22 December 2000. Read method lines 126–166, eigen construction 194–199, scope 207–226, Table 1 lines 412–435, notes 16–18 lines 338–365 (Floyd, elementwise squared distances and double centering, sampling/curvature/branch-separation conditions), and diagnostic note 42 lines 464–469. No visual figure inspection or full supplementary proof claimed. MIT archive URL failed with verified HTTP 404; its alternative path also failed. Original figures/data are not reused. Our relative Frobenius strain and direct distance RMSE are explicitly distinct from the paper’s residual variance.
- scikit-learn 1.7 — Manifold learning · Actually read fixed /1.7/ guide displaying 1.7.2: lines 90–91 nonlinear structure framing; Isomap lines 104–126, neighborhood, shortest paths, spectrum and original citation; LLE lines 127–140, weights and eigenproblem. Did not adopt guide complexity estimates for our distinct Jacobi implementation, and did not adopt its informal local-distance description as a full definition of LLE. Fixed Isomap API fetch failed and is not counted as a read source. No sklearn program run.
- A Global Geometric Framework for Nonlinear Dimensionality Reduction · Independently opened the five-page original Science reprint on the stated mirror. Read title/authors beginning at line 57 and 22 December 2000 footer (not the preceding article’s received date), neighborhood/graph/MDS steps at lines 137–166, geometric scope and convergence at 194–222, notes 16–18 (338–365) and Table 1 (412–435). Text extraction only; no original figure or supplementary-proof inspection and no original experiment reproduced. Distinguish Gram strain, distance RMSE and residual variance.
- scikit-learn 1.7 — Manifold learning · Independently read fixed /1.7 guide displaying 1.7.2, Isomap stages and citation (104–126), LLE reconstruction/eigenproblem description (127–140). No library runtime; tutorial solver complexity remains its own bounded Jacobi O(n^4) count.
相关主题