R中的SVM使用e1071代替kernlab

时间:2015-04-04 17:55:02

标签: r svm r-caret

目前,插入式列车在引擎盖下使用了kernlab svm功能,这些目的很慢。但是e1071 svm训练器提供了急需的速度提升。因此,我希望与e1071的svm培训师一起使用插件的cv程序。有没有办法做到这一点?基本上我希望从默认的kernlab中用e1071替换插入符号的svm引擎。

我目前使用以下代码进行训练。

svm使用kernlab

svmModel2 = train(factor(TopPick) ~. - Date , data = trainSet, method = 'svmRadial')
pred.svm2 = predict(svmModel2, testSet)

svm使用e1071

svmModel = e1071::svm(factor(TopPick) ~ . - Date, data = trainSet)
pred.svm = predict(svmModel, testSet)

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

根据评论中的建议,您可以创建自己的自定义模型。

svmRadial2ModelInfo <- list(
  label   = "Support Vector Machines with Radial Kernel based on libsvm",
  library = "e1071",
  type    = c("Regression", "Classification"),
  parameters = data.frame(parameter = c("cost", "gamma"),
                          class = c("numeric", "numeric"),
                          label = c("Cost", "Gamma")),
  grid    = function(x, y, len = NULL, search = NULL) {
              sigmas <- kernlab::sigest(as.matrix(x), na.action = na.omit, scaled = TRUE)
              return( expand.grid(gamma = mean(as.vector(sigmas[-2])),
                                  cost  = 2 ^((1:len) - 3)) )
  },
  loop    = NULL,
  fit     = function(x, y, wts, param, lev, last, classProbs, ...) {
              if(any(names(list(...)) == "probability") | is.numeric(y))
              {
                out <- svm(x = as.matrix(x), y = y,
                           kernel = "radial",
                           cost  = param$cost,
                           gamma = param$gamma,
                           ...)
              } else {
                out <- svm(x = as.matrix(x), y = y,
                           kernel = "radial",
                           cost  = param$cost,
                           gamma = param$gamma,
                           probability = classProbs,
                           ...)
              }
              out
  },
  predict = function(modelFit, newdata, submodels = NULL) {
    predict(modelFit, newdata)
  },
  prob    = function(modelFit, newdata, submodels = NULL) {
    out <- predict(modelFit, newdata, probability = TRUE)
    attr(out, "probabilities")
  },
  varImp = NULL,
  predictors = function(x, ...){
    out <- if(!is.null(x$terms)) predictors.terms(x$terms) else x$xNames
    if(is.null(out)) out <- names(attr(x, "scaling")$x.scale$`scaled:center`)
    if(is.null(out)) out <-NA
    out
  },
  levels = function(x) x$levels,
  sort   = function(x) x[order(x$cost, -x$gamma),]
)

用法:

svmR <- caret::train(x = trainingSet$x,
                     y = trainingSet$y,
                     trControl = caret::trainControl(number=10),
                     method = svmRadial2ModelInfo,
                     tuneLength = 3)
相关问题