Problems with apply R

291 Views Asked by At

I Have a problem with using the apply function in R. I made the following function:

TrainSupportVectorMachines <- function(trainingData,kernel,G,C){

####train het model
fit<-svm(Device~.,data=trainingData,kernel=kernel,probability=TRUE,
        gamma =G, costs=C)

return(fit);
}

I want to train the model with different values of Cost(c). Therefore, I tried the following commend:

    cst = matrix(2^(-4:-2),ncol=3)
    kernl = "sigmoid"
    fitSVMBP <- apply(cst,2,function(x)TrainSupportVectorMachines(dtr1,kernl,0.625,x))

My opinion is that, fitSVMBP becomes a list with different SVM models with different values for cost. But I get a list with different SVM model but they have all a cost of 1.

Does anybody know what I do wrong?


EDIT:

I use the e1071 package. And the dataset looks like:

> head(dtr1)
  Device Geslacht Leeftijd Invultijd Type Maanden.geleden
1     pc        M       45      16.0    A              15
2     pc        V       43      27.5    A               3
3     pc        V       28      16.0    A              15
4     pc        V       17      10.0    A              13
5     pc        M       56      16.0    A              15
6     pc        M       50      27.5    A               3
1

There are 1 best solutions below

2
On BEST ANSWER

You have called the argument costs and not cost. Here's an example using the sample data in ?svm so you can try this:

model <- svm(Species ~ ., data = iris, cost=.6)
model$cost
# [1] 0.6
model <- svm(Species ~ ., data = iris, costs=.6)
model$cost
# [1] 1

R will do partial matching (so in this case cos=.6 would work) but if you overspecify an argument it doesn't match.

Nor will it always complain if you give it an argument it doesn't expect:

> model <- svm(Species ~ ., data = iris, costs=.6, asjkdakjshd=1)
> 

Because unmatched args get caught in the ... argument.

If you take this too far, you get:

> model <- svm(Species ~ ., data = iris, c=.122)
Error in svm.default(x, y, scale = scale, ..., na.action = na.action) : 
  argument 4 matches multiple formal arguments

because c matches cost, coef0, class.weights and cachesize.