Turn categorical tokens into a fixed-size vector with the hashing trick

With millions of possible user agents or URLs, a vocabulary does not fit. The hashing trick maps each token straight to a bucket.

Write hash_features(tokens, n_buckets). Use this deterministic hash: h = sum of (i + 1) * ord(ch) over the characters of the token, with i the character position. Bucket = h % n_buckets. A sign bit avoids systematic collisions: sign = +1 if (h // n_buckets) is even, otherwise -1. Return a float array of length n_buckets with the signed counts summed.

Signaturedef hash_features(tokens, n_buckets)

Example

hash_features(["a"], 10) puts -1 in bucket 7: ord('a') = 97, 97 % 10 = 7, and 97 // 10 = 9 is odd, so the sign is -1.

Understand the idea

When there are millions of possible tokens, such as URLs or user agents, keeping a vocabulary is too costly. The hashing trick sends each token straight to one of n buckets with a hash. Different tokens can collide in a bucket, so a sign bit makes collisions sometimes add and sometimes cancel, instead of always piling up. Worked example with n_buckets = 10: token 'ab' has h = 1 * 97 + 2 * 98 = 293. Bucket = 293 % 10 = 3. 293 // 10 = 29 is odd, so the sign is -1, and bucket 3 gets -1. Token 'a' has h = 97, bucket 7, and 97 // 10 = 9 is odd, so following the rule it also gets -1. Rule: 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. Used in large-scale ad click and spam models where vocabularies do not fit in memory.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplehash_features(['a'], 10)
  • Sample 2: repeats add uphash_features(['cat', 'cat', 'dog'], 8)
  • Test 3: signed collisionshash_features(['ab', 'ba', 'zz', 'q'], 5)