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

24. 为一组 embedding 构建余弦相似度矩阵

EasyLinear algebra

Embedding 搜索通过余弦相似度对文档进行排序:即两个向量的点积除以两者的长度。它忽略向量长度,只保留方向信息。

编写 cosine_matrix(X),其中 X 的形状为 (n, d)。返回一个 (n, n) 的矩阵,其中 [i, j] 是第 i 行和第 j 行的余弦相似度。

全零行没有方向:将其与任何内容的相似度均视为 0。

函数def cosine_matrix(X)
Play with it

Dot product and cosine similarity

Drag either arrow. Cosine similarity ignores length and only measures the angle; the dot product grows with both.

-202-4-2024ab
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,两行的点积就是它们的余弦值,因此一次矩阵乘法即可得到完整的表格。

Worked example

行 [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 检索使用此方法对文档进行排序。
主题
Linear algebra
相似题目
  • 衡量 rank-k 近似在 SVD 下的损失Easy
  • 将向量投影到少量基向量的张成空间上Easy
  • 根据奇异值计算矩阵的数值秩Easy
  • 根据奇异值计算矩阵的 2-norm condition numberEasy
所有 Linear algebra 道题目
反馈
24 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def cosine_matrix(X):
# your code here
pass
​

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

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