Skip to content

Instantly share code, notes, and snippets.

@HackerEarthBlog
Last active June 5, 2019 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HackerEarthBlog/0336338c5d93dc3d724a8edb67ad0a05 to your computer and use it in GitHub Desktop.
Save HackerEarthBlog/0336338c5d93dc3d724a8edb67ad0a05 to your computer and use it in GitHub Desktop.
SVM in R
library(e1071)
library(caTools)
data(iris)
iris$spl=sample.split(iris,SplitRatio=0.7)
train=subset(iris, iris$spl==TRUE)
test=subset(iris, iris$spl==FALSE)
x=train[,-5]
y=train[,5]
svm_model <- svm(Species ~ ., data=train)
table(predict(svm_model, test[,-5]), test[,5])
setosa versicolor virginica
setosa 20 0 0
versicolor 0 19 2
virginica 0 1 18
svm_tune <- tune(svm, train.x=x, train.y=y, kernel="radial", ranges=list(cost=10^(-2:2), gamma=2^(-2:2)))
#tune() gives us the tuned parameters, C and gamma
svm_model_after_tune <- svm(Species ~ ., data=train,method = "C-classification", kernel="radial", cost=1, gamma=0.25)
summary(svm_model_after_tune)
table(predict(svm_model_after_tune, test[,-5]), test[,5])
setosa versicolor virginica
setosa 20 0 0
versicolor 0 19 1
virginica 0 1 19
@lokeshharad
Copy link

gamma=2^(-2:2) is it default value? or changes

@mangozy
Copy link

mangozy commented Jun 5, 2019

gamma=2^(-2:2) is it default value? or changes

It's a list of numbers for grid search in SVM parameter tuning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment