################ Code for "nicer" 2D plots ########################## svmPlot <- function(dt, svmModel, n=100, xname1, xname2, outcome, ...) { grange <- apply(dt[ ,1:2], 2, range) ## determine range for both predictors x1 <- seq(from=grange[1,1], to=grange[2,1], length=n) x2 <- seq(from=grange[1,2], to=grange[2,2], length=n) xgrid <- expand.grid(X1=x1, X2=x2) ## makes a grid with every ## combination of X1 and X2 names(xgrid) <- c(xname1,xname2) ygrid <- predict(svmModel, xgrid) plot(xgrid, col=c("red","blue")[as.numeric(ygrid)], pch=20, cex=0.1, ...) points(as.matrix(dt[dt[ ,outcome]=="-1",1:2]), col="red", pch=19, cex=0.7) points(as.matrix(dt[dt[ ,outcome]=="1",1:2]), col="blue", pch=19, cex=0.7) points(dt[svmModel$index, 1:2], pch = 5, cex = 1.5, col = "black") ## index in an svm fit ## gives the index of the support vectors beta <- drop(t(svmModel$coefs)%*% as.matrix(dt[svmModel$index, 1:2])) ## above line extracts beta1 and beta2 from svmModel fit -- ## "%*%" means matrix multiplication beta0 <- svmModel$rho ## and this one gives beta0 abline(beta0/beta[2], -beta[1]/beta[2], lwd=3) abline((beta0-1)/beta[2], -beta[1]/beta[2], lty=2, lwd=3, col="red") abline((beta0+1)/beta[2], -beta[1]/beta[2], lty=2, lwd=3, col="blue") }