Solved – Examples for One class SVM in R

rsvm

I am trying to do one-class SVM in R. I have been trying to use e1071/ksvm kernlab package.
But I am not sure if I am doing it correctly.

Is there any working example for one-class SVM in R?

Also,

  • I am giving a big matrix of predictors as X. Since its supposed to be one-class, is the assumption that all training data I gave forms 'positive' class? If so, we don't have to give the labels 'Y'?
  • The predicted labels given as output are True/False. So I am assuming, True is 'positive' class.

Edit: Attaching sample code. Here I sampled 60% of 'TRUE' class and I tested on the full data set.

library(e1071)
library(caret)

data(iris)

iris$SpeciesClass[iris$Species=="versicolor"] <- "TRUE"
iris$SpeciesClass[iris$Species!="versicolor"] <- "FALSE"
trainPositive<-subset(iris,SpeciesClass=="TRUE")
inTrain<-createDataPartition(1:nrow(trainPositive),p=0.6,list=FALSE)
trainpredictors<-iris[inTrain,1:4]
testpredictors<-iris[,1:4]
testLabels<-iris[,6]

svm.model<-svm(trainpredictors,y=NULL,
               type='one-classification',
               nu=0.5,
               scale=TRUE,
               kernel="radial")
svm.pred<-predict(svm.model,testpredictors)
confusionMatrixTable<-table(Predicted=svm.pred,Reference=testLabels)
confusionMatrix(confusionMatrixTable,positive='TRUE')

Best Answer

The Chapter 9 lab exercise of An Introduction to Statistical Learning provides a working example of using an SVM for binary classification, and it does indeed use the e1071 library. By permission of the publisher, a PDF version of the book is available for free download.

Related Question