rsvmkernlab

comparing performance of all ksvm kernels at once


I'm new to R, so maybe this is a dumb question, but I'm looking for a way to iterate over all possible kernel options in the ksvm function in kernlab and spit out a table of the results.

Right now I have a basic set up:

# call ksvm
model <-  ksvm(as.matrix(data[,1:10]),as.factor(data[,11]),type="C-svc",kernel="vanilladot",C=100,scaled=TRUE)
# calculate a1.am
a <- colSums(model@xmatrix[[1]] * model@coef[[1]])
a
# calculate a0
a0 <- -model@b
a0
# see what the model predicts
pred <- predict(model,data[,1:10])
pred
# see what fraction of the model's predictions match the actual classification
sum(pred == data[,11]) / nrow(data)

and it spits out all the predictions and an accuracy metric

[1] 0.8639144

Ideally what I want is a table that looks like this

kernel       accuracy
vanilladot   0.8639144
polydot      0.7285432
besseldot    1
...          ...

Is there a quick and easy way to do that, or is the only way to manually create a table with the model name and accuracy metric and then print or plot it?


Solution

  • You can iterate all kernels in a for loop:

    myKernels = c("vanilladot","polydot","besseldot")
    results=list()
    for(i in 1:length(myKernels)){
      # call ksvm using  kernel instead of linear
      model <-  ksvm(as.matrix(data[,1:10]),as.factor(data[,11]),type="C-svc",kernel=myKernels[[i]],C=100,scaled=TRUE)
      # calculate a1.am
      a <- colSums(model@xmatrix[[1]] * model@coef[[1]])
      a
      # calculate a0
      a0 <- -model@b
      a0
      # see what the model predicts
      pred <- predict(model,data[,1:10])
      pred
      # see what fraction of the model's predictions match the actual classification
      results[[i]]=data.table(kernel=myKernels[[i]],accuracy=sum(pred == data[,11]) / nrow(data))
    }
    rindlist(results)