How do I load a kernel function into the ksvm of the kernlab package in R?

I am rewriting the RBF core function:

 install.packages("kernlab")
 library(kernlab)

 rbf <- function(x, y) {
  gamma<-0.5
  exp(-0.5*norm((as.matrix(x)-as.matrix(y)),"f")) 
   }
class(rbf) <- "kernel"

      

the data I'm using (10 observations, 3 variables and the fourth column is the target):

    data<-matrix(1:40,nrow=10,ncol=4)
    train<-data[1:(0.6*nrow(data)), ]
    test<-data[((0.6*nrow(data))+1):nrow(data), ]

      

simulation with custom kernel function using ksvm and prediction:

k_rbf <- ksvm(train[,ncol(train)]~.,data=train,C=0.1,type="eps-svr",epsilon=0.01,kernel=rbf)
ksvm_rbf<-predict(k_rbf, test)

      

the function is working well so far, but I want to continue developing a custom rbf core by adding a similarity function. We usually have an RBF core as shown below:

enter image description here

Adding a core RBF with seasonality that I developed looks like this: enter image description here

Where x_i and x_j are two objects representing time series at timestamp t_i and t_j respectively, and S is the seasonal period

so adding a new column with an index for each row:

    t<-1:nrow(data)
    data_t<-cbind(t,data)
    train_t<-data_t[1:(0.6*nrow(data_t)), ]
    test_t<-data_t[((0.6*nrow(data_t))+1):nrow(data_t), ]

      

adding some of the similarity to the core I built:

      sea_rbf <- function(x, y) {
      gamma<-0.5
      S<-3
      n_x<-x[1] # row ID of X
      n_y<-y[1] # row ID of y
      x<-x[2:4]
      y<-y[2:4]
      d<-abs((n_x-n_y)%% S)
      sea<-min(d,S-d)
      value <-exp(-0.5*norm((as.matrix(x)-as.matrix(y)),"f"))*exp(-sea^2) 
      return (value )}
      class(sea_rbf) <- "kernel"

      k_rbf_t <-           ksvm(train_t[,ncol(train_t)]~.,data=train_t,C=0.1,type="eps-svr",epsilon=0.01,kernel=sea_rbf)
      ksvm_rbf_t<-predict(k_rbf_t, test_t)

      

there are no errors during training and prediction, but when I run debug () to see the details of the process, this is not what I expected! For example, the code "n_x <-x 1 " in the function never retrieved the row id from the raw data :(.

I had a misunderstanding of using a kernel function with a ksvm function: ((((

any help is appreciated!

Thank you so much!!!

+3


source to share





All Articles