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

5. 使用 np.unique 将稀疏 token ids 映射到紧凑的词表

EasyNumPy foundations

重要性 在推荐系统和经典的 NLP 流水线中,id 重新映射可以保持 embedding tables 和 one-hot 特征的紧凑性。

当你在一个小数据集上训练 embedding table 时,如果使用的 ids 仅占巨大范围中的一小部分,你需要将它们重新映射到 0..k-1,以保持 table 的规模较小。

为 1D int array 编写 compact_ids(ids)。返回一个元组 (vocab, new_ids, counts):vocab 是排序后的不同 ids 数组,new_ids 的长度与 ids 相同且 new_ids[i] 是 ids[i] 在 vocab 中的位置,counts[j] 是 vocab[j] 出现的次数。

函数def compact_ids(ids)

示例 1

输入: compact_ids([50, 7, 50, 900])

输出: vocab [7, 50, 900], new_ids [1, 0, 1, 2], counts [1, 2, 1]

示例 2

输入: ids = [3, 3, 3, 10, 2, 10]

输出: ([2, 3, 10], [1, 1, 1, 2, 0, 2], [1, 3, 2])

示例 3

输入: ids = [42]

输出: ([42], [0], [1])

约束条件

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

np.unique(ids, return_inverse=True, return_counts=True) 可以通过一次调用返回所有这三个值。

提示 2

np.unique 可以返回额外的数组。

提示 3

你需要的是逆向映射 (inverse mapping),而不是第一个索引 (first index)。

提示 4

使用 return_inverse=True, return_counts=True。

常见错误
  • 混淆了 return_index 和 return_inverse。
  • 在循环中构建 Python dict,这在处理数百万个 ids 时非常慢。
理解思路

np.unique 会对数组进行排序并保留每个值的唯一副本。通过设置标志位,它还可以返回:
return_index: 每个唯一值在输入中首次出现的位置。
return_inverse: 对于每个输入元素,它对应哪一个唯一值。
return_counts: 每个唯一值出现的次数。

Worked example

ids [50, 7, 50, 900]。排序后的唯一值: [7, 50, 900]。第一个 50 在 vocab 中的位置是 1,7 是 0,第二个 50 是 1,900 是 2,因此 new_ids = [1, 0, 1, 2]。Counts 是 [1, 2, 1]。return_index 将会是 [1, 0, 3],这并不是一种重新映射。

vocab[new_ids] == ids,且 sum(counts) == len(ids)。

推荐系统通过这种方式压缩用户和 item ids,而经典 NLP 则利用它从 token arrays 构建词表和频率表。

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

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

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