學(xué)習(xí) Bloom filter

誤判率的推導(dǎo)

  • 前提:
  1. 數(shù)組長(zhǎng)度 m
  2. 有 k 個(gè) hash 函數(shù)么介,每個(gè) hash 函數(shù)彼此獨(dú)立(老實(shí)說(shuō),彼此獨(dú)立這個(gè)條件怎么達(dá)到我也不太清楚烫映,以及或許有其他的前提條件我也不太清楚)
  3. 用 n 個(gè)樣本空間
  • 推導(dǎo)過(guò)程

第一部分:

  1. 經(jīng)過(guò)一個(gè) hash 函數(shù)以后某一位置為 0 的概率是 1 - \frac{1}{m}

  2. 經(jīng)過(guò) k 個(gè) hash 函數(shù)以后某一位置為 0 的概率是 (1 - \frac{1}{m})^{k}

  3. 經(jīng)過(guò) n 個(gè)樣本以后某一位置為 0 的概率是 (1 - \frac{1}{m})^{nk}

  4. 因此經(jīng)過(guò) n 個(gè)樣本以后某一位為 1 的概率是 1 - (1 - \frac{1}{m})^{nk}

  5. 現(xiàn)在再來(lái)一個(gè)新的樣本,全選到 1 的概率是 (1 - (1 - \frac{1}{m})^{nk})^{k}

第二部分,上面先推導(dǎo)到這里接下來(lái)需要推導(dǎo)一個(gè)別的:

  1. 這是 e 的推導(dǎo):\lim_{x \to \infty} (1 + \frac{1}{x}) ^ x = e
  2. 將 -x 替換 x lim_{(-x) \to \infty}(1 + \frac{1}{-x})^{-x} = e
  3. lim_{(-x) \to \infty}(1 + \frac{1}{-x})^{-x} = e
  4. lim_{x \to \infty}(1 - \frac{1}{x})^x = \frac{1}{e}

我們?cè)購(gòu)牡谝徊糠值牡谖宀嚼^續(xù)向后:

  1. 變形得:(1 - [1 - (\frac{1}{m})^{m}]^{nk/m})^{k}
  2. 對(duì)于大 m 約等于:(1 - e^{-nk/m})^{k}

所以針對(duì)大 m酣藻,誤報(bào)率約為:(1 - e^{-nk/m})^{k}

我們通常要根據(jù) n 和 m 推導(dǎo)合適的 hash 個(gè)數(shù),為:k = \frac{m}{n}ln2鳍置。

如果需要根據(jù)誤報(bào)率來(lái)推導(dǎo)辽剧,此時(shí) k = \frac{m}{n}ln2,此時(shí)誤報(bào)率 {\displaystyle \varepsilon =\left(1-e^{-({\frac {m}{n}}\ln 2){\frac {n}{m}}}\right)^{{\frac { m}{n}}\ln 2}}税产∨陆危可以簡(jiǎn)寫(xiě)為:

{\displaystyle \ln \varepsilon =-{\frac {m}{n}}\left(\ln 2\right)^{2}.}

這導(dǎo)致:

{\displaystyle m=-{\frac {n\ln \varepsilon }{(\ln 2)^{2}}}}

所以 m 和 n 的最佳比值此時(shí)為:

{\displaystyle {\frac {m}{n}}=-{\frac {\log _{2}\varepsilon }{\ln 2}}\approx -1.44\log _{2}\varepsilon }

后面的部分我都是摘自 wiki:https://en.wikipedia.org/wiki/Bloom_filter偷崩。根據(jù)這些我們就可以實(shí)現(xiàn)自己的 Bloom filter。

  • 參考

https://en.wikipedia.org/wiki/Bloom_filter

實(shí)現(xiàn)

我們?cè)趯?shí)現(xiàn)的時(shí)候前提條件通常是:

  • 假陽(yáng)性 p 概率是多少
  • 要存的樣本空間多大

要求的就是上面公式里的 k 和 m撞羽。

  • m 告訴我們需要多少的 bit 位
  • k 告訴我們需要多少個(gè) hash 函數(shù)

按照公式:

  • m = -1.44nlog_{2}p

  • k = \frac{m}{n}ln2

大概實(shí)現(xiàn)如下:

