Bloom Filter概念和原理

Bloom Filter是一种空间效率很高的随机数据结构,它利用位数组很简洁地表示一个集合,并能判断一个元素是否属于这个集合。Bloom Filter的这种高效是有一定代价的:在判断一个元素是否属于某个集合时,有可能会把不属于这个集合的元素误认为属于这个集合(false positive)。因此,Bloom Filter不适合那些“零错误”的应用场合。而在能容忍低错误率的应用场合下,Bloom Filter通过极少的错误换取了存储空间的极大节省。

集合表示和元素查询

下面我们具体来看Bloom Filter是如何用位数组表示集合的。初始状态时,Bloom Filter是一个包含m位的位数组,每一位都置为0

为了表达S={x1, x2,…,xn}这样一个n个元素的集合,Bloom Filter使用k个相互独立的哈希函数(Hash Function),它们分别将集合中的每个元素映射到{1,…,m}的范围中。对任意一个元素x,第i个哈希函数映射的位置hi(x)就会被置为11ik)。注意,如果一个位置多次被置为1,那么只有第一次会起作用,后面几次将没有任何效果。在下图中,k=3,且有两个哈希函数选中同一个位置(从左边数第五位)。   

 

在判断y是否属于这个集合时,我们对y应用k次哈希函数,如果所有hi(y)的位置都是11ik),那么我们就认为y是集合中的元素,否则就认为y不是集合中的元素。下图中y1就不是集合中的元素。y2或者属于这个集合,或者刚好是一个false positive

错误率估计

前面我们已经提到了,Bloom Filter在判断一个元素是否属于它表示的集合时会有一定的错误率(false positive rate),下面我们就来估计错误率的大小。在估计之前为了简化模型,我们假设kn<m且各个哈希函数是完全随机的。当集合S={x1, x2,…,xn}的所有元素都被k个哈希函数映射到m位的位数组中时,这个位数组中某一位还是0的概率是:

其中1/m表示任意一个哈希函数选中这一位的概率(前提是哈希函数是完全随机的),(1-1/m)表示哈希一次没有选中这一位的概率。要把S完全映射到位数组中,需要做kn次哈希。某一位还是0意味着kn次哈希都没有选中它,因此这个概率就是(1-1/m)的kn次方。令p = e-kn/m是为了简化运算,这里用到了计算e时常用的近似:

 

令ρ为位数组中0的比例,则ρ的数学期望E(ρ)= p’。在ρ已知的情况下,要求的错误率(false positive rate)为:

(1-ρ)为位数组中1的比例,(1-ρ)k就表示k次哈希都刚好选中1的区域,即false positive rate。上式中第二步近似在前面已经提到了,现在来看第一步近似。p’只是ρ的数学期望,在实际中ρ的值有可能偏离它的数学期望值。M. Mitzenmacher已经证明[2] ,位数组中0的比例非常集中地分布在它的数学期望值的附近。因此,第一步的近似得以成立。分别将pp’代入上式中,得:

   

   

相比p’f’,使用pf通常在分析中更为方便。

最优的哈希函数个数

既然Bloom Filter要靠多个哈希函数将集合映射到位数组中,那么应该选择几个哈希函数才能使元素查询时的错误率降到最低呢?这里有两个互斥的理由:如果哈希函数的个数多,那么在对一个不属于集合的元素进行查询时得到0的概率就大;但另一方面,如果哈希函数的个数少,那么位数组中的0就多。为了得到最优的哈希函数个数,我们需要根据上一小节中的错误率公式进行计算。

 

先用pf进行计算。注意到f = exp(k ln(1 − e−kn/m)),我们令g = k ln(1 − e−kn/m),只要让g取到最小,f自然也取到最小。由于p = e-kn/m,我们可以将g写成

根据对称性法则可以很容易看出当p = 1/2,也就是k = ln2· (m/n)时,g取得最小值。在这种情况下,最小错误率f等于(1/2) (0.6185)m/n。另外,注意到p是位数组中某一位仍是0的概率,所以p = 1/2对应着位数组中0和1各一半。换句话说,要想保持错误率低,最好让位数组有一半还空着。

 

需要强调的一点是,p = 1/2时错误率最小这个结果并不依赖于近似值pf。同样对于f’ = exp(k ln(1 − (1 − 1/m)kn))g’ = k ln(1 − (1 − 1/m)kn)p’ = (1 − 1/m)kn,我们可以将g’写成

同样根据对称性法则可以得到当p’ = 1/2时,g’取得最小值。

位数组的大小

下面我们来看看,在不超过一定错误率的情况下,Bloom Filter至少需要多少位才能表示全集中任意n个元素的集合。假设全集中共有u个元素,允许的最大错误率为є,下面我们来求位数组的位数m

 

假设X为全集中任取n个元素的集合,F(X)是表示X的位数组。那么对于集合X中任意一个元素x,在s = F(X)中查询x都能得到肯定的结果,即s能够接受x。显然,由于Bloom Filter引入了错误,s能够接受的不仅仅是X中的元素,它还能够є (u - n)false positive。因此,对于一个确定的位数组来说,它能够接受总共n + є (u - n)个元素。在n + є (u - n)个元素中,s真正表示的只有其中n个,所以一个确定的位数组可以表示

个集合。m位的位数组共有2m个不同的组合,进而可以推出,m位的位数组可以表示

   

个集合。全集中n个元素的集合总共有

   

个,因此要让m位的位数组能够表示所有n个元素的集合,必须有

   

即:

   

上式中的近似前提是nєu相比很小,这也是实际情况中常常发生的。根据上式,我们得出结论:在错误率不大于є的情况下,m至少要等于n log2(1/є)才能表示任意n个元素的集合。

 

上一小节中我们曾算出当k = ln2· (m/n)时错误率f最小,这时f = (1/2)= (1/2)mln2 / n。现在令fє,可以推出

这个结果比前面我们算得的下界n log2(1/є)大了log 1.44倍。这说明在哈希函数的个数取到最优时,要让错误率不超过єm至少需要取到最小值的1.44倍。

总结

在计算机科学中,我们常常会碰到时间换空间或者空间换时间的情况,即为了达到某一个方面的最优而牺牲另一个方面。Bloom Filter在时间空间这两个因素之外又引入了另一个因素:错误率。在使用Bloom Filter判断一个元素是否属于某个集合时,会有一定的错误率。也就是说,有可能把不属于这个集合的元素误认为属于这个集合(False Positive),但不会把属于这个集合的元素误认为不属于这个集合(False Negative)。在增加了错误率这个因素之后,Bloom Filter通过允许少量的错误来节省大量的存储空间。

 

自从Burton Bloom70年代提出Bloom Filter之后,Bloom Filter就被广泛用于拼写检查和数据库系统中。近一二十年,伴随着网络的普及和发展,Bloom Filter在网络领域获得了新生,各种Bloom Filter变种和新的应用不断出现。可以预见,随着网络应用的不断深入,新的变种和应用将会继续出现,Bloom Filter必将获得更大的发展。

参考资料

[1] A. Broder and M. Mitzenmacher. Network applications of bloom filters: A survey. Internet Mathematics, 1(4):485–509, 2005.

[2] M. Mitzenmacher. Compressed Bloom Filters. IEEE/ACM Transactions on Networking 10:5 (2002), 604—612.

[3] www.cs.jhu.edu/~fabian/courses/CS600.624/slides/bloomslides.pdf

[4] http://166.111.248.20/seminar/2006_11_23/hash_2_yaxuan.ppt


===============================java实现=================================================

摘自 https://github.com/MagnusS/Java-BloomFilter

BloomFilter.java

