高级算法 (Fall 2024)/Hashing and Sketching: Difference between revisions
Line 185: | Line 185: | ||
</math> | </math> | ||
This family of hash functions does not exactly meet the requirement of 2-universal family. However, Dietzfelbinger ''et al'' proved that <math>\mathcal{H}</math> is close to a 2-universal family. Specifically, for any input values <math>x_1,x_2\in[2^u]</math>, for a uniformly random <math>h\in\mathcal{H}</math>, | This family of hash functions does not exactly meet the requirement of 2-universal family. However, Dietzfelbinger ''et al'' proved that <math>\mathcal{H}</math> is close to a 2-universal family. Specifically, for any distinct input values <math>x_1,x_2\in[2^u]</math>, for a uniformly random <math>h\in\mathcal{H}</math>, | ||
:<math> | :<math> | ||
\Pr[h(x_1)=h(x_2)]\le\frac{1}{2^{v-1}}. | \Pr[h(x_1)=h(x_2)]\le\frac{1}{2^{v-1}}. |
Latest revision as of 12:21, 2 October 2024
Balls into Bins
The following is the so-called balls into bins model.
Consider throwing
We are concerned with the following three questions regarding the balls into bins model:
- birthday problem: the probability that every bin contains at most one ball (the mapping is 1-1);
- coupon collector problem: the probability that every bin contains at least one ball (the mapping is on-to);
- occupancy problem: the maximum load of bins.
Birthday Problem
We now consider the birthday problem.
There are
Due to the pigeonhole principle, it is obvious that for
We can model this problem as a balls-into-bins problem.
: there is no bin with more than one balls (i.e. no two students share birthday).
We first analyze this by counting. There are totally
Thus the probability is given by:
Recall that
There is also a more "probabilistic" argument for the above equation. Consider again that
The first student has a birthday for sure. The probability that the second student has a different birthday from the first student is
which is the same as what we got by the counting argument.

