BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Linear algebra4 of 16 in topic

27. 根据奇异值计算矩阵的数值秩

EasyLinear algebra

浮点数使得精确秩变得毫无意义:由数据构建的秩为 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),这仅仅是舍入噪声。数值秩仅统计相对于最大奇异值而言足够大的奇异值。

Worked example

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 实际跨越的方向数量。
主题
Linear algebra
相似题目
  • 为一组 embedding 构建余弦相似度矩阵Easy
  • 衡量 rank-k 近似在 SVD 下的损失Easy
  • 将向量投影到少量基向量的张成空间上Easy
  • 根据奇异值计算矩阵的 2-norm condition numberEasy
所有 Linear algebra 道题目
反馈
27 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def numerical_rank(X, rtol=1e-10):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 4 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS