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

8. 使用 broadcasting 为 score matrix 添加 per-query 和 per-document bias

EasyNumPy foundations

重要性 Matrix factorization 中的 bias terms、attention score biases 以及 retrieval score calibration 都是 broadcast additions。

Retrieval 和 recommendation 模型通常将 pair 的得分计算为 dot product 加上 query bias 和 document bias。Broadcasting 可以沿着正确的 axis 添加这两个 bias vector,而无需构建任何 loops 或 tiled copies。

编写 biased_scores(S, q_bias, d_bias)。S 的 shape 为 (Q, D),q_bias shape 为 (Q,),d_bias shape 为 (D,)。返回 S[i, j] + q_bias[i] + d_bias[j] 形式的 (Q, D) float array。

函数def biased_scores(S, q_bias, d_bias)

示例 1

输入: S = [[0, 0], [1, 1]], q_bias [10, 20], d_bias [1, 2]

输出: [[11, 12], [22, 23]]

示例 2

输入: S = np.eye(3), q_bias = [1, 2, 3], d_bias = [100, 200, 300]

输出: [[102.0, 201.0, 301.0], [102.0, 203.0, 302.0], [103.0, 203.0, 304.0]]

示例 3

输入: S = np.zeros((2, 3)), q_bias = [1, -1], d_bias = [0.5, 0.0, -0.5]

输出: [[1.5, 1.0, 0.5], [-0.5, -1.0, -1.5]]

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
提示 1

将 q_bias reshape 为 (Q, 1),将 d_bias reshape 为 (1, D),以便它们能沿着行和列进行 broadcast。

提示 2

每个 bias 必须与 S 的一个 axis 对齐。

提示 3

添加一个长度为 1 的 axis 来指定 vector 遵循哪个 axis。

提示 4

q[:, None] 用于行,d[None, :] 用于列。

常见错误
  • 直接添加 (Q,) vector,这会使其与最后一个 axis(列)对齐。
  • 仅测试 square shapes,在这种情况下错误的 axis 不会抛出错误。
理解思路

Broadcasting 通过拉伸长度为 1 的 axis,让不同 shape 的 arrays 进行组合。Shape 从右侧开始比较;如果两个 axis 相等或其中一个是 1,则它们匹配。一个普通的 (Q,) vector 会与最后一个 axis 对齐,因此要沿着行(rows)添加它,必须将其变为 (Q, 1)。

Worked example

S = [[0, 0], [1, 1]], q = [10, 20] 作为一列, d = [1, 2] 作为一行。Row 0: 0 + 10 + 1 = 11 且 0 + 10 + 2 = 12。Row 1: 1 + 20 + 1 = 22 且 1 + 20 + 2 = 23。

out[i, j] = S[i, j] + q[i] + d[j], 写法为 S + q[:, None] + d[None, :]

Shapes: (Q, D) + (Q, 1) + (1, D) -> (Q, D).

Matrix factorization recommenders、attention bias masks 和 pairwise score tables 都是利用这一点构建的。

Shape 与数据流
S (Q, D) + q (Q, 1) + d (1, D) -> (Q, D)
主题
NumPy foundations
相似题目
  • 不使用 Python 循环计算所有成对距离Easy
  • 使用 fancy indexing 进行类别标签的 one-hot 编码Easy
  • 对排行榜分数进行排名,使并列分数共享名次Easy
  • 使用 argsort 的逆排列撤销长度排序Easy
所有 NumPy foundations 道题目
反馈
8 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def biased_scores(S, q_bias, d_bias):
# your code here
pass
​

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

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