我正在尝试使用 e1071 包中的 naiveBayes()
函数。当我添加一个非零的 laplace
参数时,我的概率估计结果没有变化,我不明白这是为什么。
例子:
library(e1071)# 生成数据train.x <- data.frame(x1=c(1,1,0,0), x2=c(1,0,1,0))train.y <- factor(c("cat", "cat", "dog", "dog"))test.x <- data.frame(x1=c(1), x2=c(1))# 无 Laplace 平滑classifier <- naiveBayes(x=train.x, y=train.y, laplace=0)predict(classifier, test.x, type="raw") # 返回 (1, 0.00002507)# 有 Laplace 平滑classifier <- naiveBayes(x=train.x, y=train.y, laplace=1)predict(classifier, test.x, type="raw") # 返回 (1, 0.00002507)
由于所有“dog”类的训练实例的 x1 值为 0,我期望在这种情况下概率会发生变化。为了验证这一点,这里是使用 Python 的相同示例
Python 示例:
import numpy as npfrom sklearn.naive_bayes import BernoulliNBtrain_x = pd.DataFrame({'x1':[1,1,0,0], 'x2':[1,0,1,0]})train_y = np.array(["cat", "cat", "dog", "dog"])test_x = pd.DataFrame({'x1':[1,], 'x2':[1,]})# alpha (即 laplace = 0)classifier = BernoulliNB(alpha=.00000001)classifier.fit(X=train_x, y=train_y)classifier.predict_proba(X=test_x) # 返回 (1, 0)# alpha (即 laplace = 1)classifier = BernoulliNB(alpha=1)classifier.fit(X=train_x, y=train_y)classifier.predict_proba(X=test_x) # 返回 (.75, .25)
为什么使用 e1071 时我会得到这个意外结果?
回答:
Laplace 估计只适用于分类特征,而不适用于数值特征。你可以在源代码中找到:
## 估计函数est <- function(var) if (is.numeric(var)) { cbind(tapply(var, y, mean, na.rm = TRUE), tapply(var, y, sd, na.rm = TRUE)) } else { tab <- table(y, var) (tab + laplace) / (rowSums(tab) + laplace * nlevels(var)) }
对于数值,使用的则是高斯估计。因此,将你的数据转换为因子,你就可以继续使用了。
train.x <- data.frame(x1=c("1","1","0","0"), x2=c("1","0","1","0"))train.y <- factor(c("cat", "cat", "dog", "dog"))test.x <- data.frame(x1=c("1"), x2=c("1"))# 无 Laplace 平滑classifier <- naiveBayes(x=train.x, y=train.y, laplace=0)predict(classifier, test.x, type="raw") # 返回 (100% 为 dog)# 有 Laplace 平滑classifier <- naiveBayes(x=train.x, y=train.y, laplace=1)predict(classifier, test.x, type="raw") # 返回 (75% 为 dog)