11. 在填充的 batch 中仅对真实 token 求平均
句子 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。