Sub topic 3
The sketch: a grid of counters with one hash per row
This chapter assumes you know basic Python, how hash tables work, and what a hash collision is. It covers the structure of a count-min sketch. The next chapter covers adding items and reading estimates.
The idea
Exact counting needs one counter for every distinct item. A count-min sketch gives up exactness to use a fixed amount of memory. Many items share each counter, so a counter can include counts from other items.
The sketch is a table of integers with d rows and w columns. All counters start at zero. Each row has its own hash function. A hash function here maps any item to a column number from 0 to w - 1.
Each item maps to exactly one counter per row, so it touches d counters in total. Two items that collide in one row will probably not collide in every row. That is the reason for having several rows.
Why the rows use different hashes
If every row used the same hash function, the rows would hold identical information. Two items that collided in one row would collide in all of them. Giving each row its own function means a collision in one row says little about the other rows.
The code below builds one hash function per row from random parameters a and b. Row i computes ((a_i * x + b_i) mod p) mod w. Here p is a large prime, and x is the item's built-in hash value reduced modulo p.
import math
import random
class CountMinSketch:
def __init__(self, epsilon, delta, seed=0):
self.w = math.ceil(math.e / epsilon)
self.d = math.ceil(math.log(1 / delta))
self.p = (1 << 61) - 1 # a Mersenne prime used for the hash family
rng = random.Random(seed)
self.params = [
(rng.randrange(1, self.p), rng.randrange(0, self.p))
for _ in range(self.d)
]
self.table = [[0] * self.w for _ in range(self.d)]
self.total = 0
def _cols(self, item):
x = hash(item) % self.p
for a, b in self.params:
yield ((a * x + b) % self.p) % self.w
cms = CountMinSketch(epsilon=0.01, delta=0.01)
cols = list(cms._cols("apple"))
print(cms.w, cms.d) # 272 5
assert len(cols) == cms.d # one column per row
assert all(0 <= c < cms.w for c in cols) # each column is inside the row
assert all(v == 0 for row in cms.table for v in row)The constructor does three things:
- It computes the table size from
epsilonanddelta. The sizing chapter explains these formulas. - It draws
dpairs(a, b)from a seeded random generator, one pair per row. - It allocates
dlists ofwzeros.
_cols yields one column index per row, in row order. zip(self.table, self._cols(item)) pairs each row with its column, and the next chapter uses that to update and read counters.
Memory is fixed
The table holds w * d counters whatever the stream looks like. With epsilon = 0.01 and delta = 0.01, that is 272 × 5 = 1,360 counters. A stream with ten million distinct items uses the same table.
The a and b values are the only other state. Together with w, d, and p, they define the hash functions. Two sketches can only be compared or merged if they share these values, which is why the constructor takes a seed.
Common mistakes
- Using one hash for all rows. The rows become copies of each other and the sketch loses its protection against collisions.
- Using
hash()across processes. Python randomizes string hashing per process. Sketches built in different processes will not line up. Use a stable hash such as one fromhashlibif sketches must be shared or saved. - Picking
wanddby guesswork. They control the error bound. Derive them fromepsilonanddelta.
Exercise
A sketch is built with epsilon = 0.001 and delta = 0.01. How many counters does the table hold, and does that number change if the stream contains 1,000 distinct items or 100 million?
Show answer
w = ceil(e / 0.001) = 2719 and d = ceil(ln(100)) = 5, so the table holds 2719 × 5 = 13,595 counters. The number does not change with the number of distinct items, because the size depends only on epsilon and delta.
Exercise
Why does each row need its own hash function instead of sharing one?
Show answer
With a shared function, two items that collide in one row would collide in every row, so the rows would add no information. Independent functions make it unlikely that two items collide in all rows, so at least one row is likely to give a less contaminated counter.