Search code examples
rplotmachine-learningsvm

Plotting SVM Linear Separator in R


I'm trying to plot the 2-dimensional hyperplanes (lines) separating a 3-class problem with e1071's svm. I used the default method (so there is no formula involved) like so:

library('e1071')
## S3 method for class 'default':
machine <- svm(x, y, kernel="linear")

I cannot seem to plot it by using the plot.svm method:

plot(machine, x)
Error in plot.svm(machine, x) : missing formula.

But I did not use the formula method, I used the default one, and if I pass '~' or '~.' as a formula argument it'll complain about the matrix x not being a data.frame.

  • Is there a way of plotting the fitted separator/s for the 2D problem while using the default method?
  • How may I achieve this?

Thanks in advance.


Solution

  • It appears that although svm() allows you to specify your input using either the default or formula method, plot.svm() only allows a formula method. Also, by only giving x to plot.svm(), you are not giving it all the info it needs. It also needs y.

    Try this:

    library(e1071)
    
    x <- prcomp(iris[,1:4])$x[,1:2]
    y <- iris[,5]
    
    df <- data.frame(cbind(x[],y[]))
    
    machine <- svm(y ~ PC1 + PC2, data=df)
    plot(machine, data=df)
    

    svmplot