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

76. 使用 hashing trick 将类别 token 转换为固定大小的向量

EasyData processing and features

面对数百万种可能的 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。该技术用于词表无法放入内存的大规模广告点击和垃圾邮件模型中。
主题
Data processing and features
相似题目
  • 在不泄露测试数据的情况下标准化特征Easy
  • 使用中位数和 IQR 进行特征缩放,防止离群值主导Easy
  • 将一天中的小时和一周中的天数编码为正弦和余弦特征Easy
  • 仅使用在训练集上学习的分位数来裁剪离群值Easy
所有 Data processing and features 道题目
反馈
76 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def hash_features(tokens, n_buckets):
# your code here
pass
​

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

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