/**
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU Lesser General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  * GNU Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public License
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
  */
   
  package com.skjegstad.utils;
   
  import java.io.Serializable;
  import java.nio.charset.Charset;
  import java.security.MessageDigest;
  import java.security.NoSuchAlgorithmException;
  import java.util.BitSet;
  import java.util.Collection;
   
  /**
  * Implementation of a Bloom-filter, as described here:
  * http://en.wikipedia.org/wiki/Bloom_filter
  *
  * For updates and bugfixes, see http://github.com/magnuss/java-bloomfilter
  *
  * Inspired by the SimpleBloomFilter-class written by Ian Clarke. This
  * implementation provides a more evenly distributed Hash-function by
  * using a proper digest instead of the Java RNG. Many of the changes
  * were proposed in comments in his blog:
  * http://blog.locut.us/2008/01/12/a-decent-stand-alone-java-bloom-filter-implementation/
  *
  * @param <E> Object type that is to be inserted into the Bloom filter, e.g. String or Integer.
  * @author Magnus Skjegstad <[email protected]>
  */
  public class BloomFilter<E> implements Serializable {
  private BitSet bitset;
  private int bitSetSize;
  private double bitsPerElement;
  private int expectedNumberOfFilterElements; // expected (maximum) number of elements to be added
  private int numberOfAddedElements; // number of elements actually added to the Bloom filter
  private int k; // number of hash functions
   
  static final Charset charset = Charset.forName("UTF-8"); // encoding used for storing hash values as strings
   
  static final String hashName = "MD5"; // MD5 gives good enough accuracy in most circumstances. Change to SHA1 if it's needed
  static final MessageDigest digestFunction;
  static { // The digest method is reused between instances
  MessageDigest tmp;
  try {
  tmp = java.security.MessageDigest.getInstance(hashName);
  } catch (NoSuchAlgorithmException e) {
  tmp = null;
  }
  digestFunction = tmp;
  }
   
  /**
  * Constructs an empty Bloom filter. The total length of the Bloom filter will be
  * c*n.
  *
  * @param c is the number of bits used per element.
  * @param n is the expected number of elements the filter will contain.
  * @param k is the number of hash functions used.
  */
  public BloomFilter(double c, int n, int k) {
  this.expectedNumberOfFilterElements = n;
  this.k = k;
  this.bitsPerElement = c;
  this.bitSetSize = (int)Math.ceil(c * n);
  numberOfAddedElements = 0;
  this.bitset = new BitSet(bitSetSize);
  }
   
  /**
  * Constructs an empty Bloom filter. The optimal number of hash functions (k) is estimated from the total size of the Bloom
  * and the number of expected elements.
  *
  * @param bitSetSize defines how many bits should be used in total for the filter.
  * @param expectedNumberOElements defines the maximum number of elements the filter is expected to contain.
  */
  public BloomFilter(int bitSetSize, int expectedNumberOElements) {
  this(bitSetSize / (double)expectedNumberOElements,
  expectedNumberOElements,
  (int) Math.round((bitSetSize / (double)expectedNumberOElements) * Math.log(2.0)));
  }
   
  /**
  * Constructs an empty Bloom filter with a given false positive probability. The number of bits per
  * element and the number of hash functions is estimated
  * to match the false positive probability.
  *
  * @param falsePositiveProbability is the desired false positive probability.
  * @param expectedNumberOfElements is the expected number of elements in the Bloom filter.
  */
  public BloomFilter(double falsePositiveProbability, int expectedNumberOfElements) {
  this(Math.ceil(-(Math.log(falsePositiveProbability) / Math.log(2))) / Math.log(2), // c = k / ln(2)
  expectedNumberOfElements,
  (int)Math.ceil(-(Math.log(falsePositiveProbability) / Math.log(2)))); // k = ceil(-log_2(false prob.))
  }
   
  /**
  * Construct a new Bloom filter based on existing Bloom filter data.
  *
  * @param bitSetSize defines how many bits should be used for the filter.
  * @param expectedNumberOfFilterElements defines the maximum number of elements the filter is expected to contain.
  * @param actualNumberOfFilterElements specifies how many elements have been inserted into the <code>filterData</code> BitSet.
  * @param filterData a BitSet representing an existing Bloom filter.
  */
  public BloomFilter(int bitSetSize, int expectedNumberOfFilterElements, int actualNumberOfFilterElements, BitSet filterData) {
  this(bitSetSize, expectedNumberOfFilterElements);
  this.bitset = filterData;
  this.numberOfAddedElements = actualNumberOfFilterElements;
  }
   
  /**
  * Generates a digest based on the contents of a String.
  *
  * @param val specifies the input data.
  * @param charset specifies the encoding of the input data.
  * @return digest as long.
  */
  public static int createHash(String val, Charset charset) {
  return createHash(val.getBytes(charset));
  }
   
  /**
  * Generates a digest based on the contents of a String.
  *
  * @param val specifies the input data. The encoding is expected to be UTF-8.
  * @return digest as long.
  */
  public static int createHash(String val) {
  return createHash(val, charset);
  }
   
  /**
  * Generates a digest based on the contents of an array of bytes.
  *
  * @param data specifies input data.
  * @return digest as long.
  */
  public static int createHash(byte[] data) {
  return createHashes(data, 1)[0];
  }
   
  /**
  * Generates digests based on the contents of an array of bytes and splits the result into 4-byte int's and store them in an array. The
  * digest function is called until the required number of int's are produced. For each call to digest a salt
  * is prepended to the data. The salt is increased by 1 for each call.
  *
  * @param data specifies input data.
  * @param hashes number of hashes/int's to produce.
  * @return array of int-sized hashes
  */
  public static int[] createHashes(byte[] data, int hashes) {
  int[] result = new int[hashes];
   
  int k = 0;
  byte salt = 0;
  while (k < hashes) {
  byte[] digest;
  synchronized (digestFunction) {
  digestFunction.update(salt);
  salt++;
  digest = digestFunction.digest(data);
  }
   
  for (int i = 0; i < digest.length/4 && k < hashes; i++) {
  int h = 0;
  for (int j = (i*4); j < (i*4)+4; j++) {
  h <<= 8;
  h |= ((int) digest[j]) & 0xFF;
  }
  result[k] = h;
  k++;
  }
  }
  return result;
  }
   
  /**
  * Compares the contents of two instances to see if they are equal.
  *
  * @param obj is the object to compare to.
  * @return True if the contents of the objects are equal.
  */
  @Override
  public boolean equals(Object obj) {
  if (obj == null) {
  return false;
  }
  if (getClass() != obj.getClass()) {
  return false;
  }
  final BloomFilter<E> other = (BloomFilter<E>) obj;
  if (this.expectedNumberOfFilterElements != other.expectedNumberOfFilterElements) {
  return false;
  }
  if (this.k != other.k) {
  return false;
  }
  if (this.bitSetSize != other.bitSetSize) {
  return false;
  }
  if (this.bitset != other.bitset && (this.bitset == null || !this.bitset.equals(other.bitset))) {
  return false;
  }
  return true;
  }
   
  /**
  * Calculates a hash code for this class.
  * @return hash code representing the contents of an instance of this class.
  */
  @Override
  public int hashCode() {
  int hash = 7;
  hash = 61 * hash + (this.bitset != null ? this.bitset.hashCode() : 0);
  hash = 61 * hash + this.expectedNumberOfFilterElements;
  hash = 61 * hash + this.bitSetSize;
  hash = 61 * hash + this.k;
  return hash;
  }
   
   
  /**
  * Calculates the expected probability of false positives based on
  * the number of expected filter elements and the size of the Bloom filter.
  * <br /><br />
  * The value returned by this method is the <i>expected</i> rate of false
  * positives, assuming the number of inserted elements equals the number of
  * expected elements. If the number of elements in the Bloom filter is less
  * than the expected value, the true probability of false positives will be lower.
  *
  * @return expected probability of false positives.
  */
  public double expectedFalsePositiveProbability() {
  return getFalsePositiveProbability(expectedNumberOfFilterElements);
  }
   
  /**
  * Calculate the probability of a false positive given the specified
  * number of inserted elements.
  *
  * @param numberOfElements number of inserted elements.
  * @return probability of a false positive.
  */
  public double getFalsePositiveProbability(double numberOfElements) {
  // (1 - e^(-k * n / m)) ^ k
  return Math.pow((1 - Math.exp(-k * (double) numberOfElements
  / (double) bitSetSize)), k);
   
  }
   
  /**
  * Get the current probability of a false positive. The probability is calculated from
  * the size of the Bloom filter and the current number of elements added to it.
  *
  * @return probability of false positives.
  */
  public double getFalsePositiveProbability() {
  return getFalsePositiveProbability(numberOfAddedElements);
  }
   
   
  /**
  * Returns the value chosen for K.<br />
  * <br />
  * K is the optimal number of hash functions based on the size
  * of the Bloom filter and the expected number of inserted elements.
  *
  * @return optimal k.
  */
  public int getK() {
  return k;
  }
   
  /**
  * Sets all bits to false in the Bloom filter.
  */
  public void clear() {
  bitset.clear();
  numberOfAddedElements = 0;
  }
   
  /**
  * Adds an object to the Bloom filter. The output from the object's
  * toString() method is used as input to the hash functions.
  *
  * @param element is an element to register in the Bloom filter.
  */
  public void add(E element) {
  add(element.toString().getBytes(charset));
  }
   
  /**
  * Adds an array of bytes to the Bloom filter.
  *
  * @param bytes array of bytes to add to the Bloom filter.
  */
  public void add(byte[] bytes) {
  int[] hashes = createHashes(bytes, k);
  for (int hash : hashes)
  bitset.set(Math.abs(hash % bitSetSize), true);
  numberOfAddedElements ++;
  }
   
  /**
  * Adds all elements from a Collection to the Bloom filter.
  * @param c Collection of elements.
  */
  public void addAll(Collection<? extends E> c) {
  for (E element : c)
  add(element);
  }
   
  /**
  * Returns true if the element could have been inserted into the Bloom filter.
  * Use getFalsePositiveProbability() to calculate the probability of this
  * being correct.
  *
  * @param element element to check.
  * @return true if the element could have been inserted into the Bloom filter.
  */
  public boolean contains(E element) {
  return contains(element.toString().getBytes(charset));
  }
   
  /**
  * Returns true if the array of bytes could have been inserted into the Bloom filter.
  * Use getFalsePositiveProbability() to calculate the probability of this
  * being correct.
  *
  * @param bytes array of bytes to check.
  * @return true if the array could have been inserted into the Bloom filter.
  */
  public boolean contains(byte[] bytes) {
  int[] hashes = createHashes(bytes, k);
  for (int hash : hashes) {
  if (!bitset.get(Math.abs(hash % bitSetSize))) {
  return false;
  }
  }
  return true;
  }
   
  /**
  * Returns true if all the elements of a Collection could have been inserted
  * into the Bloom filter. Use getFalsePositiveProbability() to calculate the
  * probability of this being correct.
  * @param c elements to check.
  * @return true if all the elements in c could have been inserted into the Bloom filter.
  */
  public boolean containsAll(Collection<? extends E> c) {
  for (E element : c)
  if (!contains(element))
  return false;
  return true;
  }
   
  /**
  * Read a single bit from the Bloom filter.
  * @param bit the bit to read.
  * @return true if the bit is set, false if it is not.
  */
  public boolean getBit(int bit) {
  return bitset.get(bit);
  }
   
  /**
  * Set a single bit in the Bloom filter.
  * @param bit is the bit to set.
  * @param value If true, the bit is set. If false, the bit is cleared.
  */
  public void setBit(int bit, boolean value) {
  bitset.set(bit, value);
  }
   
  /**
  * Return the bit set used to store the Bloom filter.
  * @return bit set representing the Bloom filter.
  */
  public BitSet getBitSet() {
  return bitset;
  }
   
  /**
  * Returns the number of bits in the Bloom filter. Use count() to retrieve
  * the number of inserted elements.
  *
  * @return the size of the bitset used by the Bloom filter.
  */
  public int size() {
  return this.bitSetSize;
  }
   
  /**
  * Returns the number of elements added to the Bloom filter after it
  * was constructed or after clear() was called.
  *
  * @return number of elements added to the Bloom filter.
  */
  public int count() {
  return this.numberOfAddedElements;
  }
   
  /**
  * Returns the expected number of elements to be inserted into the filter.
  * This value is the same value as the one passed to the constructor.
  *
  * @return expected number of elements.
  */
  public int getExpectedNumberOfElements() {
  return expectedNumberOfFilterElements;
  }
   
  /**
  * Get expected number of bits per element when the Bloom filter is full. This value is set by the constructor
  * when the Bloom filter is created. See also getBitsPerElement().
  *
  * @return expected number of bits per element.
  */
  public double getExpectedBitsPerElement() {
  return this.bitsPerElement;
  }
   
  /**
  * Get actual number of bits per element based on the number of elements that have currently been inserted and the length
  * of the Bloom filter. See also getExpectedBitsPerElement().
  *
  * @return number of bits per element.
  */
  public double getBitsPerElement() {
  return this.bitSetSize / (double)numberOfAddedElements;
  }
  }

