Part V · 第 18 章 无监督与自监督学习 · 18.1Part V · Ch. 18 Unsupervised & Self-Supervised Learning · 18.1

聚类与 PCAClustering & PCA

机器人记录下的数据大多没有标签:抓取位置、关节轨迹、点云、相机图像。无监督学习先问两个最朴素的问题:哪些数据点属于同一类(聚类),以及描述每个点真正需要几个数(降维)。本节在浏览器里实时运行 k-means(Lloyd 算法与 k-means++)、用 EM 训练高斯混合模型,把 PCA 看成“方差最大”与“重建误差最小”的同一件事,看清这些线性、团块状的方法在哪里失效,最后用 PCA 找出机器人手的“特征抓取”(eigengrasp)。 Most of what a robot records carries no labels: grasp locations, joint trajectories, point clouds, camera images. Unsupervised learning starts with two plain questions: which data points belong together (clustering), and how many numbers are really needed to describe each one (dimensionality reduction). This lesson runs k-means (Lloyd's algorithm and k-means++) live in the browser, trains a Gaussian mixture with EM, treats PCA as "maximum variance" and "minimum reconstruction error" at once, shows where these linear, blob-shaped methods break, and ends with the eigengrasps of a robot hand.

约 40 分钟~40 min 前置:1.12 奇异值分解 · 4.4 高斯分布 · 4.6 最大似然与 MAPPrereqs: 1.12 SVD · 4.4 The Gaussian · 4.6 MLE & MAP 6 个交互6 interactives

    1为什么机器人需要它Why robots need this

    前面几章的学习都有“标准答案”:16.1 节的回归和分类,每个输入都配着一个目标 \(y\)。可机器人每天产生的数据绝大多数没人标注。一个演示者在桌上做了 150 次抓取,日志里只有夹爪闭合时的位置,没人写下“这次抓的是杯子”;一只 15 个关节的灵巧手记录了几千个抓取姿态,没人告诉你哪些关节总是一起动;一段拾放演示是一条长长的时间序列,没人标出“这里开始抬起”。

    无监督学习从数据本身找结构。本节讲两类最基本、至今仍到处在用的工具:

    • 聚类:把数据分成 \(K\) 组,同组的点彼此相近。k-means 用“最近的中心”做硬划分;高斯混合模型(GMM)给每个点一个属于各组的概率,用 EM 算法训练,它建立在 4.4 节的多元高斯和 4.6 节的最大似然之上。
    • 主成分分析(PCA):找一个低维的线性子空间,让数据投影上去后损失最少。1.12 节已经用 SVD 算过点云的主方向和法向量;这里讲它的统计含义:为什么“方差最大”和“重建误差最小”是同一个问题,“解释方差”怎么读,以及该保留几个成分。

    它们在机器人里随处可见:把桌面点云分割成一个个物体,把视觉特征量化成“视觉单词”用于回环检测,把演示切成阶段,把动作空间离散成几个“模式”,把高维的手部姿态压缩成两三个协同量。它们的共同弱点同样重要:k-means 只认圆团,PCA 只认平面,数据一弯就失效。这正是 18.2 节自编码器要解决的问题。

    Learning in the previous chapters came with "answers": the regression and classification of Lesson 16.1 pair every input with a target \(y\). Yet most of the data a robot produces every day is never labelled. A demonstrator performs 150 grasps on a table and the log only holds where the gripper closed, not "this one was the mug"; a 15-joint dexterous hand records thousands of grasp postures and nobody says which joints always move together; a pick-and-place demonstration is a long time series and nobody marks "the lift starts here".

    Unsupervised learning finds structure in the data itself. This lesson covers the two most basic families of tools, still used everywhere:

    • Clustering: split the data into \(K\) groups whose members are close to each other. k-means makes a hard split by "nearest centre"; the Gaussian mixture model (GMM) gives each point a probability of belonging to each group and is trained by the EM algorithm, built on the multivariate Gaussian of Lesson 4.4 and the maximum likelihood of Lesson 4.6.
    • Principal component analysis (PCA): find a low-dimensional linear subspace onto which the data projects with the least loss. Lesson 1.12 already used the SVD to get the principal directions and the normal of a point cloud; here we cover its statistical meaning: why "maximum variance" and "minimum reconstruction error" are the same problem, how to read "explained variance", and how many components to keep.

    Robots use them everywhere: segmenting a tabletop point cloud into objects, quantizing visual features into "visual words" for loop closure, cutting demonstrations into phases, discretizing an action space into a few "modes", compressing high-dimensional hand postures into two or three synergies. Their shared weakness matters just as much: k-means only knows round blobs and PCA only knows flat subspaces, so both fail as soon as the data bends. That is the problem the autoencoders of Lesson 18.2 address.

    2直觉:插旗、站队、挪旗Intuition: plant flags, line up, move the flags

    在桌面上插 \(K\) 面小旗(中心 \(\hl{mu}{\boldsymbol\mu_k}\))。然后反复做两件事:① 站队:每个数据点走到离它最近的旗子下面;② 挪旗:每面旗子挪到它队伍的平均位置(重心)。这就是 Lloyd 算法,人们口中的 k-means。它在降低一个量:每个点到自己旗子的距离平方之和

    Plant \(K\) little flags on the table (centres \(\hl{mu}{\boldsymbol\mu_k}\)). Then repeat two things: ① line up: every data point walks to its nearest flag; ② move the flags: every flag moves to the average position (centroid) of its queue. That is Lloyd's algorithm, what people call k-means. It lowers one number, the sum of squared distances from each point to its own flag:

    $$ \hl{J}{J}=\sum_{n=1}^{N}\big\|\mathbf x_n-\boldsymbol\mu_{c(n)}\big\|^2 $$

    其中 \(c(n)\) 是点 \(\mathbf x_n\) 所在的组。站队这一步,在旗子不动时为每个点选了最近的旗,\(J\) 不会变大;挪旗这一步,在队伍不变时把旗子放到重心,而重心正是使队内距离平方和最小的点(第 5 节),\(J\) 也不会变大。\(J\) 只降不升,而把 \(N\) 个点分成 \(K\) 组的方式只有有限多种,所以算法一定会停。但它停下的地方只是“两步都改进不了”的地方,不一定是全局最好的分法。下图让你亲手体验这两点。

    Here \(c(n)\) is the cluster of point \(\mathbf x_n\). The line-up step picks the nearest flag for every point while the flags stand still, so \(J\) cannot grow; the move step puts each flag at its queue's centroid while the queues stay fixed, and the centroid is exactly the point that minimizes the sum of squared distances within the queue (Section 5), so \(J\) cannot grow either. \(J\) only goes down, and there are only finitely many ways to split \(N\) points into \(K\) groups, so the algorithm must stop. But where it stops is only a place that neither step can improve, not necessarily the best split overall. The figure lets you feel both facts.

    FIG 1Lloyd 算法:一步一步地站队、挪旗Lloyd's algorithm, one line-up and one move at a time
    每个点是演示者在 100 × 70 cm 桌面上闭合夹爪的位置(模拟数据,随机种子固定):“3 个物体”共 150 次抓取,“5 个物体”共 180 次。方块是中心 \(\boldsymbol\mu_k\),可以拖动;底色是离每个中心最近的区域,各组的色调依次为红、蓝、绿、琥珀、紫、青。按“① 站队”之前,点不带组的色调(画成坐标轴的颜色);之后染成所属中心的色调。“② 挪旗”时细箭头从旧中心指向新中心。右图是每半步之后的 \(J/N\)(cm²),绿色虚线是 30 次 k-means++ 重启中最好的 \(J/N\),记作 \(J^\star/N\)。 Each dot is where a demonstrator closed the gripper on a 100 × 70 cm table (simulated data, fixed random seed): "3 objects" has 150 grasps, "5 objects" 180. Squares are the centres \(\boldsymbol\mu_k\); drag them. The background tint is the region nearest to each centre, the clusters' hues being red, blue, green, amber, purple and cyan in that order. Before "① Line up" the dots carry no cluster hue (they are drawn in the axis colour); afterwards they take their centre's hue. On "② Move" thin arrows point from each old centre to its new one. Right: \(J/N\) (cm²) after every half-step; the green dashed line is the best \(J/N\) over 30 k-means++ restarts, written \(J^\star/N\).
    试一试Try this
    • 保持默认设置(3 个物体,\(K=3\)),交替按“① 站队”和“② 挪旗”,或直接按“运行”,直到收敛(一次站队后没有任何点换组)。默认起点要挪 8 次旗,\(J/N\) 从 582 降到 72.8 cm²,而且每半步都不升;注意中间那段几乎平坦的“停滞”。Keep the defaults (3 objects, \(K=3\)) and alternate "① Line up" and "② Move", or just press "Run", until it converges (a line-up in which no point changes cluster). From the default start the flags move 8 times and \(J/N\) falls from 582 to 72.8 cm², never rising at any half-step; notice the nearly flat "stall" in the middle.
    • 让 Lloyd 卡在坏的局部极小:按“角落起点”(所有中心挤在左上角)或者把所有中心拖到同一个角落,再运行到收敛。收敛后的 \(J\) 至少是 \(J^\star\) 的 1.5 倍(读数里的比值)。“角落起点”下有一面旗一个点都没分到:它成了“空簇”。Get Lloyd stuck in a bad local minimum: press "Corner start" (all centres bunched in the upper-left corner) or drag all centres into one corner, then run to convergence. The converged \(J\) is at least 1.5 times \(J^\star\) (the ratio in the readout). With "Corner start" one flag gets no points at all: it becomes an "empty cluster".
    核心洞见Key insight

    k-means 是坐标下降:未知数分两块,一块是每个点的组号(离散),一块是中心(连续),轮流固定一块、最优地解另一块。每一步都精确最优,所以 \(J\) 单调下降、有限步收敛;但整体问题是非凸的组合优化,坐标下降只保证停在一个“两块都不能单独改进”的点。起点决定结局。

    k-means is coordinate descent: the unknowns come in two blocks, every point's cluster label (discrete) and the centres (continuous), and it alternately fixes one block and solves the other exactly. Every step is exactly optimal, so \(J\) decreases monotonically and converges in finitely many steps; but the whole problem is a non-convex combinatorial one, and coordinate descent only promises a point where neither block can be improved on its own. The start decides the ending.

    3动手:软聚类、初始化与选 KPlay: soft clusters, initialization and choosing K

    高斯混合模型与 EMGaussian mixtures and EM

    k-means 用欧氏距离判断“最近”,等于默认每个组都是同样大小的圆团。真实的组常常不是:同一个长条形物体上的抓取点沿物体长轴散开;一个大托盘旁边放着一个小螺丝盒。高斯混合模型换一种说法:数据是这样产生的,先以概率 \(\hl{pi}{\pi_k}\) 选一个组 \(k\),再从这个组的高斯 \(\mathcal N(\boldsymbol\mu_k,\hl{Sigma}{\Sigma_k})\) 里抽一个点。每组有自己的位置、形状(协方差椭圆,4.4 节)和份额。

    训练它的 EM 算法和 Lloyd 长得几乎一样,只是“站队”变软了:E 步算每个点属于每组的后验概率,即责任 \(\hl{gamma}{\gamma_{nk}}\)(贝叶斯公式,4.2 节);M 步用这些责任作权重,重新估计每组的 \(\pi_k,\boldsymbol\mu_k,\Sigma_k\)(加权的最大似然,4.6 节)。每一轮 EM 都不会降低数据的对数似然(第 5 节证明)。

    k-means judges "nearest" by Euclidean distance, which amounts to assuming every group is a round blob of the same size. Real groups often are not: grasps on one long object spread along its main axis; a small screw box sits next to a big tray. A Gaussian mixture model tells a different story of how the data were made: first pick a group \(k\) with probability \(\hl{pi}{\pi_k}\), then draw a point from that group's Gaussian \(\mathcal N(\boldsymbol\mu_k,\hl{Sigma}{\Sigma_k})\). Each group has its own position, shape (a covariance ellipse, Lesson 4.4) and share.

    The EM algorithm that trains it looks almost like Lloyd's, except that the line-up becomes soft: the E step computes the posterior probability of each point belonging to each group, the responsibility \(\hl{gamma}{\gamma_{nk}}\) (Bayes' rule, Lesson 4.2); the M step re-estimates every group's \(\pi_k,\boldsymbol\mu_k,\Sigma_k\) with those responsibilities as weights (weighted maximum likelihood, Lesson 4.6). No EM round ever lowers the log-likelihood of the data (proved in Section 5).

    FIG 2k-means 对 GMM:EM 实时训练k-means versus a GMM trained live by EM
    三组模拟的抓取数据:“长条”是两个平行的长条形物体(各 110 次抓取),“大小悬殊”是一个散开的大托盘(200 次)旁边一个紧凑的小盒子(30 次),“3 个物体”同 FIG 1。GMM 模式下,每组画出马氏距离 1 和 2 的椭圆(4.4 节),旁边标出份额 \(\pi_k\);点的色调是责任最大的那一组,越不确定(最大责任越小)越透明。k-means 模式下底色是最近中心的区域。被分到“错误物体”的点(按最佳的一一对应把组和真实物体配对之后)画成空心圆圈。“一致率”是配对后分对的比例。右图是每轮之后的平均对数似然(GMM)或 \(J/N\)(k-means)。为防止某个高斯塌缩到单个点上,每个协方差都加了 0.001 cm² 的下限。悬停或点按某个点可以读出它的责任。 Three simulated grasp data sets: "Elongated" is two parallel long objects (110 grasps each), "Unequal" is a widely spread big tray (200 grasps) next to a compact small box (30), "3 objects" is the set of FIG 1. In GMM mode every group is drawn as its Mahalanobis-distance 1 and 2 ellipses (Lesson 4.4) labelled with its share \(\pi_k\); a dot takes the hue of its most responsible group and is more transparent the less certain it is (the smaller its largest responsibility). In k-means mode the tint is the nearest-centre region. Points assigned to the "wrong object" (after pairing groups with true objects by the best one-to-one matching) are drawn as hollow rings; "agreement" is the fraction right after that pairing. Right: the mean log-likelihood (GMM) or \(J/N\) (k-means) after every round. To keep any Gaussian from collapsing onto a single point, every covariance gets a floor of 0.001 cm². Hover over or tap a point to read its responsibilities.
    • 选“长条”和 k-means(\(K=2\)),运行到收敛:k-means 把两个长条拦腰切开,一致率只有约 60%,并且换几个种子(“新种子”)都一样。这不是初始化不好:这样切开的 \(J\) 确实更小。Choose "Elongated" and k-means (\(K=2\)) and run to convergence: k-means cuts both bars across the middle, agreement is only about 60%, and the same happens with other seeds ("New seed"). This is not a bad start: that cut really has a smaller \(J\).
    • 切到 GMM(仍是“长条”),按“运行”:对数似然一路上升,两个椭圆拉长并转到长条的方向,大约 25 轮后收敛,一致率达到 95% 以上(默认种子是 100%)。再试“大小悬殊”:k-means 约 71%,GMM 约 99%,小盒子的份额 \(\pi\) 约 0.14。Switch to GMM (still "Elongated") and press "Run": the log-likelihood rises all the way, the two ellipses stretch and turn along the bars, and after about 25 rounds it converges with agreement above 95% (100% with the default seed). Then try "Unequal": k-means gets about 71%, the GMM about 99%, and the small box's share \(\pi\) comes out near 0.14.

    初始化与选 KInitialization and choosing K

    FIG 1 已经看到:Lloyd 的结局取决于起点。最常见的起点有两种。随机起点(Forgy 法):随机挑 \(K\) 个数据点当初始中心,容易把两个中心放进同一团、另一团没有中心。k-means++(Arthur 与 Vassilvitskii,2007):第一个中心随机挑,之后每个新中心按“到已有中心的最近距离的平方” \(D(\mathbf x)^2\) 成比例地抽样,离现有中心远的点更容易被选中,于是中心自然散开。它在期望意义下保证结果不差于最优解的 \(O(\log K)\) 倍,实践中再配合多次重启取最好的一次。

    另一个问题是 \(K\) 本身。\(J^\star(K)\)(\(K\) 个组时能达到的最小 \(J\))随 \(K\) 单调下降,\(K=N\) 时为 0,所以不能拿 \(J\) 直接选 \(K\)。常用的经验法是“肘部”:画 \(J^\star(K)\) 对 \(K\),找下降突然变缓的那个拐点。对 GMM 可以用信息准则(第 5 节的 BIC)。下图是一个货架上的 8 个格子,每格 25 次抓取。

    FIG 1 showed that Lloyd's ending depends on its start. Two starts are common. Random start (Forgy's method): pick \(K\) data points at random as the initial centres; it easily puts two centres into one blob and none into another. k-means++ (Arthur and Vassilvitskii, 2007): choose the first centre at random, then draw every new centre with probability proportional to \(D(\mathbf x)^2\), the squared distance to the nearest centre chosen so far, so points far from the existing centres are favoured and the centres spread out naturally. In expectation it is guaranteed to be within an \(O(\log K)\) factor of the optimum, and in practice it is combined with several restarts, keeping the best.

    The other question is \(K\) itself. \(J^\star(K)\), the smallest \(J\) reachable with \(K\) groups, decreases monotonically in \(K\) and is 0 at \(K=N\), so \(J\) alone cannot choose \(K\). A common rule of thumb is the "elbow": plot \(J^\star(K)\) against \(K\) and look for the bend where the decrease suddenly slows. For a GMM one can use an information criterion (the BIC of Section 5). The figure below is a shelf with 8 bins and 25 grasps per bin.

    FIG 3100 次重启:随机起点对 k-means++,以及肘部100 restarts: random start versus k-means++, and the elbow
    左:货架俯视图,8 个格子各 25 个点(模拟)。移动 K 滑块时显示该 K 下最好的解;按一次“100 次 …”后,显示这一批里最差的那次。右上:100 次运行收敛后的 \(J/J^\star\) 分布,红色是随机起点,蓝色是 k-means++;最左一格是“命中”(与 \(J^\star\) 相差不到 1%),\(J^\star\) 是 60 次 k-means++ 重启中最好的一次。右下:肘部曲线 \(J^\star(K)/N\),琥珀色点是当前 K。每次改变 K,两种方法的随机数都从同一个种子重新开始,所以“改 K 后的第一批”结果可以复现。 Left: the shelf seen from above, 8 bins with 25 points each (simulated). Moving the K slider shows the best solution at that K; after pressing one of the "100 × …" buttons it shows the worst run of that batch. Top right: the distribution of \(J/J^\star\) after convergence over 100 runs, red for random starts, blue for k-means++; the leftmost bin is a "hit" (within 1% of \(J^\star\)), where \(J^\star\) is the best of 60 k-means++ restarts. Bottom right: the elbow curve \(J^\star(K)/N\), the amber dot marking the current K. Whenever K changes, both methods' random numbers restart from the same seed, so "the first batch after changing K" is reproducible.
    • 看肘部曲线,把 K 设在“拐点”上(读数里的 \(J^\star(K)/J^\star(K-1)\) 从 0.5 左右突然跳到 0.9 以上的前一个 K)。它正好等于格子数。Read the elbow curve and set K at the bend (the last K before the readout's \(J^\star(K)/J^\star(K-1)\) jumps from about 0.5 to above 0.9). It equals the number of bins.
    • 在 \(K=8\) 时两个按钮各按一次:改 K 后的第一批里,随机起点只有 21 次命中,平均 \(J/J^\star\) 约 2.2;k-means++ 有 60 次命中,平均约 1.5,而且平均只需约 3 次迭代(随机起点约 6 次)。即使用 k-means++,也有四成的运行没找到最优:所以要重启。At \(K=8\) press each button once: in the first batch after changing K, random starts hit only 21 times with a mean \(J/J^\star\) of about 2.2; k-means++ hits 60 times with a mean of about 1.5, and needs only about 3 iterations on average (random starts about 6). Even with k-means++, four runs in ten miss the optimum: hence the restarts.
    值得注意Things worth noticing

    (1) GMM 胜过 k-means,靠的是更丰富的模型(每组自己的协方差),不是更好的优化:FIG 2 里 k-means 把长条切开,是因为在它的目标 \(J\) 下这样切就是更好的。选错了模型,优化得再好也没用。 (2) GMM 也有局部极小,而且参数更多(2D 里每组 6 个:2 个均值、3 个协方差、1 个份额),收敛也更慢(“大小悬殊”要 60 多轮),所以实践中常先用 k-means 的结果给 EM 初始化。 (3) 在 FIG 3 的最差运行里,常见的毛病是“两个中心挤在一格,另有一个中心横跨两格”,正是 FIG 1 那种局部极小。

    (1) The GMM beats k-means through a richer model (each group's own covariance), not through better optimization: in FIG 2 k-means cuts the bars because under its objective \(J\) that cut is better. With the wrong model, no amount of optimization helps. (2) The GMM has local optima too, more parameters (6 per group in 2D: 2 for the mean, 3 for the covariance, 1 share) and slower convergence ("Unequal" takes over 60 rounds), which is why EM is often initialized from a k-means result in practice. (3) In the worst runs of FIG 3 the usual defect is "two centres squeezed into one bin while another centre straddles two bins", exactly the local minimum of FIG 1.

    4另一个视角:不是分组,而是压缩:PCAAnother view: compress instead of group: PCA

    聚类用 \(K\) 个“原型”概括数据;降维换个角度,用更少的坐标描述每一个点。设想一台机械臂做了 120 次够取,每次记录肩关节角 \(q_1\) 和肘关节角 \(q_2\)。抬肩时人总是同时伸肘,两个角高度相关:点云是一根斜着的细长条。如果只允许用一个数描述每次够取,最好的办法是在这根长条上画一条直线 \(\hl{u}{\mathbf u}\)(单位向量),用点在这条线上的投影坐标 \(z=\mathbf u^\top(\mathbf x-\bar{\mathbf x})\) 代替原来的两个角。

    线该朝哪个方向?有两种说法。一种是让投影后的坐标方差最大,保留尽可能多的“变化”;另一种是让每个点到直线的距离平方和(重建误差,即图中的残差 \(\hl{res}{\mathbf r_n}\))最小。下图告诉你它们是同一个方向:对每个点,到均值的距离平方 = 投影长度平方 + 残差平方(勾股定理),左边与方向无关,所以投影方差最大时残差一定最小。这个方向就是协方差矩阵 \(S\) 最大特征值 \(\hl{lam}{\lambda_1}\) 的特征向量,第一主成分。

    Clustering summarizes data with \(K\) "prototypes"; dimensionality reduction takes another angle and describes every point with fewer coordinates. Picture an arm making 120 reaches, each recorded as its shoulder angle \(q_1\) and elbow angle \(q_2\). Raising the shoulder always comes with extending the elbow, so the two angles are strongly correlated: the cloud is a thin slanted bar. If each reach may be described by a single number, the best idea is to draw a line \(\hl{u}{\mathbf u}\) (a unit vector) along the bar and replace the two angles by the coordinate of the projection on it, \(z=\mathbf u^\top(\mathbf x-\bar{\mathbf x})\).

    Which way should the line point? There are two answers. One makes the projected coordinate's variance as large as possible, keeping as much "variation" as it can; the other makes the sum of squared distances from the points to the line (the reconstruction error, the residuals \(\hl{res}{\mathbf r_n}\) in the figure) as small as possible. The figure shows they give the same direction: for each point, squared distance to the mean = squared projection + squared residual (Pythagoras), and the left side does not depend on the direction, so the largest projected variance means the smallest residual. That direction is the eigenvector of the covariance matrix \(S\) with the largest eigenvalue \(\hl{lam}{\lambda_1}\): the first principal component.

    FIG 4转动直线:方差最大 = 重建误差最小Turn the line: maximum variance = minimum reconstruction error
    左:120 次够取的肩角 \(q_1\) 与肘角 \(q_2\)(度,模拟数据),蓝点是数据,琥珀色直线是方向 \(\mathbf u\)(拖动线上的圆形手柄转动它),琥珀小点是投影,红色短线是残差。中空的十字是直线经过的点:开启“中心化”时是均值 \(\bar{\mathbf x}\),关闭时是原点。勾选“显示主轴”会画出两条绿色虚线主轴。右:投影的均方长度随直线角度 \(\theta\) 的变化(中心化时就是投影方差 \(\mathbf u^\top S\mathbf u\)),虚线是总量(中心化时是 \(\operatorname{tr}S\),关闭时是 \(\|\mathbf x\|^2\) 的均值),琥珀点是当前角度;曲线和虚线之间的距离就是残差均方。 Left: the shoulder angle \(q_1\) and elbow angle \(q_2\) of 120 reaches (degrees, simulated); blue dots are the data, the amber line is the direction \(\mathbf u\) (turn it with the round handle on the line), small amber dots are the projections and red segments the residuals. The hollow cross is the point the line passes through: the mean \(\bar{\mathbf x}\) with "centre" on, the origin with it off. Ticking "show axes" draws the two principal axes as green dashed lines. Right: the mean squared projection as a function of the line's angle \(\theta\) (with centring, exactly the projected variance \(\mathbf u^\top S\mathbf u\)); the dashed line is the total (\(\operatorname{tr}S\) with centring, the mean of \(\|\mathbf x\|^2\) without) and the amber dot is the current angle. The gap between the curve and the dashed line is the mean squared residual.
    • “显示主轴”保持关闭,拖动手柄,把直线转到与第一主成分相差 2° 以内(看右图曲线的最高点,读数会显示差多少度)。这时残差最小:投影保留了约 97.9% 的方差,单个角度描述一次够取几乎不丢信息。With "show axes" off, drag the handle and turn the line to within 2° of the first principal component (aim for the top of the curve on the right; the readout shows how many degrees off you are). There the residual is smallest: the projection keeps about 97.9% of the variance, and one number describes a reach with almost nothing lost.
    • 关闭“中心化”,再找过原点的最佳直线(拖动或按“对准最佳方向”,与最佳方向相差 2° 以内):它指向点云的均值(约 60°),而不是沿着点云的伸展方向(约 −44°),却号称“保留了”约 95%。忘记减均值时,第一主成分描述的是“数据离原点多远”。Turn "centre" off and find the best line through the origin (drag, or press "Snap to best", to within 2° of the best direction): it points at the cloud's mean (about 60°), not along the cloud's spread (about −44°), and yet claims to "keep" about 95%. Forget to subtract the mean and the first component describes "how far the data are from the origin".

    换到“各向同性”的点云:两个方向的方差差不多(约 110 对 88),右图的曲线几乎是平的,第一主成分只解释约 56%,换一个样本(“新样本”)主轴就会大幅转动。PCA 的方向只在特征值明显分开时才有意义。

    Switch to the "isotropic" cloud: the two directions have similar variances (about 110 versus 88), the curve on the right is almost flat, the first component explains only about 56%, and a new sample ("New sample") turns the axes a lot. PCA directions only mean something when the eigenvalues are clearly apart.

    线性与团块的极限Where lines and blobs give out

    PCA 找的是平的子空间,k-means 找的是凸的团块(每组是一个 Voronoi 多边形)。数据一弯,两者都会出问题。下图第一组数据是夹爪沿圆碗边缘擦拭的路径(3/4 个圆):它本质上是一维的(一个角度就能描述每个点),但一条直线只能保留约 70% 的方差。一个补救办法是分段线性:先用 k-means 把数据切成 \(K\) 段,再在每段里各做一次一维 PCA,即局部 PCA,也就是概率模型里的“混合 PCA”的简化版。第二组数据是激光雷达在一根圆柱和外圈圆墙上的点:两组是同心圆环,k-means 怎么画直线边界也分不开它们,但若换一个特征,用点到圆心的半径 \(\|\mathbf x-\mathbf c\|\),问题立刻变成一维、可分。选对特征,线性方法就够了;核方法(核 PCA、谱聚类)和 18.2 节的自编码器,都是让机器自己学这种特征。

    PCA looks for flat subspaces; k-means looks for convex blobs (each cluster is a Voronoi polygon). When the data bend, both fail. The first data set below is a gripper's path wiping around the rim of a round bowl (three quarters of a circle): it is intrinsically one-dimensional (one angle describes every point), yet a single line keeps only about 70% of the variance. One remedy is to go piecewise linear: cut the data into \(K\) pieces with k-means and run a 1D PCA inside each, a local PCA, the simplified version of what probabilistic models call a "mixture of PCAs". The second data set is lidar points on a round pillar and on the circular wall around it: two concentric rings that k-means cannot separate with any straight boundary, but switch to another feature, the radius \(\|\mathbf x-\mathbf c\|\) from the centre, and the problem becomes one-dimensional and separable. With the right features linear methods suffice; kernel methods (kernel PCA, spectral clustering) and the autoencoders of Lesson 18.2 let the machine learn such features itself.

    FIG 5数据一弯:局部 PCA 与换特征When the data bend: local PCA and a change of features
    “擦拭路径”:160 个点(cm,噪声 0.9 cm),每段的点染上该段的色调,琥珀色线段是每段的一维主轴(画到该段投影的范围),红色短线是残差。“相对误差”是残差平方和除以数据的总方差(\(N\) 乘以 \(\operatorname{tr}S\))。K = 1 就是普通 PCA。“同心圆环”:70 个柱面点和 150 个墙面点,用 K = 2 的 k-means(30 次 k-means++ 重启中最好的一次)分组,色调表示分到的组;十字是计算半径用的圆心 \(\mathbf c\)。 "Wiping path": 160 points (cm, noise 0.9 cm); each piece's points take that piece's hue, the amber segments are the pieces' 1D principal axes (drawn over the range of their projections) and red segments are the residuals. "Relative error" is the sum of squared residuals divided by the total variation of the data (\(N\) times \(\operatorname{tr}S\)). K = 1 is plain PCA. "Concentric rings": 70 pillar points and 150 wall points grouped by k-means with K = 2 (the best of 30 k-means++ restarts); the hue shows the assigned group, and the cross is the centre \(\mathbf c\) used for the radius.
    • 在“擦拭路径”上逐步增大 K:K = 1 时相对误差约 30%,K = 2 约 3.2%;增大到相对误差低于 0.5% 为止(K = 4,约 0.43%)。再往上几乎不降:剩下的就是 0.9 cm 的测量噪声。On "Wiping path" raise K step by step: about 30% relative error at K = 1, about 3.2% at K = 2; keep going until it is below 0.5% (K = 4, about 0.43%). Beyond that it barely drops: what remains is the 0.9 cm measurement noise.
    • 切到“同心圆环”:用坐标 \((x,y)\) 聚类,一致率只有约 50%(k-means 把两环一起切成左右两半);把特征换成“半径”,一致率变成 100%。Switch to "Concentric rings": clustering on the coordinates \((x,y)\) gives only about 50% agreement (k-means cuts both rings into left and right halves together); switch the feature to "radius" and agreement becomes 100%.

    5再看数学The math

    k-means:目标与两步的最优性k-means: the objective and why both steps are optimal

    Data \(\mathbf x_1,\dots,\mathbf x_N\in\R^D\). Write the assignment as indicators \(r_{nk}\in\{0,1\}\) with \(\sum_k r_{nk}=1\). The objective is

    数据 \(\mathbf x_1,\dots,\mathbf x_N\in\R^D\)。把分组写成指示量 \(r_{nk}\in\{0,1\}\),\(\sum_k r_{nk}=1\)。目标函数是

    $$ \hl{J}{J}(r,\boldsymbol\mu)=\sum_{n=1}^{N}\sum_{k=1}^{K} r_{nk}\,\|\mathbf x_n-\hl{mu}{\boldsymbol\mu_k}\|^2 $$

    站队:固定 \(\boldsymbol\mu\),\(J\) 对每个 \(n\) 分开,各自取 \(r_{nk}=1\) 给距离最小的 \(k\),这显然是最优的。挪旗:固定 \(r\),\(J\) 是 \(\boldsymbol\mu_k\) 的凸二次函数,令梯度为零:

    Line up: with \(\boldsymbol\mu\) fixed, \(J\) separates over \(n\), and setting \(r_{nk}=1\) for the nearest \(k\) is obviously optimal. Move: with \(r\) fixed, \(J\) is a convex quadratic in \(\boldsymbol\mu_k\); set its gradient to zero:

    $$ \frac{\partial J}{\partial\boldsymbol\mu_k}=-2\sum_n r_{nk}(\mathbf x_n-\boldsymbol\mu_k)=0\quad\Longrightarrow\quad \boldsymbol\mu_k=\frac{\sum_n r_{nk}\,\mathbf x_n}{\sum_n r_{nk}} $$

    即重心。另一种看法:对任意点 \(\mathbf m\),\(\sum_{n\in k}\|\mathbf x_n-\mathbf m\|^2=\sum_{n\in k}\|\mathbf x_n-\boldsymbol\mu_k\|^2+N_k\|\boldsymbol\mu_k-\mathbf m\|^2\),所以偏离重心只会多出一项。两步都精确最优,\(J\) 单调不增;分组方式至多 \(K^N\) 种,且一次真正的改变会严格降低 \(J\),所以有限步内收敛。若某组变空(FIG 1 的“角落起点”),重心无定义,本页让它留在原地;实际库里常把它重新放到离现有中心最远的点上。

    找全局最优的 k-means 划分在一般情况下是 NP 难的,所以只能靠好的起点和重启。k-means++ 的抽样规则是:已选中心集合为 \(\mathcal C\) 时,下一个中心取 \(\mathbf x_n\) 的概率为

    the centroid. Another way to see it: for any point \(\mathbf m\), \(\sum_{n\in k}\|\mathbf x_n-\mathbf m\|^2=\sum_{n\in k}\|\mathbf x_n-\boldsymbol\mu_k\|^2+N_k\|\boldsymbol\mu_k-\mathbf m\|^2\), so leaving the centroid only adds a term. Both steps are exactly optimal and \(J\) never increases; there are at most \(K^N\) assignments and a genuine change strictly lowers \(J\), so it converges in finitely many steps. If a cluster becomes empty (FIG 1's "Corner start") its centroid is undefined; this page leaves it where it is, while real libraries often move it to the point farthest from the current centres.

    Finding the globally optimal k-means partition is NP-hard in general, so good starts and restarts are all one has. The k-means++ rule: with the set of chosen centres \(\mathcal C\), the next centre is \(\mathbf x_n\) with probability

    $$ P(\mathbf x_n)=\frac{D(\mathbf x_n)^2}{\sum_m D(\mathbf x_m)^2},\qquad D(\mathbf x)=\min_{\mathbf c\in\mathcal C}\|\mathbf x-\mathbf c\|,\qquad \mathbb E\big[J_0\big]\le 8(\ln K+2)\,J^\star $$

    其中 \(J_0\) 是抽样得到的初始中心本身的代价:右边的界对它就已经成立(Arthur 与 Vassilvitskii,2007),之后的 Lloyd 迭代只会让 \(J\) 更小。

    Here \(J_0\) is the cost of the sampled seeds themselves: the bound on the right already holds for them (Arthur and Vassilvitskii, 2007), and the Lloyd iterations that follow can only lower \(J\).

    高斯混合与 EMGaussian mixtures and EM

    $$ p_\theta(\mathbf x)=\sum_{k=1}^{K}\hl{pi}{\pi_k}\,\mathcal N(\mathbf x;\boldsymbol\mu_k,\hl{Sigma}{\Sigma_k}),\qquad \log p_\theta(\mathcal D)=\sum_{n=1}^{N}\log\sum_{k=1}^{K}\pi_k\,\mathcal N(\mathbf x_n;\boldsymbol\mu_k,\Sigma_k) $$

    对数里面有求和,导数为零的方程没有闭式解。EM 的做法是引入隐变量“这个点来自哪一组”。E 步:用当前参数算后验(责任)

    The sum inside the logarithm means the zero-gradient equations have no closed-form solution. EM introduces the hidden variable "which group did this point come from". E step: compute the posterior (the responsibilities) with the current parameters,

    $$ \hl{gamma}{\gamma_{nk}}=\frac{\pi_k\,\mathcal N(\mathbf x_n;\boldsymbol\mu_k,\Sigma_k)}{\sum_j\pi_j\,\mathcal N(\mathbf x_n;\boldsymbol\mu_j,\Sigma_j)} $$

    M 步:把责任当作“每个点有 \(\gamma_{nk}\) 份属于第 \(k\) 组”,做加权的最大似然,记 \(N_k=\sum_n\gamma_{nk}\):

    M step: treat point \(n\) as belonging to group \(k\) with weight \(\gamma_{nk}\) and do weighted maximum likelihood; with \(N_k=\sum_n\gamma_{nk}\):

    $$ \pi_k=\frac{N_k}{N},\qquad \boldsymbol\mu_k=\frac1{N_k}\sum_n\gamma_{nk}\mathbf x_n,\qquad \Sigma_k=\frac1{N_k}\sum_n\gamma_{nk}(\mathbf x_n-\boldsymbol\mu_k)(\mathbf x_n-\boldsymbol\mu_k)^\top $$

    为什么似然不降:对任意满足 \(\sum_k q_{nk}=1\) 的权重 \(q_{nk}>0\),由于对数是凹函数(Jensen 不等式),

    Why the likelihood never drops: for any weights \(q_{nk}>0\) with \(\sum_k q_{nk}=1\), concavity of the logarithm (Jensen's inequality) gives

    $$ \log\sum_k\pi_k\mathcal N(\mathbf x_n;\boldsymbol\mu_k,\Sigma_k)=\log\sum_k q_{nk}\frac{\pi_k\mathcal N(\cdot)}{q_{nk}}\;\ge\;\sum_k q_{nk}\log\frac{\pi_k\mathcal N(\mathbf x_n;\boldsymbol\mu_k,\Sigma_k)}{q_{nk}} $$

    当 \(q_{nk}=\gamma_{nk}\) 时等号成立(E 步让下界在当前参数处贴住似然),M 步再对参数最大化这个下界(它对每组是可以闭式求解的加权高斯似然)。似然 ≥ 新下界 ≥ 旧下界 = 旧似然,所以每一轮都不降。这个下界在 19.1 节的 VAE 里会再次出现,那里叫 ELBO。与 k-means 的关系:令所有 \(\Sigma_k=\sigma^2I\)、\(\pi_k=1/K\) 固定,让 \(\sigma\to0\),责任变成 0 或 1(离最近中心的那组得 1),M 步只剩更新均值:EM 退化为 k-means。

    两个坑。一是奇异性:如果某个高斯的均值正好落在一个数据点上、方差趋于 0,该点的密度趋于无穷,似然无上界。FIG 2 给每个协方差加了 \(\varepsilon I\),\(\varepsilon=0.001\) cm²(这让 M 步不再是严格的极大化,但在本页数据上对数似然的下降不超过 \(10^{-7}\));更严格的做法是给协方差加先验做 MAP(4.6 节)。二是选 K:似然随 K 单调上升。贝叶斯信息准则 \(\mathrm{BIC}=-2\log p_{\hat\theta}(\mathcal D)+P\ln N\)(\(P\) 为自由参数个数:2D 中每组有 2 个均值和 3 个全协方差参数,共 5 个,再加 \(K-1\) 个份额)取最小,就在拟合与复杂度之间做了折中。

    with equality when \(q_{nk}=\gamma_{nk}\) (the E step makes the bound touch the likelihood at the current parameters), and the M step maximizes that bound over the parameters (for each group it is a weighted Gaussian likelihood with a closed-form maximizer). Likelihood ≥ new bound ≥ old bound = old likelihood, so no round goes down. This bound returns in the VAE of Lesson 19.1, where it is called the ELBO. The link to k-means: fix all \(\Sigma_k=\sigma^2I\) and \(\pi_k=1/K\) and let \(\sigma\to0\); the responsibilities become 0 or 1 (1 for the nearest centre), the M step only updates the means, and EM turns into k-means.

    Two traps. The first is singularity: if a Gaussian's mean sits exactly on one data point and its variance goes to 0, that point's density goes to infinity and the likelihood is unbounded. FIG 2 adds \(\varepsilon I\) with \(\varepsilon=0.001\) cm² to every covariance (so the M step is no longer an exact maximization, but on this page's data the log-likelihood never drops by more than \(10^{-7}\)); the cleaner fix is a prior on the covariances, i.e. MAP (Lesson 4.6). The second is choosing K: the likelihood rises monotonically with K. Minimizing the Bayesian information criterion \(\mathrm{BIC}=-2\log p_{\hat\theta}(\mathcal D)+P\ln N\) (\(P\) free parameters: in 2D, 5 per group, 2 for the mean and 3 for a full covariance, plus \(K-1\) shares) trades fit against complexity.

    PCA:方差最大与误差最小PCA: maximum variance and minimum error

    记均值 \(\bar{\mathbf x}=\frac1N\sum_n\mathbf x_n\),把中心化后的数据按行堆成 \(N\times D\) 矩阵 \(\tilde X\),样本协方差 \(S=\frac1N\tilde X^\top\tilde X\)(统计软件常用 \(\frac1{N-1}\),只差一个比例,方向不变)。沿单位向量 \(\mathbf u\) 的投影方差为 \(\mathbf u^\top S\mathbf u\)。在 \(\|\mathbf u\|=1\) 的约束下最大化它(拉格朗日乘子,6.7 节):

    With the mean \(\bar{\mathbf x}=\frac1N\sum_n\mathbf x_n\), stack the centred data as rows of an \(N\times D\) matrix \(\tilde X\); the sample covariance is \(S=\frac1N\tilde X^\top\tilde X\) (statistics packages often use \(\frac1{N-1}\), a mere scale factor that leaves the directions unchanged). The variance of the projection onto a unit vector \(\mathbf u\) is \(\mathbf u^\top S\mathbf u\). Maximize it subject to \(\|\mathbf u\|=1\) (Lagrange multipliers, Lesson 6.7):

    $$ \nabla_{\mathbf u}\big[\hl{u}{\mathbf u}^\top S\mathbf u-\lambda(\mathbf u^\top\mathbf u-1)\big]=0\;\Longrightarrow\; S\mathbf u=\lambda\mathbf u,\qquad \mathbf u^\top S\mathbf u=\lambda $$

    所以驻点都是特征向量,投影方差就是特征值,最大值在 \(\hl{lam}{\lambda_1}\) 处(1.11 节:对称矩阵的特征向量正交,特征值为实数且这里非负)。误差的那一面:点 \(\tilde{\mathbf x}_n\) 在直线上的重建是 \(\mathbf u\mathbf u^\top\tilde{\mathbf x}_n\),

    So the stationary points are the eigenvectors, the projected variance is the eigenvalue, and the maximum is at \(\hl{lam}{\lambda_1}\) (Lesson 1.11: a symmetric matrix has orthogonal eigenvectors and real eigenvalues, here non-negative). The error side: the reconstruction of \(\tilde{\mathbf x}_n\) on the line is \(\mathbf u\mathbf u^\top\tilde{\mathbf x}_n\), and

    $$ \frac1N\sum_n\|\hl{res}{\mathbf r_n}\|^2=\frac1N\sum_n\big\|\tilde{\mathbf x}_n-\mathbf u\mathbf u^\top\tilde{\mathbf x}_n\big\|^2=\underbrace{\frac1N\sum_n\|\tilde{\mathbf x}_n\|^2}_{\operatorname{tr}S}-\;\mathbf u^\top S\mathbf u $$

    这就是 FIG 4 的“勾股定理”:残差均方 = 总方差 − 投影方差。推广到 \(q\) 个成分:取 \(W_q=[\mathbf v_1,\dots,\mathbf v_q]\)(前 \(q\) 个特征向量),编码 \(\mathbf z=W_q^\top(\mathbf x-\bar{\mathbf x})\),解码 \(\hat{\mathbf x}=\bar{\mathbf x}+W_q\mathbf z\),均方重建误差恰为被丢掉的特征值之和,“解释方差比” \(\eta_q\) 为保留的那部分:

    This is FIG 4's "Pythagoras": mean squared residual = total variance − projected variance. For \(q\) components take \(W_q=[\mathbf v_1,\dots,\mathbf v_q]\) (the first \(q\) eigenvectors), encode \(\mathbf z=W_q^\top(\mathbf x-\bar{\mathbf x})\) and decode \(\hat{\mathbf x}=\bar{\mathbf x}+W_q\mathbf z\); the mean squared reconstruction error is exactly the sum of the discarded eigenvalues, and the "explained variance ratio" \(\eta_q\) is the part kept:

    $$ \frac1N\sum_n\|\mathbf x_n-\hat{\mathbf x}_n\|^2=\sum_{i>q}\lambda_i,\qquad \eta_q=\frac{\sum_{i\le q}\hl{lamk}{\lambda_i}}{\sum_{i=1}^{D}\lambda_i} $$

    与 SVD 的关系(1.12 节):\(\tilde X=U\Sigma V^\top\),则 \(S=\frac1N V\Sigma^2V^\top\),所以主方向就是 \(V\) 的列,\(\lambda_i=\sigma_i^2/N\);1.12 节的“\(\sigma_i/\sqrt N\) 是沿该方向的标准差”说的正是 \(\sqrt{\lambda_i}\)。数值上直接对 \(\tilde X\) 做 SVD 比先算 \(S\) 再求特征值更稳(不会把条件数平方),\(N\ll D\) 时(例如图像)也更省。最小重建误差这件事就是 1.12 节的 Eckart–Young 定理:秩 \(q\) 截断 SVD 是最好的秩 \(q\) 近似。

    标准化:PCA 依赖单位。若特征的单位不同(弧度与牛顿),应先把每一维除以自己的标准差,相当于对相关矩阵做 PCA。白化:用 \(\Lambda_q^{-1/2}W_q^\top(\mathbf x-\bar{\mathbf x})\) 得到协方差为单位阵的坐标。概率 PCA(Tipping 与 Bishop,1999)把 PCA 写成一个线性高斯隐变量模型 \(\mathbf x=W\mathbf z+\bar{\mathbf x}+\boldsymbol\epsilon\),\(\mathbf z\sim\mathcal N(0,I)\),\(\boldsymbol\epsilon\sim\mathcal N(0,\sigma^2I)\),其最大似然解张成同一个主子空间。把线性的编码、解码换成神经网络,就是 18.2 节的自编码器;再把隐变量当成概率分布,就是 19.1 节的 VAE。

    Relation to the SVD (Lesson 1.12): with \(\tilde X=U\Sigma V^\top\), \(S=\frac1N V\Sigma^2V^\top\), so the principal directions are the columns of \(V\) and \(\lambda_i=\sigma_i^2/N\); Lesson 1.12's "\(\sigma_i/\sqrt N\) is the standard deviation along that direction" is exactly \(\sqrt{\lambda_i}\). Numerically, an SVD of \(\tilde X\) is more stable than forming \(S\) and taking its eigenvalues (it does not square the condition number), and cheaper when \(N\ll D\) (images, say). The minimum-reconstruction-error property is Lesson 1.12's Eckart–Young theorem: the rank-\(q\) truncated SVD is the best rank-\(q\) approximation.

    Standardization: PCA depends on units. If features have different units (radians and newtons), first divide each dimension by its own standard deviation, which amounts to PCA of the correlation matrix. Whitening: \(\Lambda_q^{-1/2}W_q^\top(\mathbf x-\bar{\mathbf x})\) gives coordinates with identity covariance. Probabilistic PCA (Tipping and Bishop, 1999) writes PCA as a linear-Gaussian latent-variable model \(\mathbf x=W\mathbf z+\bar{\mathbf x}+\boldsymbol\epsilon\), \(\mathbf z\sim\mathcal N(0,I)\), \(\boldsymbol\epsilon\sim\mathcal N(0,\sigma^2I)\), whose maximum-likelihood solution spans the same principal subspace. Replace the linear encoder and decoder by neural networks and you get the autoencoders of Lesson 18.2; treat the latent as a probability distribution and you get the VAE of Lesson 19.1.

    三者是一家One family

    k-means 用 \(K\) 个点(零维)近似数据,PCA 用一个 \(q\) 维平面,局部 PCA 用 \(K\) 个 \(q\) 维小平面;GMM 和概率 PCA 是前两者的概率版本。它们都最小化某种平方重建误差(或最大化高斯似然),也都只看二阶统计量(均值与协方差),这既是它们简单可靠的原因,也是它们看不见弯曲结构的原因。

    k-means approximates the data by \(K\) points (zero-dimensional), PCA by one \(q\)-dimensional plane, local PCA by \(K\) small \(q\)-dimensional planes; the GMM and probabilistic PCA are the probabilistic versions of the first two. All of them minimize some squared reconstruction error (or maximize a Gaussian likelihood) and all of them look only at second-order statistics (means and covariances), which is why they are simple and dependable, and also why they cannot see curved structure.

    6机器人中的它:灵巧手的特征抓取In robotics: eigengrasps of a dexterous hand

    9.3 节提到过“协同”:人手的抓取姿态高度相关,少数几个主成分就能解释大部分方差(Santello、Flanders 与 Soechting,1998)。Ciocarlie 与 Allen(2009)把这件事用到机器人上:在几个主成分张成的“特征抓取”(eigengrasp)空间里搜索抓取,而不是在全部关节空间里搜索,让多指灵巧手的抓取规划快得多。下图用一只示意的 15 关节手(5 根手指,每根 3 个屈曲角)演示这个流程。数据是模拟的:80 个抓取姿态由三种“协同”(整手握拳、拇指与食指捏合、尺侧手指与桡侧手指的反向运动)随机组合再加 3° 的独立噪声生成,PCA 并不知道这一点,它要从 80 × 15 的数据里自己找出来。

    Lesson 9.3 mentioned "synergies": human grasp postures are strongly correlated, and a few principal components explain most of their variance (Santello, Flanders and Soechting, 1998). Ciocarlie and Allen (2009) carried this over to robots: search for grasps in the "eigengrasp" space spanned by a few principal components instead of the full joint space, which makes grasp planning for multi-fingered hands much faster. The figure walks through this on a schematic 15-joint hand (5 fingers, 3 flexion angles each). The data are simulated: 80 grasp postures generated as random combinations of three "synergies" (whole-hand closing, a thumb–index pinch, and the ulnar fingers moving against the radial ones) plus 3° of independent noise. PCA is not told any of this; it has to find it in the 80 × 15 data on its own.

    FIG 6特征抓取:15 个关节,2 到 3 个旋钮Eigengrasps: 15 joints, 2 or 3 knobs
    左:5 根手指的侧视图并排画出(T 拇指、I 食指、M 中指、R 无名指、L 小指),每根手指从底部的掌根出发,0° 为伸直,屈曲向右弯。“协同探索”模式下,琥珀色手是 \(\bar{\mathbf q}+\sum_i z_i\sqrt{\lambda_i}\,\mathbf v_i\),三个滑块 \(z_i\) 以各成分的标准差为单位。“重建抓取”模式下,紫色虚线是数据里的第 n 个抓取,琥珀色是只用前 q 个成分的重建。右:每个成分的解释方差(蓝色柱)和累计值(琥珀色折线),绿色虚线是 90%。 Left: side views of the 5 fingers drawn next to each other (T thumb, I index, M middle, R ring, L little), each rising from its base at the bottom, 0° meaning straight and flexion curling to the right. In "Explore synergies" mode the amber hand is \(\bar{\mathbf q}+\sum_i z_i\sqrt{\lambda_i}\,\mathbf v_i\), the three sliders \(z_i\) being in units of each component's standard deviation. In "Reconstruct a grasp" mode the dashed purple hand is grasp number n of the data and the amber hand its reconstruction from the first q components. Right: each component's explained variance (blue bars) and the running total (amber line); the green dashed line is 90%.
    • “协同探索”模式下把 \(z_1\) 推到 +1.5 以上,\(z_2,z_3\) 保持在 ±0.5 以内:五根手指一起握拢(拇指动得最少),这一个数同时驱动 15 个关节。再单独动 \(z_2\),看拇指和食指如何与无名指、小指反向运动。In "Explore synergies" push \(z_1\) above +1.5 while keeping \(z_2,z_3\) within ±0.5: all five fingers close together (the thumb least), one number driving 15 joints. Then move \(z_2\) alone and watch the thumb and index move against the ring and little fingers.
    • 切到“重建抓取”,增大 q,直到全部 80 个抓取的平均重建误差(RMS)低于 3°:需要 q = 3(约 2.7°,此时累计解释方差约 98.4%)。q = 1 时约 11.2°,q = 2 时约 4.8°;q 再大,每多一个成分只再降约 0.2°(q = 4 时 2.5°),因为剩下的主要是 3° 的独立噪声,均匀摊在其余各个方向上,再加成分只是在拟合噪声。Switch to "Reconstruct a grasp" and raise q until the mean reconstruction error (RMS) over all 80 grasps is below 3°: that takes q = 3 (about 2.7°, with about 98.4% of the variance explained). It is about 11.2° at q = 1 and about 4.8° at q = 2; each further component only shaves off about 0.2° (2.5° at q = 4), because what remains is mostly the 3° independent noise, spread evenly over all the remaining directions, so extra components merely fit noise.

    第一个成分解释约 74%,前两个约 95%,前三个约 98.4%,之后每个成分只剩约 0.2%:碎石图(scree plot)在第 3 个成分之后变平,这就是“该保留几个”的读法。注意 PCA 找到的方向只是张成同一个子空间,未必和生成数据的三种协同一一对应:主成分彼此正交,而我们设计的三种协同并不正交,所以 \(\mathbf v_1\) 是“握拳”混了一点其他成分(例如拇指几乎不参与)。

    The first component explains about 74%, the first two about 95%, the first three about 98.4%, and each later one only about 0.2%: the scree plot goes flat after the third component, which is how one reads "how many to keep". Note that the directions PCA finds only span the same subspace and need not match the three generating synergies one to one: principal components are mutually orthogonal while the synergies we designed are not, so \(\mathbf v_1\) is "closing" mixed with a little of the others (the thumb, for one, barely takes part).

    真实系统里In real systems

    点云分割:桌面场景常先用 RANSAC(11.5 节)拟合并去掉桌面,再对剩下的点做欧氏聚类,把彼此距离小于阈值的点连成一个物体(PCL 里的 EuclideanClusterExtraction),或用 DBSCAN 这类基于密度的聚类:它们不需要预先给 K,也不要求团块是圆的。每个点的法向量来自邻域的局部 PCA(1.12 节、12.1 节)。 视觉词袋与回环检测:ORB-SLAM 的回环检测(15.2 节)用 DBoW2 词袋库,其“视觉单词”是对大量特征描述子做层次化 k-means 式聚类得到的树(思路来自 Nistér 与 Stewénius 2006 的词汇树);一幅图像变成单词的直方图,就能快速检索相似的历史帧。 演示学习:Calinon 等(2007)用 GMM 拟合多次演示中的(时间,位置)数据,再用高斯混合回归(GMR)生成平滑的轨迹;把演示切成“够取、抓取、抬起”等阶段,也常从对每个时刻的特征(速度、夹爪开合、高度)做聚类开始,实际系统再加上隐马尔可夫模型之类的时间模型,避免标签逐帧乱跳。 动作的模式:Behavior Transformer(Shafiullah 等,NeurIPS 2022)先用 k-means 把演示里的连续动作聚成 K 个中心,策略预测“哪个中心”(分类)再加一个连续的偏移量,从而能表示多峰的动作分布;这与 17.5 节的动作 token 化、22.2 节的多峰策略直接相关。 手:除了 Ciocarlie 与 Allen 的特征抓取规划,“协同”的思想也启发了用少数电机驱动多关节的欠驱动手(9.3 节)。

    Point-cloud segmentation: tabletop scenes are often handled by first fitting and removing the table with RANSAC (Lesson 11.5), then clustering the remaining points by Euclidean distance, linking points closer than a threshold into one object (EuclideanClusterExtraction in PCL), or by a density-based method such as DBSCAN: neither needs K in advance or assumes round blobs. Each point's normal comes from a local PCA of its neighbourhood (Lessons 1.12 and 12.1). Visual bag of words and loop closure: ORB-SLAM's loop detection (Lesson 15.2) uses the DBoW2 library, whose "visual words" form a tree obtained by hierarchical k-means-style clustering of many feature descriptors (an idea from the vocabulary tree of Nistér and Stewénius, 2006); an image becomes a histogram of words, so similar past frames can be retrieved quickly. Learning from demonstration: Calinon et al. (2007) fit a GMM to (time, position) data from several demonstrations and generate a smooth trajectory by Gaussian mixture regression (GMR); cutting demonstrations into phases such as "reach, grasp, lift" also often starts by clustering per-time-step features (speed, gripper opening, height), with real systems adding a temporal model such as a hidden Markov model so labels do not flicker from frame to frame. Action modes: Behavior Transformers (Shafiullah et al., NeurIPS 2022) first cluster the continuous actions in the demonstrations into K centres with k-means; the policy predicts "which centre" (a classification) plus a continuous offset, which lets it represent multimodal action distributions, tying directly to the action tokenization of Lesson 17.5 and the multimodal policies of Lesson 22.2. Hands: beyond Ciocarlie and Allen's eigengrasp planning, the synergy idea also inspired underactuated hands in which a few motors drive many joints (Lesson 9.3).

    7常见误区Common pitfalls

    误区 1:不管单位就直接算距离Pitfall 1: computing distances without minding the units

    k-means 和 PCA 都建立在欧氏距离和方差上,而它们完全取决于单位。把关节角(弧度,变化约 0.3)和夹爪力(牛顿,变化约 20)放进同一个向量,力的方差是角度的四千多倍,聚类和主成分几乎只看力。先标准化(每维减均值、除以标准差),或者有意识地选择有物理意义的权重。反过来,若各维单位相同且大小本身有意义(例如都是关节角、都是像素),标准化反而会放大噪声维度。

    k-means and PCA both rest on Euclidean distance and variance, which depend entirely on units. Put a joint angle (radians, varying by about 0.3) and a gripper force (newtons, varying by about 20) into one vector and the force's variance is over four thousand times the angle's, so clustering and components look almost only at force. Standardize first (subtract the mean and divide by the standard deviation per dimension), or choose physically meaningful weights deliberately. Conversely, when all dimensions share a unit and their sizes mean something (all joint angles, all pixels), standardizing can amplify noisy dimensions instead.

    误区 2:以为 k-means 能找到任何形状的组Pitfall 2: expecting k-means to find groups of any shape

    k-means 的每个组是一个凸的 Voronoi 区域,它偏爱大小相近的圆团。长条、大小悬殊、环形的组都会被切错(FIG 2、FIG 5),而且这不是优化失败,是目标函数本身就偏爱错的答案。按数据形状选方法:椭圆形用 GMM,任意形状且密度均匀用 DBSCAN 一类的密度方法,弯曲流形用谱聚类或先学特征。

    Each k-means group is a convex Voronoi region, and it favours round blobs of similar size. Elongated, unequal or ring-shaped groups are split wrongly (FIG 2, FIG 5), and this is not an optimization failure: the objective itself prefers the wrong answer. Match the method to the shape: a GMM for ellipses, a density method like DBSCAN for arbitrary shapes of even density, spectral clustering or learned features for curved manifolds.

    误区 3:只跑一次,或者用 J 选 KPitfall 3: running once, or choosing K by J

    一次 Lloyd 的结果取决于起点:FIG 3 里即便用 k-means++,也有四成的运行停在局部极小。总是用 k-means++ 并重启多次(scikit-learn 的 KMeans 就有 n_init 参数),取 \(J\) 最小的那次。但不要用 \(J\) 比较不同的 K:K 越大 \(J\) 一定越小。用肘部、BIC、轮廓系数,或者最好是下游任务的效果来选。

    One Lloyd run depends on its start: in FIG 3 even k-means++ stops in a local minimum four times in ten. Always use k-means++ with several restarts (scikit-learn's KMeans has an n_init parameter for this) and keep the run with the smallest \(J\). But never compare different K by \(J\): a larger K always gives a smaller \(J\). Use the elbow, the BIC, silhouette scores, or best of all the performance of the downstream task.

    误区 4:GMM 的塌缩与过多参数Pitfall 4: GMM collapse and too many parameters

    最大似然下,一个高斯可以缩到一个点上让似然无穷大(第 5 节),在重复的数据点(例如机器人静止时的多帧相同读数)上特别容易发生。给协方差加下限或先验,必要时用对角协方差或所有组共享协方差。\(D\) 维全协方差每组有 \(D(D+1)/2\) 个参数,维数一高,数据量很快不够,常先用 PCA 降维再拟合 GMM。

    Under maximum likelihood a Gaussian can shrink onto one point and make the likelihood infinite (Section 5); this happens especially easily on duplicated data (many identical readings while the robot stands still). Put a floor or a prior on the covariances, and if needed use diagonal or shared covariances. A full \(D\)-dimensional covariance has \(D(D+1)/2\) parameters per group, so as the dimension grows the data quickly run short; PCA first, then a GMM, is a common recipe.

    误区 5:误读主成分Pitfall 5: misreading principal components

    (a) 忘记中心化,第一主成分会指向均值(FIG 4)。 (b) 特征向量的符号和顺序是任意的:\(-\mathbf v\) 同样是特征向量,特征值相近时顺序和方向都不稳定(FIG 4 的“各向同性”),不同数据集算出的主成分不能直接逐个对比。 (c) 方差大不等于重要:对任务关键的那个方向(例如决定抓取成败的手指微调)可能方差很小,被 PCA 当噪声扔掉。 (d) 角度数据要注意周期性:\(179^\circ\) 和 \(-179^\circ\) 只差 2°,却被当成相差 358°,应先展开或用 \((\cos q,\sin q)\)。 (e) 数据弯曲时,解释方差比会低估真实的低维结构(FIG 5 里一维的路径只有 70%)。

    (a) Forget to centre and the first component points at the mean (FIG 4). (b) Eigenvector signs and order are arbitrary: \(-\mathbf v\) is an eigenvector too, and when eigenvalues are close both the order and the direction are unstable (FIG 4's "isotropic"), so components from different data sets cannot be compared one by one. (c) Large variance is not importance: the direction that matters for the task (a small finger adjustment that decides whether a grasp holds, say) may have little variance and be discarded by PCA as noise. (d) Mind the periodicity of angles: \(179^\circ\) and \(-179^\circ\) are 2° apart but look 358° apart; unwrap them first or use \((\cos q,\sin q)\). (e) When the data bend, the explained variance ratio understates the true low-dimensional structure (the one-dimensional path of FIG 5 gets only 70%).

    8小练习Check yourself

    1. 关于 Lloyd 算法(k-means),下列哪一项正确?1. Which statement about Lloyd's algorithm (k-means) is true?
    两步各自精确最优:站队给每个点最近的中心,挪旗把中心放到重心(使队内距离平方和最小),所以 J 单调不增,选项 A 错。分组方式有限,且每次真正的改变严格降低 J,所以有限步停止。但这只是坐标下降的不动点:FIG 1 的“角落起点”停在 J 约为最优 4 倍的地方,所以选项 B 和 D 都错,选项 C 正确。Each step is exactly optimal: the line-up gives every point its nearest centre and the move puts every centre at its centroid (which minimizes the within-cluster sum of squares), so J never increases and option A is wrong. There are finitely many assignments and every genuine change strictly lowers J, so it stops after finitely many steps. But it is only a fixed point of coordinate descent: FIG 1's "Corner start" stops at about 4 times the optimal J, so options B and D are wrong and option C is right.
    2. 一组二维数据的协方差矩阵特征值为 9 和 1。只保留第一主成分时,解释方差比和均方重建误差分别是多少?2. A 2D data set has covariance eigenvalues 9 and 1. Keeping only the first principal component, what are the explained variance ratio and the mean squared reconstruction error?
    解释方差比 \(=\lambda_1/(\lambda_1+\lambda_2)=9/10=90\%\),按方差而不是标准差算(选项 C 错)。均方重建误差等于被丢掉的特征值之和 \(\sum_{i>q}\lambda_i=\lambda_2=1\)(选项 B 把保留和丢弃弄反了)。选项 D 的 3 是被保留的第一成分的标准差 \(\sqrt{\lambda_1}\),与误差无关。所以是选项 A。The explained variance ratio is \(\lambda_1/(\lambda_1+\lambda_2)=9/10=90\%\), computed from variances, not standard deviations (so option C is wrong). The mean squared reconstruction error is the sum of the discarded eigenvalues, \(\sum_{i>q}\lambda_i=\lambda_2=1\) (option B swaps kept and discarded). Option D's 3 is the standard deviation \(\sqrt{\lambda_1}\) of the kept component, which has nothing to do with the error. So the answer is option A.
    3. 一个 GMM 的所有组都固定为 \(\Sigma_k=\sigma^2I\)、\(\pi_k=1/K\),只学均值。让 \(\sigma\to0\),EM 变成什么?3. A GMM has all groups fixed to \(\Sigma_k=\sigma^2I\) and \(\pi_k=1/K\); only the means are learned. As \(\sigma\to0\), what does EM become?
    \(\gamma_{nk}\propto\exp(-\|\mathbf x_n-\boldsymbol\mu_k\|^2/2\sigma^2)\)。\(\sigma\to0\) 时,距离最近的那一项比其他项大得无法比较,归一化后它趋于 1、其余趋于 0:这就是 k-means 的硬站队,均值更新就是重心。责任相等(选项 B)是 \(\sigma\to\infty\) 的极限。这里方差是固定的而不是学出来的,所以不会出现塌缩导致的发散(选项 C)。所以是选项 D。\(\gamma_{nk}\propto\exp(-\|\mathbf x_n-\boldsymbol\mu_k\|^2/2\sigma^2)\). As \(\sigma\to0\) the nearest term dwarfs all others, so after normalization it tends to 1 and the rest to 0: the hard line-up of k-means, and the mean update is the centroid. Equal responsibilities (option B) is the \(\sigma\to\infty\) limit. Here the variance is fixed, not learned, so there is no collapse-driven divergence (option C). So the answer is option D.
    4. 机器人记录二维特征:腕关节角(弧度,标准差约 0.3)和夹爪力(牛顿,标准差约 20),两者弱相关。不做标准化直接 PCA,第一主成分大致指向哪里?4. A robot logs two features: a wrist angle (radians, standard deviation about 0.3) and the gripper force (newtons, standard deviation about 20), weakly correlated. Run PCA without standardizing: where does the first component roughly point?
    PCA 只看协方差矩阵的数值。力那一维的方差约 \(20^2=400\),角度约 \(0.3^2=0.09\),弱相关时最大特征向量几乎就是力轴。PCA 照样能算(选项 D 错),只是结果被单位左右;“重要”与否 PCA 并不知道(选项 C 错)。若把力换算成千牛,结论就会反过来:这正是要先标准化的原因(误区 1)。所以是选项 B。PCA only sees the numbers in the covariance matrix. The force variance is about \(20^2=400\), the angle's about \(0.3^2=0.09\), so with weak correlation the top eigenvector is almost the force axis. PCA still computes (option D is wrong), but the result is dictated by units; PCA knows nothing about "importance" (option C is wrong). Express force in kilonewtons and the conclusion flips, which is exactly why one standardizes first (Pitfall 1). So the answer is option B.
    5. 二维数据均匀分布在半径为 \(R\) 的圆周上(例如转台边缘一个标记点的轨迹)。PCA 的结果是?5. 2D data lie uniformly on a circle of radius \(R\) (say, the track of a marker on the rim of a turntable). What does PCA give?
    \(\mathbf x=R(\cos t,\sin t)\),\(t\) 均匀分布,则 \(\mathbb E[x^2]=\mathbb E[y^2]=R^2/2\),\(\mathbb E[xy]=0\),协方差是 \(\tfrac{R^2}{2}I\):任何方向都是主方向,每个方向只解释一半。PCA 只看二阶统计量,看不出“一维但弯曲”的结构,这正是 FIG 5 和 18.2 节自编码器的出发点。所以是选项 C。With \(\mathbf x=R(\cos t,\sin t)\) and \(t\) uniform, \(\mathbb E[x^2]=\mathbb E[y^2]=R^2/2\) and \(\mathbb E[xy]=0\), so the covariance is \(\tfrac{R^2}{2}I\): every direction is principal and each explains half. PCA only sees second-order statistics and cannot see "one-dimensional but curved", which is the starting point of FIG 5 and of the autoencoders of Lesson 18.2. So the answer is option C.

    9延伸阅读Further reading

    • C. M. Bishop, Pattern Recognition and Machine Learning, Springer, 2006, Ch. 9 and 12 — k-means、GMM 与 EM,PCA 与概率 PCA 的标准教材讲法the standard textbook treatment of k-means, GMMs and EM, PCA and probabilistic PCA
    • S. P. Lloyd, Least Squares Quantization in PCM, IEEE Transactions on Information Theory, 1982 (Bell Labs memo of 1957) — “站队、挪旗”算法的出处the origin of the line-up-and-move algorithm
    • D. Arthur & S. Vassilvitskii, k-means++: The Advantages of Careful Seeding, SODA 2007 — \(D^2\) 抽样与 \(O(\log K)\) 的保证\(D^2\) sampling and its \(O(\log K)\) guarantee
    • A. P. Dempster, N. M. Laird & D. B. Rubin, Maximum Likelihood from Incomplete Data via the EM Algorithm, Journal of the Royal Statistical Society B, 1977 — EM 算法的经典论文the classic EM paper
    • K. Pearson, On Lines and Planes of Closest Fit to Systems of Points in Space, Philosophical Magazine, 1901; H. Hotelling, Analysis of a Complex of Statistical Variables into Principal Components, Journal of Educational Psychology, 1933 — PCA 的两个源头:最小误差与最大方差the two origins of PCA: minimum error and maximum variance
    • M. E. Tipping & C. M. Bishop, Probabilistic Principal Component Analysis, Journal of the Royal Statistical Society B, 1999 — PCA 作为线性高斯隐变量模型PCA as a linear-Gaussian latent-variable model
    • B. Schölkopf, A. Smola & K.-R. Müller, Nonlinear Component Analysis as a Kernel Eigenvalue Problem, Neural Computation, 1998 — 核 PCAkernel PCA
    • M. Santello, M. Flanders & J. F. Soechting, Postural Hand Synergies for Tool Use, Journal of Neuroscience, 1998 — 人手姿态的低维协同low-dimensional synergies of human hand postures
    • M. T. Ciocarlie & P. K. Allen, Hand Posture Subspaces for Dexterous Robotic Grasping, International Journal of Robotics Research, 2009 — 在特征抓取空间里规划机器人抓取planning robot grasps in eigengrasp space
    • S. Calinon, F. Guenter & A. Billard, On Learning, Representing, and Generalizing a Task in a Humanoid Robot, IEEE Transactions on Systems, Man, and Cybernetics B, 2007 — 用 GMM/GMR 表示演示representing demonstrations with GMM/GMR
    • N. M. Shafiullah, Z. J. Cui, A. Altanzaya & L. Pinto, Behavior Transformers: Cloning k Modes with One Stone, NeurIPS 2022 — 用 k-means 的动作中心加偏移表示多峰动作k-means action centres plus offsets for multimodal actions