使用非零 Laplace 参数时,naiveBayes 产生意外结果(e1071 包)

我正在尝试使用 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)

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注