【问题标题】:R - Generate confusion matrix and ROC for model generated by multinomial_naive_bayes() functionR - 为 multinomial_naive_bayes() 函数生成的模型生成混淆矩阵和 ROC
【发布时间】:2021-02-25 08:23:25
【问题描述】:

我有一个包含许多因子/分类/名义列/变量/特征的数据集。我需要为此数据创建一个多项式朴素贝叶斯分类器。我尝试使用插入符号库,但我不认为这是在做多项式朴素贝叶斯,我认为它是在做高斯朴素贝叶斯,详情 here。我现在发现了 multinomial_naive_bayes() 似乎很完美。它似乎可以处理预测变量中的空值和只有 1 个值的变量而不会抱怨。

问题是,我不知道如何对 multinomial_naive_bayes() 函数生成的模型进行“后处理/分析”。我想在模型以及预测输出与测试数据上获得插入符号样式的混淆矩阵,以评估分类器。我还想生成 ROC 曲线。我该怎么做?

我已经包含了下面 multinomial_naive_bayes() 文档中的示例/参考/示例,我将如何更新此代码以获得我的混淆矩阵和 ROC 曲线。

来自:R Package 'naivebayes',部分:multinomial_naive_bayes pg 10

library(naivebayes)

### Simulate the data:
cols <- 10 ; rows <- 100
M <- matrix(sample(0:5, rows * cols, TRUE, prob = c(0.95, rep(0.01, 5))), nrow = rows, ncol = cols)
y <- factor(sample(paste0("class", LETTERS[1:2]), rows, TRUE, prob = c(0.3,0.7)))
colnames(M) <- paste0("V", seq_len(ncol(M)))
laplace <- 1

### Train the Multinomial Naive Bayes
mnb <- multinomial_naive_bayes(x = M, y = y, laplace = laplace)
summary(mnb)
    
# Classification
head(predict(mnb, newdata = M, type = "class")) # head(mnb %class% M)

# Posterior probabilities
head(predict(mnb, newdata = M, type = "prob")) # head(mnb %prob% M)

# Parameter estimates
coef(mnb)

【问题讨论】:

    标签: r r-caret naivebayes


    【解决方案1】:

    您可以使用插入符号函数confusionMatrix:

    library(caret)
    pred = predict(mnb, newdata = M, type = "class")
    confusionMatrix(table(pred,y))
    
    Confusion Matrix and Statistics
    
            y
    pred     classA classB
      classA     10      3
      classB     20     67
    

    或者如果因子水平相同:

    confusionMatrix(pred,y)
    

    对于ROC曲线,需要提供预测的概率:

    library(pROC)
    roc_ = roc(y,predict(mnb, newdata = M, type ="prob")[,2])
    
    plot(roc_)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-15
      • 2018-12-26
      • 2016-02-05
      • 2021-07-29
      • 2017-10-21
      • 2022-01-04
      • 2013-03-18
      • 2018-10-25
      相关资源
      最近更新 更多