1 min read

Naive Bayes in R

{r setup, include=FALSE} knitr::opts_chunk$set(eval = FALSE) 之前在datacamp上面学过一部分Naive Bayes,主要定位应用,基于R软件。

Naive Bayes可以帮助理解,先验概率$P(A)$和后验概率$P(A \cap B)$。

$$P(A \cap B) = \frac{P(B|A)}{P(B)} \cdot P(A)$$

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

$$P(钓鱼|经验)$$


$$P(A \cap B) = \frac{P(B|A)}{P(B)} \cdot P(A)$$

对公式进行变形,

$$P(y | X) = \frac{P(X|y)}{P(X)} \cdot P(y)$$

当$y=y_1$和$y=y_2$,我们会比较 $P(y=y_1 | X)$和$P(y=y_2 | X)$ ,来决定给定X下,两种情况概率大。

我们发现两者都包含$P(X)$,因此实际上$P(y=y_1 | X)$和$P(y=y_2 | X)$的比较,其实是比较 ${P(X|y=y_1)}{P(y)}$和${P(X|y=y_2)}{P(y)}$。

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

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

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

$$P(x_1|y) \cdot P(x_2|y) \cdot … \cdot P(x_n|y)$$

其中$X=[x_1,x_2,…,x_n]$。


naivebayes

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

<pre><code>> 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
</code></pre>

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

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


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

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

$$P(y|X) = \frac{P(y) \cdots P(X|y)}{P(X)}=\frac{P(y)}{P(X)} \prod_{i=1}^nP(x_i|y) $$