1 min read

Naive Bayes in R

之前在datacamp上面学过一部分Naive Bayes,主要定位应用,基于R软件。

Naive Bayes可以帮助理解,先验概率P(A)和后验概率P(AB)

P(AB)=P(B|A)P(B)P(A)

实际中的应用是, 比如我们到河边钓鱼,根本就看不清楚河里哪里有鱼或者没鱼,似乎只能随机选择,但实际上我们会根据贝叶斯方法,利用以往积累经验找一个回水湾区开始垂钓。这就是我们根据先验知识进行主观判断,在钓过以后对这个地方有了更多了解,然后再进行选择。所以,在我们认识事物不全面的情况下,贝叶斯方法是一种非常理性且科学的方法。 (封杀这个公式,AI智商将为零)

P(|)


P(AB)=P(B|A)P(B)P(A)

对公式进行变形,

P(y|X)=P(X|y)P(X)P(y)

y=y1y=y2,我们会比较 P(y=y1|X)P(y=y2|X) ,来决定给定X下,两种情况概率大。

我们发现两者都包含P(X),因此实际上P(y=y1|X)P(y=y2|X)的比较,其实是比较 P(X|y=y1)P(y)P(X|y=y2)P(y)

P(X|y)P(y)(X,y)的联合分布,也就是Xy共同发生的概率。

所以说,朴素贝叶斯分类器的核心虽然是贝叶斯公式,但是其计算某样本的各类别的可能性时,实际上计算出的不是各类别的后验概率,而是各类别y与该样本特征X的联合概率P(X,y)

按照朴素贝叶斯的独立性假设,P(X|y)P(y)中的P(X|y)可以展开为:

P(x1|y)P(x2|y)...P(xn|y)

其中X=[x1,x2,...,xn]


naivebayes

主要使用的包为naivebayes,举个例子

> library(naivebayes)
> 
> # Build the location prediction model
> locmodel <- naive_bayes(location ~ daytype, data = where9am)
> 
# Obtain the predicted probabilities for Thursday at 9am
predict(locmodel, newdata = thursday9am , type = "prob")

# Obtain the predicted probabilities for Saturday at 9am
predict(locmodel, newdata = saturday9am , type = "prob")
> 
> locmodel
===================== Naive Bayes ===================== 
Call: 
naive_bayes.formula(formula = location ~ daytype, data = where9am)

A priori probabilities: 

appointment      campus        home      office 
 0.01098901  0.10989011  0.45054945  0.42857143 

Tables: 
         
daytype   appointment    campus      home    office
  weekday   1.0000000 1.0000000 0.3658537 1.0000000
  weekend   0.0000000 0.0000000 0.6341463 0.0000000

可以看到贝叶斯方程中Y=f(X)Xdaytype, 是一个分类变量,有两种情况weekdayweekendYlocation,是一个分类变量,有四种情况appointmentcampushomeoffice

因此贝叶斯可以处理多分类问题。


一文读懂贝叶斯分类算法(附学习资源)

之所以叫朴素贝叶斯,是因为采用了属性条件独立性假设,就是假设每个属性独立地对分类结果产生影响。即有下面的公式:

P(y|X)=P(y)P(X|y)P(X)=P(y)P(X)i=1nP(xi|y)