ROC for random forest

2020-07-30 00:34发布

问题:

I understand that ROC is drawn between tpr and fpr, but I am having difficulty in determining which parameters I should vary to get different tpr/fpr pairs.

回答1:

I wrote this answer on a similar question.

Basicly you can increase weighting on certain classes and/or downsample other classes and/or change vote aggregating rule.

[[EDITED 13.15PM CEST 1st July 2015]] @ "the two classes are very balanced – Suryavansh"

In such case your data is balanced you should mainly go with option 3 (changing aggregation rule). In randomForest this can be accessed with cutoff parameter either at training or at predicting. In other settings you may have to yourself to extract all cross-validated votes from all trees, apply a series of rules and calculate the resulting fpr and fnr.

library(randomForest)
library(AUC)

#some balanced data generator
make.data = function(obs=5000,vars=6,noise.factor = .4) {
  X = data.frame(replicate(vars,rnorm(obs)))
  yValue = with(X,sin(X1*pi)+sin(X2*pi*2)^3+rnorm(obs)*noise.factor)
  yClass = (yValue<median(yValue))*1
  yClass = factor(yClass,labels=c("red","green"))
  print(table(yClass)) #five classes, first class has 1% prevalence only
  Data=data.frame(X=X,y=yClass)
}

#plot true class separation
Data = make.data()
par(mfrow=c(1,1))
plot(Data[,1:2],main="separation problem: predict red/green class",
     col = c("#FF000040","#00FF0040")[as.numeric(Data$y)])

#train default RF
rf1 = randomForest(y~.,Data)
#you can choose a given threshold from this ROC plot
plot(roc(rf1$votes[,1],rf1$y),main="chose a threshold from")

#create at testData set from same generator
testData = make.data() 


#predict with various cutoff's 
predTable = data.frame(
  trueTest = testData$y,
  majorityVote = predict(rf1,testData),
  #~3 times increase false red
  Pred.alot.Red = factor(predict(rf1,testData,cutoff=c(.3,.1))),
  #~3 times increase false green
  Pred.afew.Red = factor(predict(rf1,testData,cutoff=c(.1,.3)))
)

#see confusion tables
table(predTable[,c(1,2)])/5000
        majorityVote
trueTest    red  green
   red   0.4238 0.0762
  green 0.0818 0.4182

.

table(predTable[,c(1,3)])/5000
        Pred.alot.Red
trueTest    red  green
    red   0.2902 0.2098
    green 0.0158 0.4842

.

table(predTable[,c(1,4)])/5000
         Pred.afew.Red
trueTest    red  green
    red   0.4848 0.0152
    green 0.2088 0.2912

.