26. 将向量投影到少量基向量的张成空间上
从 embedding 中移除某个方向,或者仅保留前几个主成分,本质上都是一种投影。
编写 project(V, B)。V 的形状为 (n, d),表示待投影的向量。B 的形状为 (k, d),表示线性无关但未必是正交归一的基向量。使用 P = B.T (B B.T)^-1 B,返回 V 的每一行在 span(B) 上的 (n, d) 投影。
def project(V, B)Projecting a onto b
The projection is (a·b / b·b) b. The dashed line is the residual, which is always perpendicular to b.
- a · b
- 5
- |a|, |b|
- 2.915, 2.55
- cosine similarity
- 0.6727
- angle
- 47.7°
- projection of a on b
- (1.92, 0.38)
示例 1
输入: V = [[3, 4]], B = [[1, 0]]
输出: [[3, 0]]
示例 2
输入: V = [[1, 2, 3]], B = [[2, 0, 0], [1, 1, 0]]
输出: [[1.0, 2.0, 0.0]]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
Because the basis vectors are not orthonormal, you cannot just take dot products with them: you need to solve a small linear system for the coefficients.
提示 2
For all vectors at once, solve (B @ B.T) C = B @ V.T with np.linalg.solve, then map the coefficients back into d dimensions using B.
提示 3
The solve returns C with shape (k, n), so transpose it before multiplying: C.T @ B gives the (n, d) projections.
常见错误
- 有 Bug 的版本假设基是正交归一的,因此对于缩放或倾斜的基会得到错误的长度。
理解思路
将向量投影到子空间中是为了找到该向量在该子空间中的最近点,就像木棒在地面上投下的影子一样。如果基向量不是单位长度或不是相互垂直的,你不能直接计算它们与向量的点积;你必须解一个 k by k 的小方程组,以修正它们的长度和重叠部分。
V = [[3, 1]], B = [[1, 1]]. B B^T = 2, B v = 3 + 1 = 4, 所以系数是 4 / 2 = 2,投影为 2 * [1, 1] = [2, 2]。剩余部分 [1, -1] 与 B 垂直,符合预期。对于缩放后的基 B = [[2, 0]] 和 V = [[2, 3]]: B B^T = 4, B v = 4, 系数为 1, 投影为 [2, 0]。
P = B^T (B B^T)^-1 B,且每一行投影为 P v;在实践中,应解 (B B^T) c = B v 而不是直接构造逆矩阵。假设基是正交归一的会导致在基向量经过缩放或倾斜时得到错误的长度。该技术常用于从 embedding 中移除偏差方向以及在 PCA 中使用。