2021-12-19

k近邻法分类和ROC曲线

是不是有几个类就要画几个ROC曲线啊?

data(iris)

library(kknn)

library(caret)

index <- sample(1:nrow(iris), size=round(nrow(iris)/3), replace=FALSE)

trainSet <- iris[-index, ]

testSet <- iris[index, ]

iris.kknn <- kknn(Species~., trainSet, testSet, distance=2, kernel="triangular")

summary(iris.kknn)

Fit.kknn <- fitted(iris.kknn)

table(testSet$Species, Fit.kknn)

confusionMatrix(testSet$Species, Fit.kknn)

library(ROCR)

library(gplots)

data(iris)

score <- list()

label <- list()

pred <- list()

pref <- list()

AUC <- list()

attributes(iris.kknn)

for(i in 1:length(levels(iris$Species))){

  score[[i]] <- iris.kknn$prob[,i]

}

colour <- c("red", "green", "blue")

for(i in 1:length(score)){

  label[[i]] <- c(0)

  label[[i]] <- c(label[[i]], testSet$Species==levels(iris$Species)[i])

  label[[i]] <- label[[i]][-1]

  sort_index <- order(score[[i]], decreasing=TRUE)

  score[[i]] <- score[[i]][sort_index]

  label[[i]] <- label[[i]][sort_index]

  pred[[i]] <- prediction(score[[i]], label[[i]])

  pref[[i]] <- performance(pred[[i]], "tpr", "fpr")

  AUC[[i]] <- performance(pred[[i]], "auc")

  if(i==1){

    plot(pref[[i]], col=colour[i])

  }

  else{

    plot(pref[[i]], add=TRUE, col=colour[i])

  }

}

你可能感兴趣的:(2021-12-19)