使用非零 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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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