布隆过滤器的概述及Python实现方法


Posted in Python onDecember 08, 2019

布隆过滤器

布隆过滤器是一种概率空间高效的数据结构。它与hashmap非常相似,用于检索一个元素是否在一个集合中。它在检索元素是否存在时,能很好地取舍空间使用率与误报比例。正是由于这个特性,它被称作概率性数据结构(probabilistic data structure)。

空间效率

我们来仔细地看看它的空间效率。如果你想在集合中存储一系列的元素,有很多种不同的做法。你可以把数据存储在hashmap,随后在hashmap中检索元素是否存在,hashmap的插入和查询的效率都非常高。但是,由于hashmap直接存储内容,所以空间利用率并不高。

如果希望提高空间利用率,我们可以在元素插入集合之前做一次哈希变换。还有其它方法呢?我们可以用位数组来存储元素的哈希值。还有吗,还有吗?我们也允许在位数组中存在哈希冲突。这正是布隆过滤器的工作原理,它们就是基于允许哈希冲突的位数组,可能会造成一些误报。在布隆过滤器的设计阶段就允许哈希冲突的存在,否则空间使用就不够紧凑了。

当使用列表或者集合时,空间效率都是重要且显著的,那么布隆过滤器就应当被考虑。

布隆过滤器基础

布隆过滤器是N位的位数组,其中N是位数组的大小。它还有另一个参数k,表示使用哈希函数的个数。这些哈希函数用来设置位数组的值。当往过滤器中插入元素x时,h1(x), h2(x), ..., hk(x)所对应索引位置的值被置“1”,索引值由各个哈希函数计算得到。注意,如果我们增加哈希函数的数量,误报的概率会趋近于0.但是,插入和查找的时间开销更大,布隆过滤器的容量也会减小。

为了用布隆过滤器检验元素是否存在,我们需要校验是否所有的位置都被置“1”,与我们插入元素的过程非常相似。如果所有位置都被置“1”,那也就意味着该元素很有可能存在于布隆过滤器中。若有位置未被置“1”,那该元素一定不存在。

单的python实现

如果想实现一个简单的布隆过滤器,我们可以这样做:

from bitarray import bitarray
# 3rd party
import mmh3
class BloomFilter(set):
 def __init__(self, size, hash_count):
  super(BloomFilter, self).__init__()
  self.bit_array = bitarray(size)
  self.bit_array.setall(0)
  self.size = size
  self.hash_count = hash_count
 def __len__(self):
  return self.size
 def __iter__(self):
  return iter(self.bit_array)
 def add(self, item):
  for ii in range(self.hash_count):
   index = mmh3.hash(item, ii) % self.size
   self.bit_array[index] = 1
  return self
 def __contains__(self, item):
  out = True
  for ii in range(self.hash_count):
   index = mmh3.hash(item, ii) % self.size
   if self.bit_array[index] == 0:
    out = False
  return out
def main():
 bloom = BloomFilter(100, 10)
 animals = ['dog', 'cat', 'giraffe', 'fly', 'mosquito', 'horse', 'eagle',
    'bird', 'bison', 'boar', 'butterfly', 'ant', 'anaconda', 'bear',
    'chicken', 'dolphin', 'donkey', 'crow', 'crocodile']
 # First insertion of animals into the bloom filter
 for animal in animals:
  bloom.add(animal)
 # Membership existence for already inserted animals
 # There should not be any false negatives
 for animal in animals:
  if animal in bloom:
   print('{} is in bloom filter as expected'.format(animal))
  else:
   print('Something is terribly went wrong for {}'.format(animal))
   print('FALSE NEGATIVE!')
 # Membership existence for not inserted animals
 # There could be false positives
 other_animals = ['badger', 'cow', 'pig', 'sheep', 'bee', 'wolf', 'fox',
      'whale', 'shark', 'fish', 'turkey', 'duck', 'dove',
      'deer', 'elephant', 'frog', 'falcon', 'goat', 'gorilla',
      'hawk' ]
 for other_animal in other_animals:
  if other_animal in bloom:
   print('{} is not in the bloom, but a false positive'.format(other_animal))
  else:
   print('{} is not in the bloom filter as expected'.format(other_animal))
if __name__ == '__main__':
 main()

输出结果如下所示:

dog is in bloom filter as expected
cat is in bloom filter as expected
giraffe is in bloom filter as expected
fly is in bloom filter as expected
mosquito is in bloom filter as expected
horse is in bloom filter as expected
eagle is in bloom filter as expected
bird is in bloom filter as expected
bison is in bloom filter as expected
boar is in bloom filter as expected
butterfly is in bloom filter as expected
ant is in bloom filter as expected
anaconda is in bloom filter as expected
bear is in bloom filter as expected
chicken is in bloom filter as expected
dolphin is in bloom filter as expected
donkey is in bloom filter as expected
crow is in bloom filter as expected
crocodile is in bloom filter as expected