There are several ways of analyzing this formular. Here is a convenient one: Due to Taylor's expansion,
The quality of this approximation is shown in the Figure.
Therefore, for
Universal Hashing
Hashing is one of the oldest tools in Computer Science. Knuth's memorandum in 1963 on analysis of hash tables is now considered to be the birth of the area of analysis of algorithms.
- Knuth. Notes on "open" addressing, July 22 1963. Unpublished memorandum.
The idea of hashing is simple: an unknown set
This idea seems clever: we use a consistent mapping to deal with an arbitrary unknown data set. However, there is a fundamental flaw for hashing.
- For sufficiently large universe (
), for any function, there exists a bad data set , such that all items in are mapped to the same entry in the table.
A simple use of pigeonhole principle can prove the above statement.
To overcome this situation, randomization is introduced into hashing. We assume that the hash function is a random mapping from
Simple Uniform Hash Assumption (SUHA or UHA, a.k.a. the random oracle model):
- A uniform random function
is available and the computation of is efficient.
Families of universal hash functions
The assumption of completely random function simplifies the analysis. However, in practice, truly uniform random hash function is extremely expensive to compute and store. Thus, this simple assumption can hardly represent the reality.
There are two approaches for implementing practical hash functions. One is to use ad hoc implementations and wish they may work. The other approach is to construct class of hash functions which are efficient to compute and store but with weaker randomness guarantees, and then analyze the applications of hash functions based on this weaker assumption of randomness.
This route was took by Carter and Wegman in 1977 while they introduced universal families of hash functions.
Definition (universal hash families) - Let
be a universe with . A family of hash functions from to is said to be -universal if, for any distinct items and for a hash function chosen uniformly at random from , we have
- A family of hash functions
from to is said to be strongly -universal if, for any distinct items , any values , and for a hash function chosen uniformly at random from , we have
- Let
In particular, for a 2-universal family
For a strongly 2-universal family
This behavior is exactly the same as uniform random hash functions on any distinct pair of inputs. For this reason, a strongly 2-universal hash family are also called pairwise independent hash functions.
2-universal hash families
The construction of pairwise independent random variables via modulo a prime introduced in Section 1 already provides a way of constructing a strongly 2-universal hash family.
Let
and the family is
Lemma is strongly 2-universal.
Proof. In Section 1, we have proved the pairwise independence of the sequence of , for , which directly implies that is strongly 2-universal.
- The original construction of Carter-Wegman
What if we want to have hash functions from
Suppose that the universe is
and the family
Note that unlike the first construction, now
Lemma (Carter-Wegman) is 2-universal.
Proof. Due to the definition of , there are many different hash functions in , because each hash function in corresponds to a pair of and . We only need to count for any particular pair of that , the number of hash functions that .We first note that for any
, . This is because would imply that , which can never happen since and (note that for an ). Therefore, we can assume that and for .By linear algebra (over finite field), for any
that , for any that , there is exact one solution to satisfying:After modulo
, every has at most many that but . Therefore, for every pair of that , there exist at most pairs of and such that , which means there are at most many hash functions having for . For uniformly chosen from , for any ,We prove that
is 2-universal.
- A construction used in practice
The main issue of Carter-Wegman construction is the efficiency. The mod operation is very slow, and has been so for more than 30 years.
The following construction is due to Dietzfelbinger et al. It was published in 1997 and has been practically used in various applications of universal hashing.
The family of hash functions is from
and the family
This family of hash functions does not exactly meet the requirement of 2-universal family. However, Dietzfelbinger et al proved that
So
The function is extremely simple to compute in c language.
We exploit that C-multiplication (*) of unsigned u-bit numbers is done
h_a(x) = (a*x)>>(u-v)
The bit-wise shifting is a lot faster than modular. It explains the popularity of this scheme in practice than the original Carter-Wegman construction.
Collision number
Consider a 2-universal family
As in the balls-into-bins with full independence, we are curious about the questions such as the birthday problem or the maximum load. These questions are interesting not only because they are natural to ask in a balls-into-bins setting, but in the context of hashing, they are closely related to the performance of hash functions.
The old techniques for analyzing balls-into-bins rely too much on the independence of the choice of the bin for each ball, therefore can hardly be extended to the setting of 2-universal hash families. However, it turns out several balls-into-bins questions can somehow be answered by analyzing a very natural quantity: the number of collision pairs.
A collision pair for hashing is a pair of elements
The total number of collision pairs among the
Since
The expected number of collision pairs is
In particular, for
The above analysis gives us an estimation on the expected number of collision pairs, such that
When
Theorem - If
is chosen uniformly from a 2-universal family of hash functions mapping the universe to where , then for any set of items, where , the probability that there exits a collision pair is
- If
Recall that for mutually independent choices of bins, for some
Set Membership
A basic question in Computer Science is:
- "
"
for a set
Formally, given an arbitrary set
- space cost: size of the data structure to represent a set
of size ; - time cost: time complexity of answering each query by accessing to the data structure.
Suppose that the universe
- sorted table / balanced search tree: with space cost
bits and time cost .
Note that
Perfect hashing using quadratic space
The idea of perfect hashing is that we use a hash function
- search for
in table :
- retrieve
from a fixed location in the table; - if
return ; else return NOT_FOUND;
This scheme works as long as that the hash function satisfies the following two conditions:
- The description of
is sufficiently short, so that can be stored in one entry (or in constant many entries) of the table. has no collisions on , i.e. there is no pair of items that are mapped to the same value by .
The first condition is easy to guarantee for 2-universal hash families. As shown by Carter-Wegman construction, a 2-universal hash function can be uniquely represented by two integers
Our discussion is now focused on the second condition. We find that it relies on the perfectness of the hash function for a data set
A hash function
We have shown by the birthday problem for 2-universal hashing that when
for a table of
The construction of perfect hashing is straightforward then:
- For a set
of elements:
- uniformly choose an
from a 2-universal family ; (for Carter-Wegman's construction, it means uniformly choose two integer and for a sufficiently large prime .) - check whether
is perfect for ; - if
is NOT perfect for , start over again; otherwise, construct the table;
This is a Las Vegas randomized algorithm, which construct a perfect hashing for a fixed set
FKS perfect hashing
In the last section we see how to use
This was once seemingly impossible, until Yao's seminal paper:
- Yao. Should tables be sorted? Journal of the ACM (JACM), 1981.
Yao's paper shows a possibility of achieving linear space and constant time at the same time by exploiting the power of hashing, but assumes an unrealistically large universe.
Inspired by Yao's work, Fredman, Komlós, and Szemerédi discover the first linear-space and constant-time static dictionary in a realistic setting:
- Fredman, Komlós, and Szemerédi. Storing a sparse table with O(1) worst case access time. Journal of the ACM (JACM), 1984.
The idea of FKS hashing is to arrange hash table in two levels:
- In the first level,
items are hashed to buckets by a 2-universal hash function .
- Let
be the set of items hashed to the th bucket.
- In the second level, construct a
-size perfect hashing for each bucket .
The data structure can be stored in a table. The first few entries are reserved to store the primary hash function
It is easy to see that the search time is constant. To search for an item
- Retrieve
. - Retrieve the address for bucket
. - Search by perfect hashing within bucket
.
Each line takes constant time. So the worst-case search time is constant.
We then need to guarantee that the space is linear to
For a fixed set
Since each bucket
We will show that
Note that a bucket of
Therefore, the sum of squares of the sizes of buckets is related to collision number by:
By our analysis of the collision number, we know that for
Due to Markov's inequality,
Bloom filter
Now we consider the lossy representation of the original data set
The Bloom filter is such a lossy data structure. It is a space-efficient hash table that solves the approximate membership problem with one-sided error (false positive).
Given a set
As before, we assume the Uniform Hash Assumption (UHA):
The Bloom filter works as follows:
Bloom filter (Bloom 1970) - Suppose
are uniform and independent random hash functions.
- Data structure construction: Given a set
of size , the data structure is a Boolean array of bits constructed as- initialize all
bits of the Boolean array to 0; - for each
, let for all .
- initialize all
- Query resolution: Upon each query of an arbitrary
,- answer "yes" if
for all and "no" if otherwise.
- answer "yes" if
- Suppose
The Boolean array is our data structure, whose size is
When the answer returned by the algorithm is "no", it holds that
On the other hand, when the answer returned by the algorithm is "yes",
,
which by independence between different hash functions and by symmetry is equal to:
.
For an element
Putting everything together, for any
which is
Bloom filter solves the membership query with a small constant error of false positives using a data structure of
Distinct Elements
Consider the following problem of counting distinct elements: Suppose that
- Input: a sequence of (not necessarily distinct) elements
; - Output: an estimation of the total number of distinct elements
.
A straightforward way of solving this problem is to maintain a dictionary data structure, which costs at least linear (
Our goal is to relax the problem a little bit to significantly reduce the space cost by tolerating approximate answers. The form of approximation we consider is
-estimator- A random variable
is an -estimator of a quantity if .
is said to be an unbiased estimator of if .
- A random variable
Usually
We now present an elegant algorithm. The algorithm can be implemented in data stream model: The input elements
A famous quotation of Flajolet describes the performance of this algorithm as:
"Using only memory equivalent to 5 lines of printed text, you can estimate with a typical accuracy of 5% and in a single pass the total vocabulary of Shakespeare."
The -sketch
Suppose that we can access to an idealized random hash function
Recall that the input sequence
Proposition .
Proof. The input sequence
consisting of distinct elements are mapped to random hash values uniformly and independently distributed in . These hash values partition the unit interval into subintervals , where denotes the -th smallest value among all hash values . Clearly we have .
Meanwhile, since all hash values are uniformly and independently distributed in
, the lengths of all subintervals are identically distributed. By symmetry, they have the same expectation, thereforewhich implies that
.
The quantity
Apply the mean trick to the -sketch
The reason that the above estimator of a single hash function performs poorly is that the unbiased estimator
Suppose that we can access to
The -sketch- Suppose that
are uniform and independent random hash functions, where is a parameter to be fixed later.
- Scan the input sequence
in a single pass to compute: for every ;- average value
;
- return
as the estimator.
- Suppose that
The algorithm is easy to implement in data stream model, with a space cost of storing
Theorem - For any
, if then the output always gives an -estimator of the correct answer .
- For any
In the following we prove this main theorem for
An obstacle to analyze the estimator
,
for
.
It is then sufficient to show that
.
Lemma - The followings hold for each
, , and : ; , and consequently .
- The followings hold for each
Proof. As in the case of single hash function, by symmetry it holds that
for every . Therefore, .
Recall that each
is the minimum of random hash values uniformly and independently distributed over . By geometry probability, it holds that for any , ,
which means
. Taking the derivative with respect to , we obtain the probability density function of random variable , which is .We then compute the second moment.
.
The variance is bounded as
.
Due to the (pairwise) independence between
's, .
We resume to prove the inequality
.
When
Frequency Estimation
Suppose that
- Data: a sequence of (not necessarily distinct) elements
; - Query: an element
; - Output: an estimation
of the frequency of in input data.
We still want to give an algorithm in the data stream model: the algorithm scan the input sequence
Clearly this problem can always be solved by storing all appeared distinct elements along with their frequencies. However, the space cost of this straightforward solution is rather high. Instead, we want to use a lossy representation (a sketch) of input data which uses significantly less space but can still answer queries with tolarable accuracy.
Formally, upon each query of
.
Note that this notion of approximation is with bounded additive error which is weaker than the notion of
With such weak accuracy guarantee, its is possible to give a succinct data structure whose size is determined only by the error bounds
Count-min sketch
The count-min sketch given by Cormode and Muthukrishnan is an elegant data structure for frequency estimation.
The data structure is a two-dimensional
Count-min sketch (Cormode and Muthukrishnan 2003) - Suppose
are uniform and independent random hash functions.
- Data structure construction: Given a sequence
, the data structure is a two-dimensional integer array constructed as- initialize all entries of
to 0; - for
, upon receiving :
- for every
, evaluate and .
- for every
- initialize all entries of
- Query resolution: Upon each query of an arbitrary
,- return
.
- return
- Suppose
It is easy to see that the space cost of count-min sketch is
First, it is easy to observe that for any query
,
because the appearances of element
Therefore, for any query
where the second equation is due to the mutual independence of random hash functions
It remains to upper bound the probability
Proposition - For any
and every , it holds that .
- For any
Proof. The value of
is constituted by the frequency of and the frequencies of all other elements among , thuswhere
denotes the Boolean random variable that indicates the occurrence of event .By linearity of expectation,
.
Due to Uniform Hash Assumption (UHA),
is a uniform random function. For any , the probability of hash collision is .
Therefore,
where the last equation is due to the obvious identity
.
The above proposition shows that for any
.
Recall that
.
Combining with above equation
.
By setting
For any positive
.