5. 使用 np.unique 将稀疏 token ids 映射到紧凑的词表
重要性 在推荐系统和经典的 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: 每个唯一值出现的次数。
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,)