在python sklearn与R bnlearn中运行朴素贝叶斯的不同结果

时间:2019-01-29 22:52:16

标签: python r machine-learning naivebayes

我在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

为什么会有如此大的差异?

1 个答案:

答案 0 :(得分:0)

您在R和Python中定义的管道不同:

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