27. 根据奇异值计算矩阵的数值秩
浮点数使得精确秩变得毫无意义:由数据构建的秩为 2 的矩阵会包含微小但非零的额外奇异值。
编写 numerical_rank(X, rtol=1e-10)。计算奇异值 s,并统计有多少个奇异值大于 rtol * s.max()。零矩阵的秩为 0。
def numerical_rank(X, rtol=1e-10)示例 1
输入: numerical_rank([[1, 2], [2, 4]])
输出: 1
示例 2
输入: X = np.zeros((3, 3))
输出: 0
示例 3
输入: X = np.eye(4)
输出: 4
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
Rank is the number of singular values that are clearly nonzero, measured relative to the largest one.
提示 2
Get the singular values with np.linalg.svd(X, compute_uv=False), then count how many are greater than rtol * s.max().
提示 3
Return 0 early when the matrix is empty or s.max() == 0, otherwise the threshold is 0 and comparisons misbehave; return the count as a plain int.
理解思路
在精确数学中,秩表示独立行的数量。在使用浮点数时,一个本应秩为 2 的矩阵通常会显示出一个极小的第三个奇异值(例如 5e-16),这仅仅是舍入噪声。数值秩仅统计相对于最大奇异值而言足够大的奇异值。
X = [[1, 2, 3], [2, 4, 6], [1, 0, 1]]。第 2 行是第 1 行的两倍,因此真实秩为 2。计算出的奇异值约为 [8.435, 0.918, 5.3e-16]。阈值为 1e-10 * 8.435 = 8.4e-10,因此有两个值通过,数值秩为 2。如果统计所有大于零的值,会错误地得出 3。
计算奇异值 s;rank = 大于 rtol * max(s) 的 s 的数量;零矩阵 (max 0) 的秩为 0。无论矩阵元素的大小如何,相对阈值都有效。常用于检测冗余特征、检查 LoRA 更新秩以及衡量一组 embedding 实际跨越的方向数量。