预测三分类变量模型的ROC介绍

我们对Logistics回归很熟悉,预测变量y为二分类变量,然后对预测结果进行评估,会用到2*2 Matrix,计算灵敏度、特异度等及ROC曲线,判断模型预测准确性。

但是如果遇到y为三分类变量,那么会得到3*3 Matrix 那该选用什么指标进行评估呢?

答案:macro-average and micro-average

接下来,我们将介绍如何建立模型预测三分类变量,及对模型准确性进行评估。

1.模型构建

我们根据 iris数据集中的 Species三分类变量,建立多元回归模型,根据花的特征预测Species种类,其中我们添加xv新变量;
首先我们对 iris数据集进行拆分成 Training与Testing两个数据集,Training用于模型构建。

# https://stackoverflow.com/questions/59205776/random-forest-svm-and-multinomial-logistic-regression-with-r

library(tidyverse)
library(randomForest)
set.seed(123)
head(iris)
df=iris %>% mutate(xv=as.factor(ifelse(rnorm(150,3,4)<3,"Yes","No"))) # new predictor
## split da
split1= sample(c(rep(0, 0.7 * nrow(df)), rep(1, 0.3 * nrow(df)))) 
train <- df[split1 == 0, ]   
test <- df[split1 == 1, ]  

## Model LM
library(nnet)
fit1 = multinom(Species~.,data=train)
summary(fit1)

fit1结果解读比二分类多一个分类。参照OR的解释。

2.观测值VS预测值-Matrix

构建完模型fit1后,需要对testing 数据进行预测,然后我们创建一个真实值与预测值的矩阵。

## Model Prediction
pre=predict(fit1,test)
dfpre=tibble(actual=test$Species,predicted=pre)
table(dfpre)

            predicted
actual       setosa versicolor virginica
  setosa         13          0         0
  versicolor      0         13         0
  virginica       0          1        18

3.Performance Measures

接下来对该矩阵进行分析,需要预先对矩阵的一些参数进行计算;为后续的
Accuracy, precision, F1等。
Source: https://www.r-bloggers.com/2016/03/computing-classification-evaluation-metrics-in-r/

## basic variables
n = sum(cm) # number of instances
nc = nrow(cm) # number of classes
diag = diag(cm) # number of correctly classified instances per class 
rowsums = apply(cm, 1, sum) # number of instances per class
colsums = apply(cm, 2, sum) # number of predictions per class
p = rowsums / n # distribution of instances over the actual classes
q = colsums / n # distribution of instances over the predicted classes

## Accuracy
accuracy = sum(diag) / n 
accuracy 
precision = diag / colsums 
recall = diag / rowsums 
f1 = 2 * precision * recall / (precision + recall) 
data.frame(precision, recall, f1) 

## Macro
macroPrecision = mean(precision)
macroRecall = mean(recall)
macroF1 = mean(f1)
data.frame(macroPrecision, macroRecall, macroF1)

上述计算过程比较繁琐,有没有一键输出的,有!接下来是一键输出

3.1 Performance Measures 一键输出

这里使用 Evaluate 函数进行输出,其中Evaluate代码见连接或后台私信。 Source:https://github.com/saidbleik/Evaluation/blob/master/eval.R

results = Evaluate(actual=df3$ya, predicted=xa)
results
## output
$ConfusionMatrix
            Predicted
Actual       setosa versicolor virginica
  setosa         13          0         0
  versicolor      0         13         0
  virginica       0          1        18

$Metrics
                                setosa versicolor virginica
Accuracy                     0.9777778  0.9777778 0.9777778
Precision                    1.0000000  0.9285714 1.0000000
Recall                       1.0000000  1.0000000 0.9473684
F1                           1.0000000  0.9629630 0.9729730
MacroAvgPrecision            0.9761905  0.9761905 0.9761905
MacroAvgRecall               0.9824561  0.9824561 0.9824561
MacroAvgF1                   0.9786453  0.9786453 0.9786453
AvgAccuracy                  0.9851852  0.9851852 0.9851852
MicroAvgPrecision            0.9777778  0.9777778 0.9777778
MicroAvgRecall               0.9777778  0.9777778 0.9777778
MicroAvgF1                   0.9777778  0.9777778 0.9777778
MajorityClassAccuracy        0.4222222  0.4222222 0.4222222
MajorityClassPrecision       0.0000000  0.0000000 0.4222222
MajorityClassRecall          0.0000000  0.0000000 1.0000000
MajorityClassF1              0.0000000  0.0000000 0.5937500
Kappa                        0.9662162  0.9662162 0.9662162
RandomGuessAccuracy          0.3333333  0.3333333 0.3333333
RandomGuessPrecision         0.2888889  0.2888889 0.4222222
RandomGuessRecall            0.3333333  0.3333333 0.3333333
RandomGuessF1                0.3095238  0.3095238 0.3725490
RandomWeightedGuessAccuracy  0.3451852  0.3451852 0.3451852
RandomWeightedGuessPrecision 0.2888889  0.2888889 0.4222222
RandomWeightedGuessRecall    0.2888889  0.2888889 0.4222222
RandomWeightedGuessF1        0.2888889  0.2888889 0.4222222