badger is not in the bloom filter as expected
cow is not in the bloom filter as expected
pig is not in the bloom filter as expected
sheep is not in the bloom, but a false positive
bee is not in the bloom filter as expected
wolf is not in the bloom filter as expected
fox is not in the bloom filter as expected
whale is not in the bloom filter as expected
shark is not in the bloom, but a false positive
fish is not in the bloom, but a false positive
turkey is not in the bloom filter as expected
duck is not in the bloom filter as expected
dove is not in the bloom误报 filter as expected
deer is not in the bloom filter as expected
elephant is not in the bloom, but a false positive
frog is not in the bloom filter as expected
falcon is not in the bloom filter as expected
goat is not in the bloom filter as expected
gorilla is not in the bloom filter as expected
hawk is not in the bloom filter as expected

从输出结果可以发现,存在不少误报样本,但是并不存在假阴性。

不同于这段布隆过滤器的实现代码,其它语言的多个实现版本并不提供哈希函数的参数。这是因为在实际应用中误报比例这个指标比哈希函数更重要,用户可以根据误报比例的需求来调整哈希函数的个数。通常来说,sizeerror_rate是布隆过滤器的真正误报比例。如果你在初始化阶段减小了error_rate,它们会调整哈希函数的数量。

误报

布隆过滤器能够拍着胸脯说某个元素“肯定不存在”,但是对于一些元素它们会说“可能存在”。针对不同的应用场景,这有可能会是一个巨大的缺陷,亦或是无关紧要的问题。如果在检索元素是否存在时不介意引入误报情况,那么你就应当考虑用布隆过滤器。

另外,如果随意地减小了误报比率,哈希函数的数量相应地就要增加,在插入和查询时的延时也会相应地增加。本节的另一个要点是,如果哈希函数是相互独立的,并且输入元素在空间中均匀的分布,那么理论上真实误报率就不会超过理论值。否则,由于哈希函数的相关性和更频繁的哈希冲突,布隆过滤器的真实误报比例会高于理论值。

在使用布隆过滤器时,需要考虑误报的潜在影响。

确定性

当你使用相同大小和数量的哈希函数时,某个元素通过布隆过滤器得到的是正反馈还是负反馈的结果是确定的。对于某个元素x,如果它现在可能存在,那五分钟之后、一小时之后、一天之后、甚至一周之后的状态都是可能存在。当我得知这一特性时有一点点惊讶。因为布隆过滤器是概率性的,那其结果显然应该存在某种随机因素,难道不是吗?确实不是。它的概率性体现在我们无法判断究竟哪些元素的状态是可能存在

换句话说,过滤器一旦做出可能存在的结论后,结论不会发生变化。

缺点

布隆过滤器并不十全十美。

布隆过滤器的容量

布隆过滤器需要事先知道将要插入的元素个数。如果你并不知道或者很难估计元素的个数,情况就不太好。你也可以随机指定一个很大的容量,但这样就会浪费许多存储空间,存储空间却是我们试图优化的首要任务,也是选择使用布隆过滤器的原因之一。一种解决方案是创建一个能够动态适应数据量的布隆过滤器,但是在某些应用场景下这个方案无效。有一种可扩展布隆过滤器,它能够调整容量来适应不同数量的元素。它能弥补一部分短板。

布隆过滤器的构造和检索

在使用布隆过滤器时,我们不仅要接受少量的误报率,还要接受速度方面的额外时间开销。相比于hashmap,对元素做哈希映射和构建布隆过滤器时必然存在一些额外的时间开销。

无法返回元素本身

布隆过滤器并不会保存插入元素的内容,只能检索某个元素是否存在,因为存在哈希函数和哈希冲突我们无法得到完整的元素列表。这是它相对于其它数据结构的最显著优势,空间的使用率也造成了这块短板。

删除某个元素

想从布隆过滤器中删除某个元素可不是一件容易的事情,你无法撤回某次插入操作,因为不同项目的哈希结果可以被索引在同一位置。如果想撤消插入,你只能记录每个索引位置被置位的次数,或是重新创建一次。两种方法都有额外的开销。基于不同的应用场景,若要删除一些元素,我们更倾向于重建布隆过滤器。

在不同语言中的实现

