自定义SVM模型在插入符号中进行调整时出错

时间:2015-01-07 20:31:53

标签: r svm

我尝试关注this link来创建自定义SVM并通过一些交叉验证来运行它。我的主要原因是在我的网格搜索中运行Sigma,Cost和Epsilon参数,而最近的插入符模型(svmRadial)只能执行其中的两个。

当我尝试运行下面的代码时,我在网格的每次迭代中都会出现以下错误:

Warning in eval(expr, envir, enclos) :
  model fit failed for Fold1.: sigma=0.2, C=2, epsilon=0.1 Error in if (!isS4(modelFit) & !(method$label %in% c("Ensemble Partial Least Squares Regression",  : 
  argument is of length zero

即使我逐字地复制链接中的代码,我也会遇到类似的错误,而且我不确定如何解决它。我发现了this link,它介绍了如何构建自定义模型,并且我看到了引用此错误的位置,但仍然不确定问题是什么。我的代码如下:

#Generate Tuning Criteria across Parameters
C <- c(1,2)
sigma <- c(0.1,.2)
epsilon <- c(0.1,.2)
grid <- data.frame(C,sigma)

#Parameters
prm <- data.frame(parameter = c("C", "sigma","epsilon"),
                  class = rep("numeric", 3),
                  label = c("Cost", "Sigma", "Epsilon"))

#Tuning Grid
svmGrid <- function(x, y, len = NULL) {
    expand.grid(sigma = sigma,
                C = C,
                epsilon = epsilon)
}

#Fit Element Function
svmFit <- function(x, y, wts, param, lev, last, weights, classProbs, ...) {
    ksvm(x = as.matrix(x), y = y,
         type = "eps-svr",
         kernel = rbfdot,
         kpar = list(sigma = param$sigma),
         C = param$C,
         epsilon = param$epsilon,
         prob.model = classProbs,
         ...)
}

#Predict Element Function
svmPred <- function(modelFit, newdata, preProc = NULL, submodels = NULL)
    predict(modelFit, newdata)

#Sort Element Function
svmSort <- function(x) x[order(x$C),]

#Model
newSVM <- list(type="Regression",
               library="kernlab",
               loop = NULL,
               parameters = prm,
               grid = svmGrid,
               fit = svmFit,
               predict = svmPred,
               prob = NULL,
               sort = svmSort,
               levels = NULL)                    


#Train 
tc<-trainControl("repeatedcv",number=2, repeats = 0,
                 verboseIter = T,savePredictions=T)
svmCV <- train(
    Y~ 1
    + X1
    + X2
    ,data = data_nn,
    method=newSVM, 
    trControl=tc
    ,preProc = c("center","scale"))                 
svmCV

1 个答案:

答案 0 :(得分:0)

在查看提供的second link之后,我决定尝试在模型的参数中包含一个标签,这就解决了问题!它很有趣,因为插入符号文档说价值是可选的,但如果它有效,我不能抱怨。

#Model 
newSVM <- list(label="My Model",
                   type="Regression",
                   library="kernlab",
                   loop = NULL,
                   parameters = prm,
                   grid = svmGrid,
                   fit = svmFit,
                   predict = svmPred,
                   prob = NULL,
                   sort = svmSort,
                   levels = NULL)