【问题标题】:Different results running naive Bayes in Python sklearn vs. R bnlearn在 Python sklearn 与 R bnlearn 中运行朴素贝叶斯的不同结果
【发布时间】:2019-06-23 03:47:06
【问题描述】:

我在 python 和 R 中都尝试了朴素贝叶斯,得到了不同的 AUROC 值。为什么会这样?

R 代码:

library(bnlearn)
library(pROC)
library(tm)

corpus <- VCorpus(VectorSource(paste(data$TEXT, sep = ' ')))
dtm <- DocumentTermMatrix(corpus, control = list(tolower = TRUE,
                                  removeNumbers = FALSE,
                                  stopwords = TRUE,
                                  removePunctuation = TRUE,
                                  stemming = TRUE))
convert_codes <- function(x) { x <- ifelse(x > 0, 1, 0) }
dtm <- apply(dtm, MARGIN = 2,convert_codes) 
dtm <- as.data.frame(dtm)

model <- naive.bayes(dtm, approval, colnames(dtm)[-length(dtm)])


preds <- predict(model, dtm, prior = c(0.5, 0.5), prob = TRUE)
data$SCORE <- t(attr(preds, "prob"))[,2]
data$SCORE[is.nan(data$SCORE)] <- 0
print(auc(data$APPROVAL, data$SCORE))

结果 = 0.93

Python 代码:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import MultinomialNB

pipe = Pipeline([
    ('vectorizer', CountVectorizer()),
    ('model', MultinomialNB())
])

pipe.fit(data["TEXT"], data["APPROVAL"])
preds = pipe.predict_proba(data["TEXT"])
print(roc_auc_score(data["APPROVAL"], preds[:,1]))

结果 = 0.76

为什么会有这么大的差异?

【问题讨论】:

  • 顺便说一句,从原始标题中,有人不知道您在问什么——可能是关于速度的差异,可能是关于代码大小的差异,可能是问如何将某些内容从一个转移到另一个,等等。请尝试确保问题标题不仅描述了您所询问的一般主题,而且实际上描述了 问题本身,并且具有足够的特异性else 无需点击就可以了解他们是否有同样的问题。
  • 对不起。我会尝试寻找更长更详细的标题。

标签: python r machine-learning naivebayes


【解决方案1】:

你在 R 和 Python 中定义的管道不一样:

  • 在 R 中,DocumentTermMatrix 的 weighting 参数默认为 weightTf,因此不考虑 idf 组件。
  • 在 Python 中,TfidfVectorizer 具有默认参数 use_idf=True,因此它使用 idf 组件。

【讨论】:

  • 我在 Python 中也使用了 CountVectorizer,得到了类似的结果。
猜你喜欢
  • 2018-12-15
  • 2021-07-16
  • 2018-12-24
  • 1970-01-01
  • 2011-04-08
  • 1970-01-01
  • 2013-11-24
  • 2020-02-28
  • 2021-10-18
相关资源
最近更新 更多