// bloom.go
// Copyright 2021 hardcore-os Project Authors
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package utils

import "math"

// Filter is an encoded set of []byte keys.
type Filter []byte

// MayContainKey _
func (f Filter) MayContainKey(k []byte) bool {
    return f.MayContain(Hash(k))
}

func (f Filter) K() uint8 {
    return f[len(f) - 1]
}

// get 根據(jù) hash 值得到 filter 中某一位的值
func (f Filter) get(h uint32) uint8 {
    x, y := posInFilter(h, len(f) - 1)
    return uint8((f[x] >> y) & 1)
}

// set 根據(jù) hash 值將某一位置 1
func (f Filter) set(h uint32) {
    x, y := posInFilter(h, len(f) - 1)
    f[x] = f[x] | 1 << y
}

// MayContain returns whether the filter may contain given key. False positives
// are possible, where it returns true for keys not in the original set.
func (f Filter) MayContain(h uint32) bool {
    //Implement me here!!!
    //在這里實(shí)現(xiàn)判斷一個(gè)數(shù)據(jù)是否在bloom過(guò)濾器中
    //思路大概是經(jīng)過(guò)K個(gè)Hash函數(shù)計(jì)算阐斜,判讀對(duì)應(yīng)位置是否被標(biāo)記為1
    delta, k := h >> 17 | h << 15, f.K()
    for j := uint8(0); j < k; j ++ {
        if f.get(h) == 0 {
            return false
        }
        h += delta
    }
    return true
}

// posInFilter 根據(jù) hash 值計(jì)算此 hash 在 pos 的哪一個(gè)位置
// h 是 hash 值,filterLen 就是用byte數(shù)組中真正做做filter的長(zhǎng)度
func posInFilter(h uint32, filterLen int) (x, y int) {
    nBits :=  uint32(filterLen * 8)
    bitPos := h % nBits
    return int(bitPos / 8), int(bitPos % 8)
}

// NewFilter returns a new Bloom filter that encodes a set of []byte keys with
// the given number of bits per key, approximately.
//
// A good bitsPerKey value is 10, which yields a filter with ~ 1% false
// positive rate.
func NewFilter(keys []uint32, bitsPerKey int) Filter {
    return appendFilter(keys, bitsPerKey)
}

// BloomBitsPerKey returns the bits per key required by bloomfilter based on
// the false positive rate.
func BloomBitsPerKey(numEntries int, fp float64) int {
    //Implement me here!!!
    //閱讀bloom論文實(shí)現(xiàn)放吩,并在這里編寫(xiě)公式
    //傳入?yún)?shù)numEntries是bloom中存儲(chǔ)的數(shù)據(jù)個(gè)數(shù)智听,fp是false positive假陽(yáng)性率
    // 計(jì)算 m/n 根據(jù):https://en.wikipedia.org/wiki/Bloom_filter
    return int(-1.44 * math.Log2(fp) + 1)
}

func appendFilter(keys []uint32, bitsPerKey int) Filter {
    //Implement me here!!!
    //在這里實(shí)現(xiàn)將多個(gè)Key值放入到bloom過(guò)濾器中
    // TODO:系統(tǒng)檢查 bitsPerKey
    if bitsPerKey < 0 {
        bitsPerKey = 0
    }
    keyLen := len(keys)
    k := uint8(float64(bitsPerKey) * 0.69)
    if k < 1 {
        k = 1
    }

    if k > 30 {
        k = 30
    }

    nBits := bitsPerKey * keyLen

    // 如果 nBits 太小會(huì)有很高的 false positive
    if nBits < 64 {
        nBits = 64
    }

    // TODO:檢查 nBits 的上界

    nBytes := (nBits + 7) / 8
    // 最后一位
    filter := Filter(make([]byte, nBytes + 1))


    // 向 filter 中放入所有的 key
    for _, h := range keys {
        delta := h >> 17 | h << 15
        for j := uint8(0); j < k; j ++ {
            filter.set(h)
            h += delta
        }
    }

    filter[nBytes] = k
    return filter
}