在产品中,你肯定不想自己去实现布隆过滤器。有两个原因,其中之一是选择好的哈希函数和实现方法能有效改善错误率的分布。其次,它需要通过实战测试,错误率和容量大小都要经得起实战检验。各种语言都有开源实现的版本,以我自己的经验,下面的Node.js和Python版本实现非常好用:

NodePython

还有更快版本的pybloomfilter(插入和检索速度都比上面的python库快10倍),但它需要运行在PyPy环境下,并不支持Python3。

总结

以上所述是小编给大家介绍的布隆过滤器的概述及Python实现方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

Python 相关文章推荐
在SAE上部署Python的Django框架的一些问题汇总
May 30 Python
python从入门到精通(DAY 3)
Dec 20 Python
Python subprocess模块详细解读
Jan 29 Python
使用Python处理Excel表格的简单方法
Jun 07 Python
python实现逐个读取txt字符并修改
Dec 24 Python
python中比较两个列表的实例方法
Jul 04 Python
python自定义时钟类、定时任务类
Feb 22 Python
python 的 openpyxl模块 读取 Excel文件的方法
Sep 09 Python
解决Tensorflow2.0 tf.keras.Model.load_weights() 报错处理问题
Jun 12 Python
解决pytorch 数据类型报错的问题
Mar 03 Python
如何在python中实现ECDSA你知道吗
Nov 23 Python
Python+Matplotlib+LaTeX玩转数学公式
Feb 24 Python
Python+Redis实现布隆过滤器
Dec 08 #Python
PyCharm 2019.3发布增加了新功能一览
Dec 08 #Python
使用tqdm显示Python代码执行进度功能
Dec 08 #Python
Python tkinter实现图片标注功能(完整代码)
Dec 08 #Python
Python中six模块基础用法
Dec 08 #Python
python实现布隆过滤器及原理解析
Dec 08 #Python
python实现图片二值化及灰度处理方式
Dec 07 #Python
You might like
php过滤html标记属性类用法实例
2014/09/23 PHP
用 Composer构建自己的 PHP 框架之构建路由
2014/10/30 PHP
ThinkPHP入库出现两次反斜线转义及数据库类转义的解决方法
2014/11/04 PHP
基于PHP后台的Android新闻浏览客户端
2016/05/23 PHP
php实用代码片段整理
2016/11/12 PHP
PHP观察者模式实例分析【对比JS观察者模式】
2019/05/22 PHP
PHP 使用位运算实现四则运算的代码
2021/03/09 PHP
一个判断email合法性的函数[非正则]
2008/12/09 Javascript
在每个匹配元素的外部插入新元素的方法
2013/12/20 Javascript
js写出遮罩层登陆框和对联广告并自动跟随滚动条滚动
2014/04/29 Javascript
将HTML格式的String转化为HTMLElement的实现方法
2014/08/07 Javascript
jsonp跨域请求数据实现手机号码查询实例分析
2015/12/12 Javascript
bootstrap datepicker插件默认英文修改为中文
2017/07/28 Javascript
vue实现吸顶、锚点和滚动高亮按钮效果
2019/10/21 Javascript
JavaScript中的相等操作符使用详解
2019/12/21 Javascript
VUE实现Studio管理后台之鼠标拖放改变窗口大小
2020/03/04 Javascript
flexible.js实现移动端rem适配方案
2020/04/07 Javascript
Vue3不支持Filters过滤器的问题
2020/09/24 Javascript
Python基类函数的重载与调用实例分析
2015/01/12 Python
Python网络编程中urllib2模块的用法总结
2016/07/12 Python
Python常见加密模块用法分析【MD5,sha,crypt模块】
2017/05/24 Python
Tensorflow 训练自己的数据集将数据直接导入到内存
2018/06/19 Python
[原创]Python入门教程2. 字符串基本操作【运算、格式化输出、常用函数】
2018/10/29 Python
PyQt QCombobox设置行高的方法
2019/06/20 Python
Python循环实现n的全排列功能
2019/09/16 Python
利用python实现PSO算法优化二元函数
2019/11/13 Python
Python udp网络程序实现发送、接收数据功能示例
2019/12/09 Python
Python requests获取网页常用方法解析
2020/02/20 Python
详解在Python中使用Torchmoji将文本转换为表情符号
2020/07/27 Python
Pytorch1.5.1版本安装的方法步骤
2020/12/31 Python
python上下文管理器异常问题解决方法
2021/02/07 Python
详解Html5中video标签那些属性和方法
2019/07/01 HTML / CSS
Interrail法国:乘火车探索欧洲,最受欢迎的欧洲铁路通票
2019/08/27 全球购物
什么是就业协议书
2014/04/17 职场文书
供货协议书
2014/04/22 职场文书
初中团委工作总结
2015/08/13 职场文书