Sub topic 4
Adding items and estimating counts with the row minimum
This chapter assumes you know basic Python, hash tables, and the idea of a hash collision. It builds on the sketch structure from the previous chapter: a table of d rows and w columns of counters, with one hash function per row.
Adding an item
To add an item, hash it once per row. Each hash gives a column index. Then add the count to the counter at that column in that row.
An update touches exactly d counters, one per row. The cost does not depend on how many distinct items the sketch has seen.
Estimating a count
To estimate an item's count, compute the same d column indexes and read the d counters. Return the smallest of them.
Each counter holds the item's true count plus the counts of any other items that hashed to the same cell. Collisions only add to a counter, so every counter is at least the true count. The smallest counter is the one least damaged by collisions, so it is the best estimate.
A worked example
Take a sketch with 3 rows and 5 columns. Suppose "apple" hashes to columns 1, 4, and 2 in rows 0, 1, and 2. We add "apple" three times. Then we add "pear" once, and "pear" happens to collide with "apple" in row 0 only (both land in column 1).
| Row | Column for "apple" | Counter value |
|---|---|---|
| 0 | 1 | 4 (3 apple + 1 pear) |
| 1 | 4 | 3 |
| 2 | 2 | 3 |
The estimate for "apple" is min(4, 3, 3) = 3, which is correct. Row 0 overcounts, but the other rows hide the error. This works because an item is unlikely to collide with other items in every row.
Implementation
This is the core class. It sizes itself from epsilon and delta. The next chapters explain those formulas.
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
def add(self, item, count=1):
for row, col in zip(self.table, self._cols(item)):
row[col] += count
self.total += count
def estimate(self, item):
return min(row[col] for row, col in zip(self.table, self._cols(item)))Each row uses a hash of the form ((a*x + b) mod p) mod w, with its own random a and b. The generator _cols yields one column per row, and both add and estimate pair those columns with the table rows.
Now feed in a small stream:
cms = CountMinSketch(epsilon=0.01, delta=0.01)
for _ in range(1000):
cms.add("apple")
for _ in range(50):
cms.add("banana")
cms.add("cherry")
print(cms.w, cms.d) # table dimensions: 272 columns, 5 rows
for word, true_count in [("apple", 1000), ("banana", 50), ("cherry", 1)]:
est = cms.estimate(word)
assert est >= true_count # never an undercount
print(word, true_count, est)With only three distinct items in 272 columns, collisions are rare, so the estimates will usually equal the true counts. The assertion holds in every case, not just by luck.
Common errors
- Using the same hash parameters for every row. The rows would collide in the same places, and the minimum would give no benefit.
- Returning the sum or average of the counters instead of the minimum. Both include collision noise from every row.
- Reading the estimate as exact. It is an upper bound on the true count, never a lower bound.
Exercise
A sketch has 4 rows. Item "x" has a true count of 10. Its four counters read 10, 17, 12, and 25. What does the sketch return, and could the true count be lower than that value?
Show answer
It returns min(10, 17, 12, 25) = 10. The true count cannot be lower, because every counter is at least the true count. Collisions only add to counters, so the minimum is an upper bound on the true count.