贝叶斯定理在拼写检查中的应用

版权声明:本文为博主原创文章,转载请声明出处。 https://blog.csdn.net/GnahzNib/article/details/70243220

贝叶斯定理

  • 条件概率

    通常条件概率表示为 P(A|B) ,表示在给定B条件下A事件发生的概率。

  • 联合概率

    两个事件同时发生的概率,表示为 P(A,B) ,事件A,B互相独立时有 P(AB)=P(A)P(B)
    通常意义下,联合概率表示为 P(A,B)=P(A)P(B|A)

  • 贝叶斯定理

    由联合概率乘法交换律可得:

    P(A,B)=P(B,A)

    又因为:
    P(A,B)=P(A)P(B|A)
    P(B,A)=P(B)P(A|B)

    所以可得:
    P(A)P(B|A)=P(B)P(A|B)

    即:
    P(AB)=P(A)P(BA)P(B)

    P(A) : 称为先验概率
    P(A|B) : 称为后验概率
    P(B|A) : 称为似然度
    P(B) : 称为标准化常量

    • 贝叶斯定理在拼写检查中的应用
      先看一个一段代码(出自google工程师之手)
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('big.txt').read()))

def P(word, N=sum(WORDS.values())): 
    "Probability of `word`."
    return WORDS[word] / N

def correction(word): 
    "Most probable spelling correction for word."
    return max(candidates(word), key=P)

def candidates(word): 
    "Generate possible spelling corrections for word."
    return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words): 
    "The subset of `words` that appear in the dictionary of WORDS."
    return set(w for w in words if w in WORDS)

def edits1(word):
    "All edits that are one edit away from `word`."
    letters    = 'abcdefghijklmnopqrstuvwxyz'
    splits     = [(word[:i], word[i:])    for i in range(len(word) + 1)]
    deletes    = [L + R[1:]               for L, R in splits if R]
    transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
    replaces   = [L + c + R[1:]           for L, R in splits if R for c in letters]
    inserts    = [L + c + R               for L, R in splits for c in letters]
    return set(deletes + transposes + replaces + inserts)

def edits2(word): 
    "All edits that are two edits away from `word`."
    return (e2 for e1 in edits1(word) for e2 in edits1(e1))

运行情况如下:

correction('lates')
Out[1]: 'later'

Q: 当你输入一个单词(如lates)在错误的情况下,该错误单词对应的所有正确的单词(latelatestlattes、…)有很多,但是程序怎么猜测你最有可能想输入的是哪个单词。为什么程序返回的是later
A: 当你输入lates时(错误的输入用w表示),所有可能正确的单词中(c表示正确的结果),使得在给出错误输入lates时找到c中可能最大的正确单词,用条件概率表示如下:

argmaxP(c|w)

贝叶斯定理表示为:
P(cw)=P(c)P(wc)P(w)

P(cw) 取最大值时所对应的 c就是你可能要输入的那个正确单词。

猜你喜欢

转载自blog.csdn.net/GnahzNib/article/details/70243220