4.ROC Curves Across Multi-Class Classifications

当然我们也可以绘制 The ROC curves of micro-average and macro-average, indicating the overall distinguishing ability of the three-class classification. 但是需要分几个步骤进行:

  1. 我们原来的预测值输出是Species的分类结果,这部分我们需要输出对各种类别的概率值。
  2. 哑变量设置,将我们的 testing数据集中Species分类改成哑变量
  3. 计算 macro/micro。并绘制ROC曲线
    Source:https://mran.microsoft.com/snapshot/2018-02-12/web/packages/multiROC/vignettes/my-vignette.html

当然这里我们需要提到一个概念:One-vs-all confusion matrices
即针对三个变量转换成,setosa与非setosa;这样就可以得到setosa的ROC

library(multiROC)
actual=dummies::dummy.data.frame(test %>% select(Species),               
                                 sep = "_",            
                                 dummy.classes = "factor"  )

predicted=predict(fit1,test,type = "prob")# with probability


test_data=cbind(actual,predicted)
colnames(test_data)=c("setosa_true","versicolor_true" ,"virginica_true",
                      "setosa_pred_m1","versicolor_pred_m1","virginica_pred_m1")
res <- multi_roc(test_data, force_diag=T)
res

res里面存储了我们想要的信息,接下来对res进行提取各组的Specificity 与Sensitivity,绘制ROC曲线。

#### ggplot ROC
n_method <- length(unique(res$Methods))
n_group <- length(unique(res$Groups))
res_df <- data.frame(Specificity= numeric(0), Sensitivity= numeric(0), Group = character(0), AUC = numeric(0), Method = character(0))
for (i in 1:n_method) {
  for (j in 1:n_group) {
    temp_data_1 <- data.frame(Specificity=res$Specificity[[i]][j],
                              Sensitivity=res$Sensitivity[[i]][j],
                              Group=unique(res$Groups)[j],
                              AUC=res$AUC[[i]][j],
                              Method = unique(res$Methods)[i])
    colnames(temp_data_1) <- c("Specificity", "Sensitivity", "Group", "AUC", "Method")
    res_df <- rbind(res_df, temp_data_1)
    
  }
  temp_data_2 <- data.frame(Specificity=res$Specificity[[i]][n_group+1],
                            Sensitivity=res$Sensitivity[[i]][n_group+1],
                            Group= "Macro",
                            AUC=res$AUC[[i]][n_group+1],
                            Method = unique(res$Methods)[i])
  temp_data_3 <- data.frame(Specificity=res$Specificity[[i]][n_group+2],
                            Sensitivity=res$Sensitivity[[i]][n_group+2],
                            Group= "Micro",
                            AUC=res$AUC[[i]][n_group+2],
                            Method = unique(res$Methods)[i])
  colnames(temp_data_2) <- c("Specificity", "Sensitivity", "Group", "AUC", "Method")
  colnames(temp_data_3) <- c("Specificity", "Sensitivity", "Group", "AUC", "Method")
  res_df <- rbind(res_df, temp_data_2)
  res_df <- rbind(res_df, temp_data_3)
}

ggplot(res_df, aes(x = 1-Specificity, y=Sensitivity)) + 
  geom_path(aes(color = Group, linetype=Method)) + 
  geom_segment(aes(x = 0, y = 0, xend = 1, yend = 1), colour='grey', linetype = 'dotdash') + 
  theme_bw() + 
  theme(plot.title = element_text(hjust = 0.5), 
        legend.justification=c(1, 0), 
        legend.position=c(.95, .05), 
        legend.title=element_blank(), 
        legend.background = element_rect(fill=NULL, size=0.5, linetype="solid", colour ="black"))

ggsave("ROC-SVM.pdf",width = 16,height = 12,dpi=500)
image.png

最后,附上RF,SVM的模型

#### 2.SVM
library(e1071)
fitsvm = svm(ya~ ., data = df2,probability=TRUE)
summary(fitsvm)


#### 3.RF
library(randomForest)
fitrf = randomForest(ya~ ., 
                   data = df2,
                   ntree = 300, # parameter setting
                   mtry = 8,
                   importance = TRUE,
                   proximity = TRUE)

参考:
Performance Measures for Multi-Class Problems--
https://www.datascienceblog.net/post/machine-learning/performance-measures-multi-class-problems/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容