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

11. 在填充的 batch 中仅对真实 token 求平均

MediumNumPy foundations

句子 batch 会被填充到相同的长度。当你通过对 token vectors 求平均来获取句子向量时,padding 不能被计入。

编写 masked_mean(x, mask),其中 x 的 shape 为 (batch, seq, d),mask 的 shape 为 (batch, seq),其中 1 表示真实 token,0 表示 padding。返回 shape 为 (batch, d):仅对真实 token 求平均。

如果某一行没有真实 token,请为该行返回零,而不是除以零。

函数def masked_mean(x, mask)

示例 1

输入: masked_mean([[[1.0, 2.0], [3.0, 4.0], [9.0, 9.0]]], [[1, 1, 0]])

输出: [[2.0, 3.0]]

约束条件

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

Padding should add nothing to the sum and nothing to the count, so zero it out before summing and count only the real tokens.

提示 2

Multiply x by the mask so padded vectors become zero, sum over the sequence axis, then divide by the number of real tokens in each row.

提示 3

The mask is (batch, seq) but x is (batch, seq, d), so broadcast it with mask[:, :, None]. Use np.maximum(count, 1) with keepdims=True on the count so empty rows give zeros instead of dividing by zero.

理解思路

一个 batch 中的句子长度不同,因此短句子会用 filler tokens 进行填充。当你通过对 token vectors 求平均来获取句子向量时,padding 不能被计入,否则平均值会被无效数据拉偏。可以将其类比为仅对到校的学生计算考试成绩平均分。将 x 乘以 mask(增加最后一个维度以便进行 broadcast),在 sequence 轴上求和,然后除以真实 token 的数量。Worked example, d = 1: 一行包含 tokens [2], [4], [100] 且 mask 为 [1, 1, 0]。Masked sum 为 2 + 4 = 6,count 为 2,mean 为 3。朴素的 mean 会得到 106 / 3 = 35.3。对于 mask 全为零的行,count 为 0;将 count clip 到至少为 1,这样结果就是 0 而不是 nan。

每行 mean = sum(x * mask) / max(sum(mask), 1)。句子 embedding 模型通常使用 masked mean pooling。
主题
NumPy foundations
相似题目
  • 将 token 序列切割为重叠的固定大小窗口Medium
  • 使用前缀和在常数时间内回答多个区间和查询Medium
  • 使用 searchsorted 和计数 padding 将序列分配到长度桶中Medium
  • 从二进制矩阵计算所有成对的 Jaccard 相似度Medium
所有 NumPy foundations 道题目
反馈
11 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def masked_mean(x, mask):
# your code here
pass
​
masked_mean(_x, _m)[0]

此用例使用生成数据,因此按原样运行。按 + 添加你自己的用例。

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

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