birdy
birdy

Reputation: 9636

How to create a contour plot in R

I've tuned a SVM with various values for cost and gamma for a dataset

> library(e1071)
> library(foreign)
> dataframe <- read.arff("/diabetes.arff")
> index <- seq_len(nrow(dataframe))
> trainindex <- sample(index, trunc(length(index)/2))
> trainset <- dataframe[trainindex, ]
> testset <- dataframe[-trainindex, ]
> tunedsvm <- tune.svm(class ~ ., data = trainset, gamma = 2^(seq(-15,3,by=2)), cost = 2^(seq(-5,15,by=2)))
> tunedsvm

Parameter tuning of ‘svm’:

- sampling method: 10-fold cross validation 

- best parameters:
        gamma cost
 0.0001220703 2048

- best performance: 0.2187029 
> head(tunedsvm$performances)
         gamma    cost    error dispersion
1 3.051758e-05 0.03125 0.351546 0.06245835
2 1.220703e-04 0.03125 0.351546 0.06245835
3 4.882812e-04 0.03125 0.351546 0.06245835
4 1.953125e-03 0.03125 0.351546 0.06245835
5 7.812500e-03 0.03125 0.351546 0.06245835
6 3.125000e-02 0.03125 0.351546 0.06245835
> nrow(tunedsvm$performances)
[1] 110

I want to create a contour plot similar to what matlab generates (below is an example)

enter image description here

I tried the plot command but the contour I can't deduce much from the plot it generates.

> plot(tunedsvm)

enter image description here

Upvotes: 7

Views: 1959

Answers (1)

Heather Turner
Heather Turner

Reputation: 3314

tune.svm returns an object of class "tune":

> class(tunedsvm)
[1] "tune"

Therefore the relevant help page is ?plot.tune. A little reading of this reveals several useful arguments for customisation:

plot(tunedsvm, 
     transform.x = log2, transform.y = log2, # log 2 scale for x and y
     transform.z = function(x) 1 - x,        # convert error rate to accuracy rate
     swapxy = TRUE,                          # put gamma on y axis
     color.palette = terrain.colors,         # define color palette for contours
     xlab = expression(log[2](cost)), ylab = expression(log[2](gamma)),
     main = "Accuracy Rate of SVM")

This code produces the following plot:

contour plot showing accuracy rate of svm over log2 gamma vs log2 cost

Upvotes: 9

Related Questions