高级算法 (Fall 2024)/Hashing and Sketching: Difference between revisions

From TCS Wiki
Jump to navigation Jump to search
Kvrmnks (talk | contribs)
Kvrmnks (talk | contribs)
 
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 m balls into n bins uniformly and independently at random. This is equivalent to a random mapping f:[m][n]. Needless to say, random mapping is an important random model and may have many applications in Computer Science, e.g. hashing.

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 m students in the class. Assume that for each student, his/her birthday is uniformly and independently distributed over the 365 days in a years. We wonder what the probability that no two students share a birthday.

Due to the pigeonhole principle, it is obvious that for m>365, there must be two students with the same birthday. Surprisingly, for any m>57 this event occurs with more than 99% probability. This is called the birthday paradox. Despite the name, the birthday paradox is not a real paradox.

We can model this problem as a balls-into-bins problem. m different balls (students) are uniformly and independently thrown into 365 bins (days). More generally, let n be the number of bins. We ask for the probability of the following event E

  • E: 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 nm ways of assigning m balls to n bins. The number of assignments that no two balls share a bin is (nm)m!.

Thus the probability is given by:

Pr[E]=(nm)m!nm.

Recall that (nm)=n!(nm)!m!. Then

Pr[E]=(nm)m!nm=n!nm(nm)!=nnn1nn2nn(m1)n=k=1m1(1kn).

There is also a more "probabilistic" argument for the above equation. Consider again that m students are mapped to n possible birthdays uniformly at random.

The first student has a birthday for sure. The probability that the second student has a different birthday from the first student is (11n). Given that the first two students have different birthdays, the probability that the third student has a different birthday from the first two students is (12n). Continuing this on, assuming that the first k1 students all have different birthdays, the probability that the kth student has a different birthday than the first k1, is given by (1k1n). By the chain rule, the probability that all m students have different birthdays is:

Pr[E]=(11n)(12n)(1m1n)=k=1m1(1kn),

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, ek/n1k/n. Then

k=1m1(1kn)k=1m1ekn=exp(k=1m1kn)=em(m1)/2nem2/2n.

The quality of this approximation is shown in the Figure.

Therefore, for m=2nln1ϵ, the probability that Pr[E]ϵ.

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 S of n data items (or keys) are drawn from a large universe U=[N] where Nn; in order to store S in a table of M entries (slots), we assume a consistent mapping (called a hash function) from the universe U to a small range [M].

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 (N>M(n1)), for any function, there exists a bad data set S, such that all items in S 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 [N] to [M]. In order to ease the analysis, the following ideal assumption is used:

Simple Uniform Hash Assumption (SUHA or UHA, a.k.a. the random oracle model):

A uniform random function h:[N][M] is available and the computation of h 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 [N] be a universe with NM. A family of hash functions H from [N] to [M] is said to be k-universal if, for any distinct items x1,x2,,xk[N] and for a hash function h chosen uniformly at random from H, we have
Pr[h(x1)=h(x2)==h(xk)]1Mk1.
A family of hash functions H from [N] to [M] is said to be strongly k-universal if, for any distinct items x1,x2,,xk[N], any values y1,y2,,yk[M], and for a hash function h chosen uniformly at random from H, we have
Pr[h(x1)=y1h(x2)=y2h(xk)=yk]=1Mk.

In particular, for a 2-universal family H, for any distinct elements x1,x2[N], a uniform random hH has

Pr[h(x1)=h(x2)]1M.

For a strongly 2-universal family H, for any distinct elements x1,x2[N] and any values y1,y2[M], a uniform random hH has

Pr[h(x1)=y1h(x2)=y2]=1M2.

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 p be a prime. The function ha,b:[p][p] is defined by

ha,b(x)=(ax+b)modp,

and the family is

H={ha,ba,b[p]}.
Lemma
H is strongly 2-universal.
Proof.
In Section 1, we have proved the pairwise independence of the sequence of (ai+b)modp, for i=0,1,,p1, which directly implies that H is strongly 2-universal.
The original construction of Carter-Wegman

What if we want to have hash functions from [N] to [M] for non-prime N and M? Carter and Wegman developed the following method.

