简体   繁体   中英

Error using kernlab package with precomputed kernels

I have been using the kernlab package and been facing issues using ksvm / predict function with precomputed kernels.

The error message I have got is:

> ksvm.mod <- ksvm(trainingset.outer, traininglabels.outer, kernel = "matrix",type="C-svc", C = 60, prob.model = TRUE)
> temp <-  predict(ksvm.mod, test.kernel.outer)
Error in .local(object, ...) : test vector does not match model !

I have looked at the source code for the place of error and found that it is due to difference in columns

newnrows <- nrow(newdata)
newncols <- ncol(newdata)
if(!is(newdata,"kernelMatrix") && !is.null(xmatrix(object))){
  if(is(xmatrix(object),"list") && is(xmatrix(object)[[1]],"matrix")) oldco <- ncol(xmatrix(object)[[1]])
  if(is(xmatrix(object),"matrix")) oldco <- ncol(xmatrix(object))
  if (oldco != newncols) stop ("test vector does not match model !")
}

However, the objects I have used have equal columns

> ncol(trainingset.outer)
[1] 1498
> ncol(test.kernel.outer)
[1] 1498

​Then, I have looked at the columns stored as per the models and found the below:

> ncol(xmatrix(ksvm.mod)[[1]])
Error in xmatrix(ksvm.mod)[[1]] : subscript out of bounds
> xmatrix(ksvm.mod)[[1]]
Error in xmatrix(ksvm.mod)[[1]] : subscript out of bounds
> xmatrix(ksvm.mod)
<0 x 0 matrix>
> ?xmatrix
> ksvm.mod
Support Vector Machine object of class "ksvm" 

SV type: C-svc  (classification) 
 parameter : cost C = 60 

[1] " Kernel matrix used as input."

Number of Support Vectors : 831 

Objective Function Value : -211534.1 
Training error : 0.257677 
Probability model included. ​
> ncol(xmatrix(gene)[[1]]) # for dataframes used without precomputed kernels
[1] 172

I guess the model didn't store any object, am I correct in understanding ? As there are no good examples in web for using the package with precomputed kernels, I am writing for your help.

PS: I will try to provide the data for testing, if required.

You are doing it half right. The predict object wants only the kernel distance between newdata and support vectors, but it doesn't extract them itself, you must pass them yourself.

Try this:

ksvm.mod <- ksvm(trainingset.outer, traininglabels.outer, kernel = "matrix",type="C-svc", C = 60, prob.model = TRUE)
temp <-  predict(ksvm.mod, test.kernel.outer[, SVindex(ksvm.mod))

I'm assuming here test.kernel.outer is a kernelMatrix that measures the kernel distance between test data (rows) and train data (columns).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM