【机器学习】笔记内容002:贝叶斯算法(理论+实战)

概述

本文用于记录传统机器学习算法之Bayers算法,一方面加深知识理解,另一方面作为自己的参考和学习资料,如果文章中错误性知识,欢迎评论指出!谢谢!!!

A u t h o r : S o p h e r Author: Sopher Author:Sopher
I d e n t i f i c a t i o n : S t u d e n t Identification: Student Identification:Student
D e s c r i p t i o n : Description: Description: 他常在深夜调试!因为她热爱这份职业!

一 贝叶斯算法概述

1.贝叶斯算法被应用于解决:正向概率和逆向概率(以袋中的黑白求作出解释)
①正向概率:已知袋中黑球和白球的数量,问模中其中一球的概率
②逆向概率:不知道袋中的黑白球比例,随机从袋中摸出一个(或多个)球,问通过这个操作能对袋中的黑白求比例做出什么猜测?
2.理解:对于复杂环境,通过局部推出整体的条件;即是将复杂问题转换为简单问题进行求解

二 贝叶斯公式

1 贝叶斯公式

P ( A ∣ B ) = P ( B ∣ A ) ∗ P ( A ) P ( B ) P(A|B)=\frac{P(B|A)*P(A)}{P(B)} P(AB)=P(B)P(BA)P(A)

2 举例解释贝叶斯公式

问题:学校中有学生 M M M人,其中理科生( S c i e n c e s t u d e n t s Science students Sciencestudents)为 60 % 60\% 60%,文科生( L i t e r a t u r e s t u d e n t s Literature students Literaturestudents)为 40 % 40\% 40%,现在要求所有的 S c i e n c e s t u d e n t s Science students Sciencestudents 均要学习计算机,而文科生中要求 30 % 30\% 30%需要学习计算机。问:在学习计算机中,文科生所占比例?
求解过程:
① 学习计算机理科生: S _ c o m p u t e r = M ∗ P ( S ) ∗ P ( c o m p u t e r ∣ S ) S\_computer=M*P(S)*P(computer|S) S_computer=MP(S)P(computerS)
其中:

  • S:理科生
  • P(S):学校中理科生概率比
  • P(computer|S):理科生中学习计算机概率

② 学习计算机文科生: L _ c o m p u t e r = M ∗ P ( L ) ∗ P ( c o m p u t e r ∣ L ) L\_computer=M*P(L)*P(computer|L) L_computer=MP(L)P(computerL)
其中:

  • L:文科生
  • P(L):学校中文科生概率比
  • P(computer|L):文科生中学习计算机概率

③ 总学习计算机人数: A l l _ c o m p u t e r = L _ c o m p u t e r + S _ c o m p u t e r All\_computer = L\_computer + S\_computer All_computer=L_computer+S_computer
④ 学习计算机中,文科生占比: P ( L | c o m p u t e r ) = L _ c o m p u t e r / A l l _ c o m p u t e r P\left(L\middle| c o m p u t e r\right)=L\_computer/All\_computer P(Lcomputer)=L_computer/All_computer
⑤ 对④中公式化简:
P ( L | c o m p u t e r ) = P ( L ) ∗ P ( c o m p u t e r ∣ L ) ( P ( S ) ∗ P ( c o m p u t e r ∣ S ) + P ( L ) ∗ P ( c o m p u t e r ∣ L ) ) P\left(L\middle| c o m p u t e r\right)=\frac{P(L)\ast P(computer|L)}{(P(S)\ast P(computer|S)+P(L)\ast P(computer|L))} P(Lcomputer)=(P(S)P(computerS)+P(L)P(computerL))P(L)P(computerL)

进一步观察说明:
⑥ 求解学习 c o m p u t e r computer computer中,文科生的比例和学校的总人数 M M M无关的
P ( c o m p u t e r ) = P ( S ) ∗ P ( c o m p u t e r ∣ S ) + P ( L ) ∗ P ( c o m p u t e r ∣ L ) P(computer) = P(S)\ast P(computer|S)+P(L)\ast P(computer|L) P(computer)=P(S)P(computerS)+P(L)P(computerL),即为学习计算机的总人数
P ( c o m p u t e r , L ) = P ( L ) ∗ P ( c o m p u t e r ∣ L ) P(computer,L) = P(L)\ast P(computer|L) P(computer,L)=P(L)P(computerL),即为文科生中学习计算机的人数
因此,对⑤中公式进行进一步的转换:
P ( L ∣ c o m p u t e r ) = P ( c o m p u t e r , L )   P ( c o m p u t e r ) P(L|computer)=\frac{P(computer,L)\ }{P(computer)} P(Lcomputer)=P(computer)P(computer,L) 

三 实例分析

1 Bayers单词拼写纠错分析

问题: Sopher开发一款Sopher lexicon用于单词纠正, 现词库中有单词 H = h 1 , h 2 , . . . , h n H={h_1,h_2,...,h_n} H=h1,h2,...,hn, 现在用户penny输入错误单词D(D不在Sopher lexicon中),我们需要用词库中单词去猜测penny真正想输入的单词是什么?
过程分析
① 问题结合Bayers公式可以转换成数学符号表示:
P ( h ∣ D ) = P ( h ) ∗ P ( D ∣ h ) P ( D ) P(h|D)=\frac{P(h)*P(D|h)}{P(D)} P(hD)=P(D)P(h)P(Dh)
其中:

  • h表示统一表示 H = h 1 , h 2 , . . . , h n H={h_1,h_2,...,h_n} H=h1,h2,...,hn中的任意单词
  • P ( h ) P(h) P(h)表示单词h在词库中出现的概率,我们称为先验概率
  • D表示观察数据,即penny输入的单词
  • P ( D ) P(D) P(D)表示输入纠错单词中D的概率
  • P ( D ∣ h ) P(D|h) P(Dh)表示输入单词和词库单词h之间的相似度,类似键盘中不同单词的间距

② 因为单词D是penny输入的,且纠错过程是我们假设考虑单个错误性单词,因此 P ( D ) P(D) P(D)表示常量1(或者我们理解:输入错误单词P(D)对于每一种猜测 P ( h ∣ D ) P(h|D) P(hD)都是一样的,因此我们忽略P(D)不看)。进一步,我们对公式进行修改,如下:
P ( h ∣ D ) = P ( h ) ∗ P ( D ∣ h ) P(h|D)=P(h)*P(D|h) P(hD)=P(h)P(Dh)
③ 此时再衡量 P ( h ∣ D ) P(h|D) P(hD),发现只和两种因素相关:

  • 先验概率 P ( h ) : P(h): P(h)为单词的选择提供指示作用
  • P ( D ∣ h ) : P(D|h): P(Dh):表示猜测单词h就是代表用户penny想输入单词的可能性大小,即表示相似性

④ 通过比较不同单词 h h h P ( h ∣ D ) P(h|D) P(hD)的大小,确定预测单词h表示penny想输入的单词
⑤ 模型比较的方法

  • 最大似然估计: P ( D ∣ h ) P(D|h) P(Dh)大的占有优势,理解成与观察数据最相似的最优优势
  • 奥卡姆剃刀: P ( h ) P(h) P(h)较大的占有优势,即词库中单词h出现次数做多的

2 Bayers邮件过滤分析

问题: Sopher邮件中转站致力于邮件的刷选和分发,现在Sopher接收到一个邮件D,邮件由n个单词构成,即表示 D = d 1 , d 2 , . . . , d n D={d_1,d_2,...,d_n} D=d1,d2,...,dn他需要进行判断该邮件是否为垃圾邮件,其中我们规定是有 h + h_+ h+表示垃圾邮件不进行分发, h − h_- h表示正常邮件进行分发。
过程分析:
① 仍然结合Bayers公式,将接收邮件为垃圾邮件概率表示如下:
P ( h + ∣ D ) = P ( h + ) ∗ P ( D ∣ h + ) P ( D ) P(h_+|D)=\frac{P(h_+)*P(D|h_+)}{P(D)} P(h+D)=P(D)P(h+)P(Dh+)
其中:

  • P ( h + ) : P(h_+): P(h+):先验概率,表示邮件中垃圾邮件的概率,可以通过历史接收邮件中进行求取
  • P ( D ∣ h + ) : P(D|h_+): P(Dh+):垃圾邮件中和目前接收的邮件相似的概率,也可以表示为: P ( d 1 , d 2 , . . . , d n ∣ h + ) P(d_1,d_2,...,d_n|h_+) P(d1,d2,...,dnh+),理解就是垃圾邮件中出现这些单词的概率大小
  • P ( D ) : P(D): P(D):表示接收邮件为D的概率,但我们是单独邮件考虑,因此不考虑 P ( D ) P(D) P(D)

② 对于接收邮件,不能以邮件与垃圾邮件的全部单词都相同,才认为该邮件是垃圾邮件。我们认为邮件D中出现垃圾邮件中的单词达到一定概率,则认为其为垃圾邮件,因此我们对 P ( d 1 , d 2 , . . . , d n ∣ h + ) P(d_1,d_2,...,d_n|h_+) P(d1,d2,...,dnh+)进一步展开表示为:
P ( d 1 , d 2 , . . . , d n ∣ h + ) = P ( d 1 ∣ h + ) ∗ P ( d 2 ∣ d 1 , h + ) ∗ P ( d 3 ∣ d 1 , d 2 , h + ) . . . ∗ P ( d n ∣ d 1 , d 2 , . . . , d n − 1 , h + ) P(d_1,d_2,...,d_n|h_+)=P(d_1|h_+)*P(d_2|d_1,h_+)*P(d_3|d_1,d_2, h_+)...*P(d_n|d_1,d_2,...,d_{n-1},h_+) P(d1,d2,...,dnh+)=P(d1h+)P(d2d1,h+)P(d3d1,d2,h+)...P(dnd1,d2,...,dn1,h+)
③对于 P ( D ∣ h + ) P(D|h_+) P(Dh+)展开式,由于单词之间是相互独立没有联系的。此时,问题转化为Naive Bayers:假设特征之间是完全独立的。因此,我们只需要统计每个单词 d i d_i di在垃圾邮件 h + h_+ h+出现的频率(即,垃圾邮件中出现单词 d 1 , d 2 , . . . d n d_1,d_2,...d_n d1,d2,...dn的频率),进一步公式表示如下:
P ( D ∣ h + ) = P ( d 1 ∣ h + ) ∗ P ( d 2 ∣ h + ) ∗ P ( d 3 ∣ h + ) . . . ∗ P ( d n ∣ h + ) P(D|h_+)=P(d_1|h_+)*P(d_2|h_+)*P(d_3| h_+)...*P(d_n|h_+) P(Dh+)=P(d1h+)P(d2h+)P(d3h+)...P(dnh+)

四 实战代码

一 单词拼写检查器

1. 代码说明

  • ①在3.1中我们已经对单词过滤过程进行详细的说明,这里我们在进行回顾一下
  • ②假设输入单词我们设置为 w w w,词库中存在的单词使用 c c c表示,依据贝叶斯公式,我们的求解目标可以装换为如下的公式表示:
    a r g m a x ( P ( c ∣ w ) ) = a r g m a x ( P ( c ) ∗ P ( w ∣ c ) P ( w ) ) argmax(P(c|w)) = argmax(\frac{P(c)*P(w|c)}{P(w)}) argmax(P(cw))=argmax(P(w)P(c)P(wc))
    其中:
    • P ( c ∣ w ) : P(c|w): P(cw): 表示用户输入单词 w w w,但实际想输入单词为 c c c的概率
    • P ( w ∣ c ) : P(w|c): P(wc): 表示用户想要单词输入单词 c c c,但误输入成单词 w w w的概率
    • P ( c ) : P(c): P(c): 表示词库中存在单词c的概率/频率
    • P ( w ) : P(w): P(w): 常量
    • 说明:对于 P ( c ∣ w ) P(c|w) P(cw) P ( w ∣ c ) P(w|c) P(wc)的说明可能有点相似,但实际是有区别的,大家可细品!!本质可以理解: P ( c ∣ w ) P(c|w) P(cw)不好求,而 P ( w ∣ c ) P(w|c) P(wc)容易求出!!
  • 求解出最大的概率 P ( c ∣ w ) P(c|w) P(cw),则认为 c c c为用户penny想输入的单词

2. 代码实现

import re, collections

'''
function: spelling check machine
methods: Bayers methods
'''

def words(text):
    return re.findall('[a-z]+', text.lower())  # fetch words changed lower case  matching regular expression:[a-z]+

def train(features):
    model = collections.defaultdict(lambda :1)  # dict generate: make input word appear once(probability is small) although the word not in lexicon

    for feature in features:
        model[feature] += 1
    return model
numWords = train(words(open('big.txt').read()))

alphabet = 'abcdefghijklmnopqrstuvwxyz'
def edits(word):
    '''
    function: set distance equal 1 between input words with true words, get new form for input words
    '''
    n = len(word)
    return set([word[0:i] + word[i+1:] for i in range(n)] +  # delete single letter
               [word[0:i] + word[i+1] + word[i] + word[i+2:] for i in range(n - 1)] +   # transpose adjacent letter
               [word[0:i] + c + word[i+1:] for i in range(n) for c in alphabet] +  # alteration single letter with 26 letter
               [word[0:i] + c + word[i:] for i in range(n + 1) for c in alphabet]  # insert 26 letter
               )

def know_edits(word):
    '''
    function: set distance equal 2 between e2 and e1, makesure e2 is true
    '''
    return set(e2 for e1 in edits(word) for e2 in edits(e1) if e2 in numWords)

def know(word):
    return set(w for w in word if w in numWords)

def correct(word):
    candidates = know([word]) or know(edits(word)) or know_edits(word) or [word]  # stop when satisfy one 
    return max(candidates, key=lambda w : numWords[w])

result1 = correct("tha")
print("输入单词为tha,拼写检查器纠错后单词为:", result1)
result2 = correct("mrow")
print("输入单词为mat,拼写检查器纠错后单词为:", result2)

测试结果如下:

输入单词为tha,拼写检查器纠错后单词为: the
输入单词为mat,拼写检查器纠错后单词为: grow

3. 资料说明
①文中所有big.txt文件获取路径:https://github.com/dscape/spell
②具体方式:将路径中的项目使用Git或者Download ZIP形式下载到本地,具体文件所在在目录:test->resources->big.txt

二 新闻分类

"""
    朴素贝叶斯算法进行文本分类
    :return:None
"""
from sklearn.datasets import fetch_20newsgroups
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report

def naveibayes():
    # 加载新闻数据
    news = fetch_20newsgroups(subset= "all")
    # 数据分割
    x_train, x_test, y_train, y_test = train_test_split(news.data, news.target, test_size= 0.25)

    # print(x_train)
    # 对数据集进行特征抽取(字符串数据)
    tf = TfidfVectorizer()
    x_train = tf.fit_transform(x_train)
    x_test = tf.transform(x_test)
    print(tf.get_feature_names())    # 获取特征抽取的特征名
    # 进行朴素贝叶斯算法
    mlt = MultinomialNB(alpha = 1.0)
    print(x_train.toarray())
    mlt.fit(x_train, y_train)
    # 对训练集特征值进行预测
    y_predict = mlt.predict(x_test)
    print("训练集预测结果为:", y_predict)
    print("模型的准确率:", mlt.score(x_test, y_test))
    # 精确率和召回率
    print("每个类别的精确率和召回率:")
    print(classification_report(y_test,y_predict,target_names= news.target_names))

    return None

if __name__ == "__main__":
    naveibayes()

Q W Q , I   w i l l   s u c c e e d   u n t i l   s u c c e s s !!!! QWQ, I\space will\space succeed\space until\space success!!!! QWQ,I will succeed until success!!!!

  • 5
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chuckie今天也要学习!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值