Reputation: 187
I have trained and tested a model using the following code
library(e1071)
library(readxl)
library(caret)
class1.svm.model <- svm(Class ~ ., data = class1.trainset,cost=20, cross=10,type="C-classification",kernel="radial",na.action=na.omit)
class1.svm.pred <- predict(class1.svm.model, class1.testset)
finalmatrix<-data.matrix(class1.svm.pred, rownames.force = F)
test<-table(pred = class1.svm.pred, true = class1.testset[,c(15768)])
confusionMatrix(test)
But unable to plot a ROC curve for the model. please help me with the correct syntax to plot a ROC curve to see the performance of my test data.
Upvotes: 1
Views: 8619
Reputation: 1527
Another way when you want to apply the ROC curve to binary classification:
# example data
X_class_a = matrix(rnorm(0, sd=.2, n=80), 40, 2)
X_class_b = matrix(rnorm(1, sd=.2, n=80), 40, 2)
X = rbind(X_class_a, X_class_b)
y = rep(c(-1, 1), c(40, 40))
df_linear = data.frame(x1 = X[,1],x2 = X[,2],class = factor(y))
we need a probability vector, so we need to set the parameter probability = TRUE
, both in svm
and predict
.
df_mod <- svm(class ~ ., data = df_linear, probability=TRUE)
library(ROCR)
pred2 <- predict(df_mod, df_linear, type = "prob", probability = TRUE)
pred2 <- attr(pred2,"probabilities")
pred = prediction(pred2[,2], df_linear$class)
perf = performance(pred, "tpr","fpr")
AUC1 <- performance(pred, "auc")@y.values # additionally AUC
plot(perf, col = 4, lwd = 2, xlab = "1-Specificity", ylab = "Sensitivity", main = paste("ROC Curve (Train)\nAUC:",AUC1))
lines(x = c(0,1), y = c(0,1), col = 2, lty = 2, lwd = 2)
legend(cex=1, "bottomright", legend = c("SVM model","Random"), col = c(4,2), lty = c(1,2), lwd = 2)
Upvotes: 1
Reputation: 1720
Ploting ROC curve for SVM with class:
roc_svm_test <- roc(response = class1.trainset$Class, predictor =as.numeric(class1.svm.pred))
plot(roc_svm_test, add = TRUE,col = "red", print.auc=TRUE, print.auc.x = 0.5, print.auc.y = 0.3)
legend(0.3, 0.2, legend = c("test-svm"), lty = c(1), col = c("blue"))
Upvotes: 1