// Hash implements a hashing algorithm similar to the Murmur hash.
func Hash(b []byte) uint32 {
    const (
        seed = 0xbc9f1d34
        m    = 0xc6a4a793
    )
    h := uint32(seed) ^ uint32(len(b))*m
    for ; len(b) >= 4; b = b[4:] {
        h += uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
        h *= m
        h ^= h >> 16
    }
    switch len(b) {
    case 3:
        h += uint32(b[2]) << 16
        fallthrough
    case 2:
        h += uint32(b[1]) << 8
        fallthrough
    case 1:
        h += uint32(b[0])
        h *= m
        h ^= h >> 24
    }
    return h
}
// bloom_test.go
// Copyright 2021 hardcore-os Project Authors
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils

import (
    "testing"
)

func (f Filter) String() string {
    s := make([]byte, 8*len(f))
    for i, x := range f {
        for j := 0; j < 8; j++ {
            if x&(1<<uint(j)) != 0 {
                s[8*i+j] = '1'
            } else {
                s[8*i+j] = '.'
            }
        }
    }
    return string(s)
}

func TestSmallBloomFilter(t *testing.T) {
    var hash []uint32
    for _, word := range [][]byte{
        []byte("hello"),
        []byte("world"),
    } {
        hash = append(hash, Hash(word))
    }

    f := NewFilter(hash, 10)
    got := f.String()
    // The magic want string comes from running the C++ leveldb code's bloom_test.cc.
    want := "1...1.........1.........1.....1...1...1.....1.........1.....1....11....."
    if got != want {
        t.Fatalf("bits:\ngot  %q\nwant %q", got, want)
    }

    m := map[string]bool{
        "hello": true,
        "world": true,
        "x":     false,
        "foo":   false,
    }
    for k, want := range m {
        got := f.MayContainKey([]byte(k))
        if got != want {
            t.Errorf("MayContain: k=%q: got %v, want %v", k, got, want)
        }
    }
}

func TestBloomFilter(t *testing.T) {
    nextLength := func(x int) int {
        if x < 10 {
            return x + 1
        }
        if x < 100 {
            return x + 10
        }
        if x < 1000 {
            return x + 100
        }
        return x + 1000
    }
    le32 := func(i int) []byte {
        b := make([]byte, 4)
        b[0] = uint8(uint32(i) >> 0)
        b[1] = uint8(uint32(i) >> 8)
        b[2] = uint8(uint32(i) >> 16)
        b[3] = uint8(uint32(i) >> 24)
        return b
    }

    nMediocreFilters, nGoodFilters := 0, 0
loop:
    for length := 1; length <= 10000; length = nextLength(length) {
        keys := make([][]byte, 0, length)
        for i := 0; i < length; i++ {
            keys = append(keys, le32(i))
        }
        var hashes []uint32
        for _, key := range keys {
            hashes = append(hashes, Hash(key))
        }
        f := NewFilter(hashes, 10)

        if len(f) > (length*10/8)+40 {
            t.Errorf("length=%d: len(f)=%d is too large", length, len(f))
            continue
        }

        // All added keys must match.
        for _, key := range keys {
            if !f.MayContainKey(key) {
                t.Errorf("length=%d: did not contain key %q", length, key)
                continue loop
            }
        }

        // Check false positive rate.
        nFalsePositive := 0
        for i := 0; i < 10000; i++ {
            if f.MayContainKey(le32(1e9 + i)) {
                nFalsePositive++
            }
        }
        if nFalsePositive > 0.02*10000 {
            t.Errorf("length=%d: %d false positives in 10000", length, nFalsePositive)
            continue
        }
        if nFalsePositive > 0.0125*10000 {
            nMediocreFilters++
        } else {
            nGoodFilters++
        }
    }

    if nMediocreFilters > nGoodFilters/5 {
        t.Errorf("%d mediocre filters but only %d good filters", nMediocreFilters, nGoodFilters)
    }
}

func TestHash(t *testing.T) {
    // The magic want numbers come from running the C++ leveldb code in hash.cc.
    testCases := []struct {
        s    string
        want uint32
    }{
        {"", 0xbc9f1d34},
        {"g", 0xd04a8bda},
        {"go", 0x3e0b0745},
        {"gop", 0x0c326610},
        {"goph", 0x8c9d6390},
        {"gophe", 0x9bfd4b0a},
        {"gopher", 0xa78edc7c},
        {"I had a dream it would end this way.", 0xe14a9db9},
    }
    for _, tc := range testCases {
        if got := Hash([]byte(tc.s)); got != tc.want {
            t.Errorf("s=%q: got 0x%08x, want 0x%08x", tc.s, got, tc.want)
        }
    }
}

  • 參考

