24. 为一组 embedding 构建余弦相似度矩阵
Embedding 搜索通过余弦相似度对文档进行排序:即两个向量的点积除以两者的长度。它忽略向量长度,只保留方向信息。
编写 cosine_matrix(X),其中 X 的形状为 (n, d)。返回一个 (n, n) 的矩阵,其中 [i, j] 是第 i 行和第 j 行的余弦相似度。
全零行没有方向:将其与任何内容的相似度均视为 0。
def cosine_matrix(X)Dot product and cosine similarity
Drag either arrow. Cosine similarity ignores length and only measures the angle; the dot product grows with both.
- a · b
- 4
- |a|, |b|
- 2.236, 2.236
- cosine similarity
- 0.8
- angle
- 36.9°
- projection of a on b
- (0.8, 1.6)
示例 1
输入: X = [[1, 0], [0, 2], [3, 0]]
输出: [[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 1.0]]
示例 2
输入: X = [[0, 0], [1, 1]]
输出: [[0.0, 0.0], [0.0, 1]]
示例 3
输入: X = [[1.0, 2.0], [-2.0, -4.0]]
输出: [[1.0, -1.0], [-1.0, 1.0]]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 8 tests to be accepted.
提示 1
Cosine similarity is just a dot product once every vector has length 1.
提示 2
Compute each row's norm with np.linalg.norm(..., axis=1), divide each row by its norm, then the full matrix is one matrix product of the normalised rows with their transpose.
提示 3
Use keepdims=True on the norm so it broadcasts, and divide with np.divide(X, n, out=np.zeros_like(X), where=n > 0) so zero rows stay all zeros instead of becoming NaN.
理解思路
余弦相似度衡量两个向量是否指向相同方向,而不考虑它们的长短。这就像是在比较两个人的行走方向,而不是速度。相同方向的值为 1,垂直方向为 0,相反方向为 -1。一旦每一行都被缩放到长度 1,两行的点积就是它们的余弦值,因此一次矩阵乘法即可得到完整的表格。
行 [1, 0] 和 [1, 1]。长度分别为 1 和 sqrt(2) = 1.414。单位行向量为 [1, 0] 和 [0.707, 0.707]。它们的点积是 0.707。矩阵为 [[1, 0.707], [0.707, 1]]。全零行没有方向,会导致除以零,因此其相似度必须为 0。
cos(a, b) = (a . b) / (|a| |b|); 归一化行,然后计算 X_n X_n^T。语义搜索和 RAG 检索使用此方法对文档进行排序。