76. 使用 hashing trick 将类别 token 转换为固定大小的向量
面对数百万种可能的 user agents 或 URLs,维护一个词表是不现实的。hashing trick 将每个 token 直接映射到一个桶中。
编写 hash_features(tokens, n_buckets)。使用此确定性哈希:h = token 中所有字符的 (i + 1) * ord(ch) 之和,其中 i 是字符位置。Bucket = h % n_buckets。符号位可以避免系统性碰撞:如果 (h // n_buckets) 是偶数,则 sign = +1,否则为 -1。返回一个长度为 n_buckets 的 float 数组,其中包含累加的带符号计数。
def hash_features(tokens, n_buckets)示例 1
输入: hash_features(["a"], 10) puts -1 in bucket 7: ord('a') = 97, 97 % 10 = 7, and 97 // 10 = 9
输出: odd
解析: So the sign is -1.
示例 2
输入: tokens = ['a'], n_buckets = 10
输出: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0]
示例 3
输入: tokens = ['cat', 'cat', 'dog'], n_buckets = 8
输出: [0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
Each token maps to one bucket and one sign, both derived from a single integer hash, and the output just accumulates those signed counts.
提示 2
For each token compute h as the sum of (position + 1) * ord(char), find bucket h % n_buckets and the sign from (h // n_buckets), then add the sign into that bucket of a zero array.
提示 3
Positions start at 1 in the weight, so use enumerate(t) with (i + 1) * ord(ch); the sign is +1 when (h // n_buckets) % 2 == 0, otherwise -1.
理解思路
当存在数百万个可能的 token(如 URLs 或 user agents)时,维护词表成本太高。hashing trick 通过哈希将每个 token 直接发送到 n 个桶中的一个。不同的 token 可能会在同一个桶中发生碰撞,因此引入符号位可以让碰撞有时相加,有时抵消,而不是总是堆积。Worked example with n_buckets = 10: token 'ab' 的 h = 1 * 97 + 2 * 98 = 293。Bucket = 293 % 10 = 3。293 // 10 = 29 是奇数,所以 sign 为 -1,桶 3 得到 -1。Token 'a' 的 h = 97,bucket 为 7,且 97 // 10 = 9 是奇数,按照规则它也得到 -1。
h = sum over characters of (position + 1) * ord(ch), positions starting at 0; bucket = h % n_buckets; sign = +1 if (h // n_buckets) is even, else -1; add the sign to that bucket for every token; return a float array of length n_buckets。该技术用于词表无法放入内存的大规模广告点击和垃圾邮件模型中。