測(cè)試代碼和實(shí)現(xiàn)代碼的框架來(lái)自:https://github.com/hardcore-os/corekv

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市渡紫,隨后出現(xiàn)的幾起案子到推,更是在濱河造成了極大的恐慌,老刑警劉巖惕澎,帶你破解...
    沈念sama閱讀 221,635評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件莉测,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡唧喉,警方通過(guò)查閱死者的電腦和手機(jī)捣卤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)八孝,“玉大人董朝,你說(shuō)我怎么就攤上這事「甚耍” “怎么了子姜?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,083評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)楼入。 經(jīng)常有香客問(wèn)我哥捕,道長(zhǎng),這世上最難降的妖魔是什么嘉熊? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,640評(píng)論 1 296
  • 正文 為了忘掉前任遥赚,我火速辦了婚禮,結(jié)果婚禮上阐肤,老公的妹妹穿的比我還像新娘凫佛。我一直安慰自己,他們只是感情好孕惜,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布愧薛。 她就那樣靜靜地躺著,像睡著了一般诊赊。 火紅的嫁衣襯著肌膚如雪厚满。 梳的紋絲不亂的頭發(fā)上府瞄,一...
    開(kāi)封第一講書(shū)人閱讀 52,262評(píng)論 1 308
  • 那天碧磅,我揣著相機(jī)與錄音碘箍,去河邊找鬼。 笑死鲸郊,一個(gè)胖子當(dāng)著我的面吹牛丰榴,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播秆撮,決...
    沈念sama閱讀 40,833評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼四濒,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了职辨?” 一聲冷哼從身側(cè)響起盗蟆,我...
    開(kāi)封第一講書(shū)人閱讀 39,736評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎舒裤,沒(méi)想到半個(gè)月后喳资,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,280評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡腾供,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評(píng)論 3 340
  • 正文 我和宋清朗相戀三年仆邓,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片伴鳖。...
    茶點(diǎn)故事閱讀 40,503評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡节值,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出榜聂,到底是詐尸還是另有隱情搞疗,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布峻汉,位于F島的核電站贴汪,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏休吠。R本人自食惡果不足惜扳埂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望瘤礁。 院中可真熱鬧阳懂,春花似錦、人聲如沸柜思。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,340評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)赡盘。三九已至号枕,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間陨享,已是汗流浹背葱淳。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,460評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工钝腺, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人赞厕。 一個(gè)月前我還...
    沈念sama閱讀 48,909評(píng)論 3 376
  • 正文 我出身青樓艳狐,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親皿桑。 傳聞我的和親對(duì)象是個(gè)殘疾皇子毫目,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • 1. 前言 Bloom Filter的名字早有耳聞,但一直沒(méi)看實(shí)現(xiàn)原理诲侮。今天乘地鐵時(shí)心血來(lái)潮看了算法镀虐,頓時(shí)被其簡(jiǎn)單...
    kophy閱讀 10,781評(píng)論 5 29
  • A Bloom filter is a data structure designed to tell you, ...
    Zihowe閱讀 288評(píng)論 0 0
  • What is a Bloom Filter? ??在任意的keys集合中,應(yīng)用一個(gè)算法并生成一個(gè)字節(jié)數(shù)組沟绪,這個(gè)字...
    薛少佳閱讀 8,207評(píng)論 0 3
  • 為什么需要布隆過(guò)濾器 想象一下遇到下面的場(chǎng)景你會(huì)如何處理: 手機(jī)號(hào)是否重復(fù)注冊(cè) 用戶(hù)是否參與過(guò)某秒殺活動(dòng) 偽造請(qǐng)求...
    ouyangan閱讀 1,208評(píng)論 0 0
  • 布隆過(guò)濾器 Bloom Filter 布隆過(guò)濾器粉私,用來(lái)判斷一個(gè)元素是否在集合中。它的特點(diǎn)是節(jié)省空間近零,但是有誤判诺核。有...
    周肅閱讀 4,610評(píng)論 0 5