Sub topic 4
Adding Items and Estimating Counts with the Row Minimum
What this chapter assumes
You have read the previous chapters. You know the sketch is a table of d rows and w columns of counters, and that each row has its own hash function that maps an item to one column. You are comfortable with Python and with the idea that two different items can hash to the same column (a collision).
This chapter covers the two operations a count-min sketch supports: update (record that an item was seen) and point query (estimate how many times an item was seen). Why the estimate is never too low, how large the error can be, and how to pick w and d are covered in the next chapters.
The two operations at a glance
| Operation | What it does | Rows touched | Changes the table? |
|---|---|---|---|
| `add(item, count)` | Adds `count` to one counter in every row | all `d` | yes |
| `estimate(item)` | Reads one counter in every row and returns the smallest | all `d` | no |
Both operations use the same first step. For each row r, apply that row's hash function to the item to get a column h_r(item). The pair (r, h_r(item)) identifies one counter. An item therefore "owns" exactly d counters, one per row, but it does not own them exclusively. Other items hashed to the same column share the counter.
Update: one increment per row
To add an item, compute its column in each row and increase that counter by the count (usually 1).
- For row 0, compute
h_0(item)and addcounttotable[0][h_0(item)]. - Repeat for rows 1 to
d - 1. - Add
countto a separate running totalN, which tracks the stream length.
The update never reads or compares counters. It does not matter whether a counter already holds contributions from other items. Everything that hashes to a column is added into the same cell, and the sketch never records which items contributed.
Query: the minimum across rows
To estimate an item, compute its column in each row, read those d counters, and return the smallest.
Each counter holds the item's true count plus the counts of every other item that collided with it in that row. Each counter is therefore an overestimate, possibly an exact one. A row where the item collided with nothing heavy gives a tight value, and a row where it collided with a frequent item gives a loose one. Taking the minimum selects the row with the least contamination.
A worked trace
Use a tiny sketch with w = 5 columns and d = 3 rows. Suppose the three hash functions map the items as follows. These columns are chosen by hand for the example.
| Item | Row 0 column | Row 1 column | Row 2 column |
|---|---|---|---|
| a | 1 | 4 | 0 |
| b | 1 | 2 | 3 |
| c | 0 | 4 | 3 |
| d | 1 | 4 | 3 |
The stream is a, b, a, c. After processing it, the table is:
| Row | col 0 | col 1 | col 2 | col 3 | col 4 |
|---|---|---|---|---|---|
| 0 | 1 | 3 | 0 | 0 | 0 |
| 1 | 0 | 0 | 1 | 0 | 3 |
| 2 | 2 | 0 | 0 | 2 | 0 |
Row 0, column 1 holds 3 because a (twice) and b (once) both hash there. Row 1, column 4 holds 3 because a (twice) and c (once) share it.
Now query each item:
| Item | Row 0 value | Row 1 value | Row 2 value | Minimum | True count |
|---|---|---|---|---|---|
| a | 3 | 3 | 2 | 2 | 2 |
| b | 3 | 1 | 2 | 1 | 1 |
| c | 1 | 3 | 2 | 1 | 1 |
| d (never seen) | 3 | 3 | 2 | 2 | 0 |
For a, rows 0 and 1 are inflated by collisions, but row 2 is clean, so the minimum is exact. The same happens for b and c. The last row shows a limit: d never appeared, yet every one of its counters was touched by some other item, so the sketch reports 2. The estimate can be wrong, and it is wrong in the upward direction only.
The implementation
This is the full class. The hash for row r has the form ((a*x + b) mod p) mod w, where a and b are random per row and p is a large prime. The _cols helper is the shared first step of both operations.
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)))add pairs each row with that row's column and increments the counter. estimate uses the same pairing but reads instead of writing, and wraps the reads in min. Because both go through _cols, an item always lands on the same counters.
Now feed it 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)The table has ceil(e / 0.01) = 272 columns and ceil(ln 100) = 5 rows. With only three distinct items in 272 columns, collisions are rare, so the estimates will usually equal the true counts. The assert holds on every run.
Edge cases and gotchas
Unseen items can get a nonzero estimate
The d row in the trace showed this. An empty sketch returns 0 for everything, but as the table fills, an unseen item can get a positive estimate. If all d of its counters collide with other items, the minimum is above zero. A sketch cannot tell you "this item definitely appeared." It can only tell you "this item appeared at most this many times," and a small estimate is the strongest statement it can make about absence. A 0 is reliable proof that the item never appeared, because a counter can only be 0 if nothing was added to it.
Python's `hash()` is only stable within one process
String hashing in Python is randomized per process by default. Within one run, add and estimate agree, which is all the examples above need. If you save a sketch to disk, or build sketches in separate processes and want to merge them, replace hash(item) with a stable hash such as one derived from hashlib. Otherwise the same item lands in different columns in different processes, and the counters become meaningless.
The item must be hashable
hash() raises TypeError for lists and dicts. Convert such items to tuples or strings first.
Counts other than 1
add(item, 5) is equivalent to five calls of add(item). This is useful for batching, for example when you have already aggregated counts locally. Keep counts non-negative for now. With negative counts the estimate can fall below the true count, which breaks the property the next chapter relies on. Deletions are handled in a later chapter.
Queries do not change the table
estimate is read-only, so you can call it as often as you like, including between updates, without affecting later results.
The minimum is the right choice, not the average
The counters differ only by how much extra weight other items added, and extra weight is never negative. The smallest counter is therefore the closest to the truth. An average would blend in the contaminated rows and be less accurate. A later chapter discusses the median, which matters only when deletions are allowed.
Cost
Both operations compute d hashes and touch d counters. The time per operation is O(d), independent of the number of distinct items and of the stream length. Memory is w * d counters plus the d hash parameter pairs, also independent of the stream. Because d = ceil(ln(1/δ)) grows slowly, d is usually a small number such as 5 to 10, so each operation is only a handful of array accesses.
Exercises
Exercise
Using the table from the worked trace (rows [1,3,0,0,0], [0,0,1,0,3], [2,0,0,2,0]) and the column mapping given there, add one more occurrence of item c, then estimate c and d. What do you get?
Show answer
Item c maps to row 0 col 0, row 1 col 4, row 2 col 3, so those counters become 2, 4 and 3. The estimate for c is min(2, 4, 3) = 2, which equals its true count of 2. Item d maps to row 0 col 1, row 1 col 4, row 2 col 3. Its counters are 3, 4 and 3, so the estimate for d is 3, while its true count is still 0. The extra occurrence of c raised two of d's counters, because d shares row 1 col 4 and row 2 col 3 with c.
Exercise
Why does a query return the minimum of the d counters rather than their average, and what does a returned value of 0 tell you for certain?
Show answer
Each counter equals the item's true count plus nonnegative collision weight from other items, so every counter is at least the true count and the smallest one has the least extra weight. An average would include the more contaminated rows and be less accurate. A returned 0 means at least one of the item's counters is 0, so nothing was ever added to it, which proves the item never appeared (assuming all counts added were non-negative).