Suppose that the universe is [N], and the functions map [N] to [M], where NM. For some prime pN, let

ha,b(x)=((ax+b)modp)modM,

and the family

H={ha,b1ap1,b[p]}.

Note that unlike the first construction, now a0.

Lemma (Carter-Wegman)
H is 2-universal.
Proof.
Due to the definition of H, there are p(p1) many different hash functions in H, because each hash function in H corresponds to a pair of 1ap1 and b[p]. We only need to count for any particular pair of x1,x2[N] that x1x2, the number of hash functions that h(x1)=h(x2).

We first note that for any x1x2, ax1+bax2+b(modp). This is because ax1+bax2+b(modp) would imply that a(x1x2)0(modp), which can never happen since 1ap1 and x1x2 (note that x1,x2[N] for an Np). Therefore, we can assume that (ax1+b)modp=u and (ax2+b)modp=v for uv.

By linear algebra (over finite field), for any x1,x2[N] that x1x2, for any u,v[p] that uv, there is exact one solution to (a,b) satisfying:

{ax1+bu(modp)ax2+bv(modp).

After modulo M, every u[p] has at most p/M1 many v[p] that vu but vu(modM). Therefore, for every pair of x1,x2[N] that x1x2, there exist at most p(p/M1)p(p1)/M pairs of 1ap1 and b[p] such that ((ax1+b)modp)modM=((ax2+b)modp)modM, which means there are at most p(p1)/M many hash functions hH having h(x1)=h(x2) for x1x2. For h uniformly chosen from H, for any x1x2,

Pr[h(x1)=h(x2)]p(p1)/Mp(p1)=1M.

We prove that H 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 [2u] to [2v]. With a binary representation, the functions map binary strings of length u to binary strings of length v. Let

ha(x)=axmod2u2uv,

and the family

H={haa[2v] and a is odd}.

This family of hash functions does not exactly meet the requirement of 2-universal family. However, Dietzfelbinger et al proved that H is close to a 2-universal family. Specifically, for any distinct input values x1,x2[2u], for a uniformly random hH,

Pr[h(x1)=h(x2)]12v1.

So H is within an approximation ratio of 2 to being 2-universal. The proof uses the fact that odd numbers are relative prime to a power of 2.

The function is extremely simple to compute in c language. We exploit that C-multiplication (*) of unsigned u-bit numbers is done mod2u, and have a one-line C-code for computing the hash function:

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 H of hash functions from [N] to [M]. Let h be a hash function chosen uniformly from H. For a fixed set S of n distinct elements from [N], say S={x1,x2,,xn}, the elements are mapped to the hash values h(x1),h(x2),,h(xn). This can be seen as throwing n balls to M bins, with pairwise independent choices of bins.

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 x1,x2S which are mapped to the same hash value, i.e. h(x1)=h(x2). Formally, for a fixed set of elements S={x1,x2,,xn}, for any 1i,jn, let the random variable

Xij={1if h(xi)=h(xj),0otherwise.

The total number of collision pairs among the n items x1,x2,,xn is

X=i<jXij.

Since H is 2-universal, for any ij,

Pr[Xij=1]=Pr[h(xi)=h(xj)]1M.

The expected number of collision pairs is

E[X]=E[i<jXij]=i<jE[Xij]=i<jPr[Xij=1](n2)1M<n22M.

In particular, for n=M, i.e. n items are mapped to n hash values by a pairwise independent hash function, the expected collision number is E[X]<n22M=n2.

The above analysis gives us an estimation on the expected number of collision pairs, such that E[X]<n22M. Apply the Markov's inequality, for 0<ϵ<1, we have

Pr[Xn22ϵM]Pr[X1ϵE[X]]ϵ.

When n2ϵM, the number of collision pairs is X1 with probability at most ϵ, therefore with probability at least 1ϵ, there is no collision at all. Therefore, we have the following theorem.

Theorem
If h is chosen uniformly from a 2-universal family of hash functions mapping the universe [N] to [M] where NM, then for any set S[N] of n items, where n2ϵM, the probability that there exits a collision pair is
Pr[collision occurs]ϵ.

Recall that for mutually independent choices of bins, for some n=2Mln(1/ϵ), the probability that a collision occurs is about ϵ. For constant ϵ, this gives an essentially same bound as the pairwise independent setting. Therefore, the behavior of pairwise independent hash function is essentially the same as the uniform random hash function for the birthday problem. This is easy to understand, because birthday problem is about the behavior of collisions, and the definition of 2-universal hash function can be interpreted as "functions that the probability of collision is as low as a uniform random function".

Set Membership

A basic question in Computer Science is:

"Is xS?"

for a set S and an element x. This is the set membership problem.

Formally, given an arbitrary set S of n elements from a universe U, we want to use a succinct data structure to represent this set S, so that upon each query of any element x from the universe [N], the question of whether xS is efficiently answered. The complexity of such data structure is measured in two-fold:

  • space cost: size of the data structure to represent a set S of size n;
  • time cost: time complexity of answering each query by accessing to the data structure.

Suppose that the universe U is of size N. Clearly, the membership problem can be solved by a dictionary data structure, e.g.:

  • sorted table / balanced search tree: with space cost O(nlogN) bits and time cost O(logn).

Note that log(Nn)=Θ(nlogNn) is the entropy of sets S of n elements from a universe U of size N. Therefore it is necessary to use so many bits to represent a set without losing any information. With hashing, we can solve this fundamental problem with asymptotic optimal space cost and time cost at the same time.

Perfect hashing using quadratic space

The idea of perfect hashing is that we use a hash function h to map the n items to distinct entries of the table; store every item xS in the entry h(x); and also store the hash function h in a fixed location in the table (usually the beginning of the table). The algorithm for searching for an item is as follows:

search for x in table T:
  1. retrieve h from a fixed location in the table;
  2. if x=T[h(x)] return h(x); else return NOT_FOUND;

This scheme works as long as that the hash function satisfies the following two conditions:

  • The description of h is sufficiently short, so that h can be stored in one entry (or in constant many entries) of the table.
  • h has no collisions on S, i.e. there is no pair of items x1,x2S that are mapped to the same value by h.

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 a and b, which can be stored in two entries (or just one, if the word length is sufficiently large) of the table.

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 S.

A hash function h is perfect for a set S of items if h maps all items in S to different values, i.e. there is no collision.

We have shown by the birthday problem for 2-universal hashing that when n items are mapped to n2 values, for an h chosen uniformly from a 2-universal family of hash functions, the probability that a collision occurs is at most 1/2. Thus

Pr[h is perfect for S]12

for a table of n2 entries.

The construction of perfect hashing is straightforward then:

For a set S of n elements:
  1. uniformly choose an h from a 2-universal family H; (for Carter-Wegman's construction, it means uniformly choose two integer 1ap1 and b[p] for a sufficiently large prime p.)
  2. check whether h is perfect for S;
  3. if h is NOT perfect for S, start over again; otherwise, construct the table;

This is a Las Vegas randomized algorithm, which construct a perfect hashing for a fixed set S with expectedly at most two trials (due to geometric distribution). The resulting data structure is a O(n2)-size static dictionary of n elements which answers every search in deterministic O(1) time.

FKS perfect hashing

In the last section we see how to use O(n2) space and constant time for answering search in a set. Now we see how to do it with linear space and constant time. This solves the problem of searching asymptotically optimal for both time and space.

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, n items are hashed to n buckets by a 2-universal hash function h.
Let Bi be the set of items hashed to the ith bucket.
  • In the second level, construct a |Bi|2-size perfect hashing for each bucket Bi.

The data structure can be stored in a table. The first few entries are reserved to store the primary hash function h. To help the searching algorithm locate a bucket, we use the next n entries of the table as the "pointers" to the bucket: each entry stores the address of the first entry of the space to store a bucket. In the rest of table, the n buckets are stored in order, each using a |Bi|2 space as required by perfect hashing.

It is easy to see that the search time is constant. To search for an item x, the algorithm does the followings:

  • Retrieve h.
  • Retrieve the address for bucket h(x).
  • Search by perfect hashing within bucket h(x).

Each line takes constant time. So the worst-case search time is constant.

We then need to guarantee that the space is linear to n. At the first glance, this seems impossible because each instance of perfect hashing for a bucket costs a square-size of space. We will prove that although the individual buckets use square-sized spaces, the sum of the them is still linear.

For a fixed set S of n items, for a hash function h chosen uniformly from a 2-universe family which maps the items to [n], called n buckets, let Yi=|Bi| be the number of items in S mapped to the ith bucket. We are going to bound the following quantity:

Y=i=1nYi2.

Since each bucket Bi use a space of Yi2 for perfect hashing. Y gives the size of the space for storing the buckets.

We will show that Y is related to the total number of collision pairs. (Indeed, the number of collision pairs can be computed by a degree-2 polynomial, just like Y.)

Note that a bucket of Yi items contributes (Yi2) collision pairs. Let X be the total number of collision pairs. X can be computed by summing over the collision pairs in every bucket:

X=i=1n(Yi2)=i=1nYi(Yi1)2=12(i=1nYi2i=1nYi)=12(i=1nYi2n).

Therefore, the sum of squares of the sizes of buckets is related to collision number by:

i=1nYi2=2X+n.

By our analysis of the collision number, we know that for n items mapped to n buckets, the expected number of collision pairs is: E[X]n2. Thus,

E[i=1nYi2]=E[2X+n]2n.

Due to Markov's inequality, i=1nYi2=O(n) with a constant probability. For any set S, we can find a suitable h after expected constant number of trials, and FKS can be constructed with guaranteed (instead of expected) linear-size which answers each search in constant time.

Bloom filter

Now we consider the lossy representation of the original data set S, to further save the space usage. Such lossy data structure is sometimes called a sketch.

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 S of n elements from a universe U, a Bloom filter consists of an array A of cn bits, and k hash functions h1,h2,,hk map U to [cn], where both c and k are parameters that we can try to optimize later.

As before, we assume the Uniform Hash Assumption (UHA): h1,h2,,hk are mutually independent hash function where each hi is a uniform random hash function hi:U[cn].

The Bloom filter works as follows:

Bloom filter (Bloom 1970)
Suppose h1,h2,,hk:U[cn] are uniform and independent random hash functions.

Data structure construction: Given a set SU of size n=|S|, the data structure is a Boolean array A of cn bits constructed as
  • initialize all cn bits of the Boolean array A to 0;
  • for each xS, let A[hi(x)]=1 for all 1ik.

Query resolution: Upon each query of an arbitrary xU,
  • answer "yes" if A[hi(x)]=1 for all 1ik and "no" if otherwise.

The Boolean array is our data structure, whose size is cn bits. With Uniform Hash Assumption (UHA), the time cost of the data structure for answering each query is O(k).

When the answer returned by the algorithm is "no", it holds that A[hi(x)]=0 for some 1ik, in which case the query x must not belong to the set S. Thus, the Bloom filter has no false negatives.

On the other hand, when the answer returned by the algorithm is "yes", A[hi(x)]=1 for all 1ik. It is still possible for some xS that all bits A[hi(x)] are set by elements in S. We want to bound such false positive, that is, the following probability for an xS:

Pr[1ik,A[hi(x)]=1],

which by independence between different hash functions and by symmetry is equal to:

Pr[A[h1(x)]=1]k=(1Pr[A[h1(x)]=0])k.

For an element xS, its hash value h1(x) is independent of all hash values hi(y) for all 1ik and all yS. This is due to the Uniform Hash Assumption. The hash value h1(x) of xS is then independent of the content of the array A. Therefore, the probability of this position A[h1(x)] missed by all kn updates to the Boolean array A caused by all n elements in S is:

Pr[A[h1(x)]=0]=(11cn)knek/c.

Putting everything together, for any xS, the false positive is bounded as:

Pr[wrongly answer ''yes'']=Pr[1ik,A[hi(x)]=1]=Pr[A[h1(x)]=1]k=(1Pr[A[h1(x)]=0])k=(1(11cn)kn)k(1ek/c)k

which is (0.6185)c when k=cln2.

Bloom filter solves the membership query with a small constant error of false positives using a data structure of O(n) bits which answers each query with O(1) time cost.

Distinct Elements

Consider the following problem of counting distinct elements: Suppose that U is a sufficiently large universe.

  • Input: a sequence of (not necessarily distinct) elements x1,x2,,xnU;
  • Output: an estimation of the total number of distinct elements z=|{x1,x2,,xn}|.

A straightforward way of solving this problem is to maintain a dictionary data structure, which costs at least linear (O(n)) space. For big data, where n is very large, this is still too expensive. However, due to an information-theoretical argument, linear space is necessary if you want to compute the exact value of z.

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.

(ϵ,δ)-estimator
A random variable Z^ is an (ϵ,δ)-estimator of a quantity z if
Pr[(1ϵ)zZ^(1+ϵ)z]1δ.
Z^ is said to be an unbiased estimator of z if E[Z^]=z.

Usually ϵ is called approximation error and δ is called confidence error.

We now present an elegant algorithm. The algorithm can be implemented in data stream model: The input elements x1,x2,,xn is presented to the algorithm one at a time, where the size of data n is unknown to the algorithm. The algorithm maintains a value Z^ which is an (ϵ,δ)-estimator of the total number of distinct elements z=|{x1,x2,,xn}|, using only a small amount of memory space to memorize (with loss) the data set {x1,x2,,xn}.

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 min-sketch

Suppose that we can access to an idealized random hash function h:U[0,1] which is uniformly distributed over all mappings from the universe U to unit interval [0,1].

Recall that the input sequence x1,x2,,xnU consists of z=|{x1,x2,,xn}| distinct elements. These elements are mapped by the random function h to z hash values uniformly and independently distributed in [0,1]. We could maintain these hash values instead of the original elements, but this would still be too expensive because in the worst case we still have up to n distinct values to maintain. However, due to the idealized random hash function, the unit interval [0,1] will be partitioned into z+1 subintervals by these z uniform and independent hash values. The typical length of the subinterval gives an estimation of the number z.

Proposition
E[min1inh(xi)]=1z+1.
Proof.

The input sequence x1,x2,,xnU consisting of z distinct elements are mapped to z random hash values uniformly and independently distributed in [0,1]. These z hash values partition the unit interval [0,1] into z+1 subintervals [0,v1],[v1,v2],[v2,v3],[vz1,vz],[vz,1], where vi denotes the i-th smallest value among all hash values {h(x1),h(x2),,h(xn)}. Clearly we have

v1=min1inh(xi).

Meanwhile, since all hash values are uniformly and independently distributed in [0,1], the lengths of all subintervals v1,v2v1,v3v2,,vzvz1,1vz are identically distributed. By symmetry, they have the same expectation, therefore

(z+1)E[v1]=E[v1]+i=1z1E[vi+1vi]+E[1vz]=E[v1+(v2v1)+(v3v2)++(vzvz1)+1vz]=1,

which implies that

E[min1inh(xi)]=E[v1]=1z+1.

The quantity min1inh(xi) can be computed with small space cost (for storing the current smallest hash value) by scan the input sequence in a single pass. Because as we proved its expectation is 1z+1, the smallest hash value Y=min1inh(xi) gives an unbiased estimator for 1z+1. However, 1Y1 is not necessarily a good estimator for z. Actually, it is a rather poor estimator. Consider for example when z=1, all input elements are the same. In this case, there is only one hash value and Y=min1inh(xi) is distributed uniformly over [0,1], thus 1Y1 fails to be close enough to the correct answer 1 with high probability.

Apply the mean trick to the min-sketch

The reason that the above estimator of a single hash function performs poorly is that the unbiased estimator min1inh(xi) has large variance. So a natural way to reduce this variance is to have multiple independent hash functions and take the average. This generic approach for reducing the variance is called the mean trick.

Suppose that we can access to k independent random hash functions h1,h2,,hk, where each hj:U[0,1] is uniformly and independently distributed over all functions mapping U to [0,1]. Here k is a parameter to be fixed by the desired approximation error ϵ and confidence error δ. The min-sketch algorithm (using the mean trick) is given by the following pseudocode.

The min-sketch
Suppose that h1,h2,,hk:U[0,1] are k uniform and independent random hash functions, where k is a parameter to be fixed later.

Scan the input sequence x1,x2,,xnU in a single pass to compute:
  • Yj=min1inhj(xi) for every j=1,2,,k;
  • average value Y¯=1kj=1kYj;
return Z^=1Y¯1 as the estimator.

The algorithm is easy to implement in data stream model, with a space cost of storing k hash values. The following theorem guarantees that the algorithm returns an (ϵ,δ)-estimator of the total number of distinct elements for a suitable k=O(1ϵ2δ).

Theorem
For any ϵ,δ<1/2, if k4ϵ2δ then the output Z^ always gives an (ϵ,δ)-estimator of the correct answer z.

In the following we prove this main theorem for min-sketch algorithm.

An obstacle to analyze the estimator Z^=1Y¯1 is that it is a nonlinear function of Y¯ who is easier to analyze. Nevertheless, we observe that Z^ is an (ϵ,δ)-estimator of z as long as Y¯ is an (ϵ/2,δ)-estimator of 1z+1. This can be deduced by just verifying the following:

1ϵ/2z+1Y¯1+ϵ/2z+1(1ϵ)z1Y¯1(1+ϵ)z,

for ϵ<12. Therefore,

Pr[(1ϵ)zZ^(1+ϵ)z]Pr[1ϵ/2z+1Y¯1+ϵ/2z+1]=Pr[|Y¯1z+1|ϵ/2z+1].

It is then sufficient to show that Pr[|Y¯1z+1|ϵ/2z+1]1δ for proving the main theorem above. We will see that this is equivalent to show the concentration inequality

Pr[|Y¯E[Y¯]|ϵ/2z+1]1δ().
Lemma
The followings hold for each Yj, j=1,2,k, and Y¯=1kj=1kYj:
  • E[Y¯]=E[Yj]=1z+1;
  • Var[Yj]1(z+1)2, and consequently Var[Y¯]1k(z+1)2.
Proof.

As in the case of single hash function, by symmetry it holds that E[Yj]=1z+1 for every j=1,2,,k. Therefore,

E[Y¯]=1kj=1kE[Yj]=1z+1.

Recall that each Yj is the minimum of z random hash values uniformly and independently distributed over [0,1]. By geometry probability, it holds that for any y[0,1],

Pr[Yj>y]=(1y)z,

which means Pr[Yjy]=1(1y)z. Taking the derivative with respect to y, we obtain the probability density function of random variable Yj, which is z(1y)z1.

We then compute the second moment.

E[Yj2]=01y2z(1y)z1dy=2(z+1)(z+2).

The variance is bounded as

Var[Yj]=E[Yj2]E[Yj]2=2(z+1)(z+2)1(z+1)21(z+1)2.

Due to the (pairwise) independence between Yj's,

Var[Y¯]=Var[1kj=1kYj]=1k2j=1kVar[Yj]1k(z+1)2.

We resume to prove the inequality (). By Chebyshev's inequality, it holds that

Pr[|Y¯E[Y¯]|>ϵ/2z+1]4ϵ2(z+1)2Var[Y¯]4ϵ2k.

When k4ϵ2δ, this probability is at most δ. The inequality () is proved. As we discussed above, this proves the above main theorem min-sketch algorithm improved by the mean trick.

Frequency Estimation

Suppose that U is the data universe. The frequency estimation problem is defined as follows.

  • Data: a sequence of (not necessarily distinct) elements x1,x2,,xnU;
  • Query: an element xU;
  • Output: an estimation f^x of the frequency fx|{ixi=x}| of x in input data.

We still want to give an algorithm in the data stream model: the algorithm scan the input sequence x1,x2,,xn to construct a succinct data structure, such that upon each query of xU, the algorithm returns an estimation of the frequency fx.

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 xU, the algorithm should return an answer f^x satisfying:

Pr[|f^xfx|ϵn]1δ.

Note that this notion of approximation is with bounded additive error which is weaker than the notion of (ϵ,δ)-estimator, whose error bound is multiplicative.

With such weak accuracy guarantee, its is possible to give a succinct data structure whose size is determined only by the error bounds ϵ and δ but independent of n, because only the frequencies of those heavy hitters (elements x with high frequencies fx>ϵn) need to be memorized, and there are at most 1/ϵ many such heavy hitters.

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 k×m integer array, where k and m are two parameters to be determined by the error bounds ϵ and δ. We still adopt the Uniform Hash Assumption to assume that we have access to k mutually independent uniform random hash functions h1,h2,,hk:U[m].

Count-min sketch (Cormode and Muthukrishnan 2003)
Suppose h1,h2,,hk:U[m] are uniform and independent random hash functions.

Data structure construction: Given a sequence x1,x2,,xnU, the data structure is a two-dimensional k×m integer array CMS[k][m] constructed as
  • initialize all entries of CMS[k][m] to 0;
  • for i=1,2,,n, upon receiving xi:
for every 1jk, evaluate hj(xi) and CMS[j][hj(xi)]++.

Query resolution: Upon each query of an arbitrary xU,
  • return f^x=min1jkCMS[j][hj(x)].

It is easy to see that the space cost of count-min sketch is O(km) memory words, or O(kmlogn) bits. Each query is answered within time cost O(k), assuming that an evaluation of hash function can be done in unit or constant time. We then analyze the error bounds.

First, it is easy to observe that for any query xU and every hash function 1jk, it always holds for the corresponding entry in the count-min sketch

CMS[j][hj(x)]fx,

because the appearances of element x in the input sequence contribute at least fx to the value of CMS[j][hj(x)].

Therefore, for any query xU it always holds for the answer f^x=min1jkCMS[j][hj(x)]fx, which means

Pr[|f^xfx|ϵn]=Pr[f^xfxϵn]=j=1kPr[CMS[j][hj(x)]fxϵn],()

where the second equation is due to the mutual independence of random hash functions h1,h2,,hk.

It remains to upper bound the probability Pr[CMS[j][hj(x)]fxϵn], which can be done by calculating the expectation of CMS[j][hj(x)].

Proposition
For any xU and every 1jk, it holds that E[CMS[j][hj(x)]]fx+nm.
Proof.

The value of CMS[j][hj(x)] is constituted by the frequency fx of x and the frequencies fy of all other elements yx among x1,x2,,xn, thus

CMS[j][hj(x)]=fx+y{x1,,xn}{x}hj(y)=hj(x)fy=fx+y{x1,,xn}{x}fyI[hj(y)=hj(x)]

where I[hj(y)=hj(x)] denotes the Boolean random variable that indicates the occurrence of event hj(y)=hj(x).

By linearity of expectation,

E[CMS[j][hj(x)]]=fx+y{x1,x2,,xn}{x}fyPr[hj(y)=hj(x)].

Due to Uniform Hash Assumption (UHA), hj:U[m] is a uniform random function. For any yx, the probability of hash collision is

Pr[hj(y)=hj(x)]=1m.

Therefore,

E[CMS[j][hj(x)]]=fx+1my{x1,,xn}{x}fyfx+1my{x1,,xn}fy=fx+nm,

where the last equation is due to the obvious identity y{x1,,xn}fy=n.

The above proposition shows that for any xU and every 1jk

E[CMS[j][hj(x)]fx]nm.

Recall that CMS[j][hj(x)]fx always holds, thus CMS[j][hj(x)]fx is a positive random variable. By Markov's inequality, we have

Pr[CMS[j][hj(x)]fxϵn]1ϵm.

Combining with above equation (), we have

Pr[|f^xfx|ϵn]=(Pr[CMS[j][hj(x)]fxϵn])k1(ϵm)k.

By setting m=eϵ and k=ln1δ, the above error probability is bounded as 1(ϵm)kδ.

For any positive ϵ and δ, the count-min sketch gives a data structure of size O(km)=O(1ϵlog1δ) (in memory words) and answering each query xU in time O(k)=O(1ϵ) with the following accuracy guarantee:

Pr[|f^xfx|ϵn]1δ.