BloomfilterBenchmark.java

/**
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU Lesser General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  * GNU Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public License
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
  */
  package com.skjegstad.utils;
   
  import java.util.ArrayList;
  import java.util.List;
  import java.util.Random;
   
  /**
  * A (very) simple benchmark to evaluate the performance of the Bloom filter class.
  *
  * @author Magnus Skjegstad
  */
  public class BloomfilterBenchmark {
  static int elementCount = 50000; // Number of elements to test
   
  public static void printStat(long start, long end) {
  double diff = (end - start) / 1000.0;
  System.out.println(diff + "s, " + (elementCount / diff) + " elements/s");
  }
   
  public static void main(String[] argv) {
   
   
  final Random r = new Random();
   
  // Generate elements first
  List<String> existingElements = new ArrayList(elementCount);
  for (int i = 0; i < elementCount; i++) {
  byte[] b = new byte[200];
  r.nextBytes(b);
  existingElements.add(new String(b));
  }
   
  List<String> nonExistingElements = new ArrayList(elementCount);
  for (int i = 0; i < elementCount; i++) {
  byte[] b = new byte[200];
  r.nextBytes(b);
  nonExistingElements.add(new String(b));
  }
   
  BloomFilter<String> bf = new BloomFilter<String>(0.001, elementCount);
   
  System.out.println("Testing " + elementCount + " elements");
  System.out.println("k is " + bf.getK());
   
  // Add elements
  System.out.print("add(): ");
  long start_add = System.currentTimeMillis();
  for (int i = 0; i < elementCount; i++) {
  bf.add(existingElements.get(i));
  }
  long end_add = System.currentTimeMillis();
  printStat(start_add, end_add);
   
  // Check for existing elements with contains()
  System.out.print("contains(), existing: ");
  long start_contains = System.currentTimeMillis();
  for (int i = 0; i < elementCount; i++) {
  bf.contains(existingElements.get(i));
  }
  long end_contains = System.currentTimeMillis();
  printStat(start_contains, end_contains);
   
  // Check for existing elements with containsAll()
  System.out.print("containsAll(), existing: ");
  long start_containsAll = System.currentTimeMillis();
  for (int i = 0; i < elementCount; i++) {
  bf.contains(existingElements.get(i));
  }
  long end_containsAll = System.currentTimeMillis();
  printStat(start_containsAll, end_containsAll);
   
  // Check for nonexisting elements with contains()
  System.out.print("contains(), nonexisting: ");
  long start_ncontains = System.currentTimeMillis();
  for (int i = 0; i < elementCount; i++) {
  bf.contains(nonExistingElements.get(i));
  }
  long end_ncontains = System.currentTimeMillis();
  printStat(start_ncontains, end_ncontains);
   
  // Check for nonexisting elements with containsAll()
  System.out.print("containsAll(), nonexisting: ");
  long start_ncontainsAll = System.currentTimeMillis();
  for (int i = 0; i < elementCount; i++) {
  bf.contains(nonExistingElements.get(i));
  }
  long end_ncontainsAll = System.currentTimeMillis();
  printStat(start_ncontainsAll, end_ncontainsAll);
   
  }
  }

猜你喜欢

转载自blog.csdn.net/micwing/article/details/79625099