代码之家  ›  专栏  ›  技术社区  ›  Shahzad

在R中使用tryCatch

svm r
  •  1
  • Shahzad  · 技术社区  · 13 年前

    使用e1071,可以调整SVM模型的参数

    svmmodels <- lapply(trainingtemp, function(data)
                        {
                          svm.tune <- tune.svm(label~., data=data,
                                               gamma=10^(-3:0), cost=10^(-3:3));
                          svm(label~., data=data,
                              method="C-classification",
                              kernel="radial", cost=svm.tune$best.parameters$cost, 
                                   gamma=svm.tune$best.parameters$gamma)
                        })
    

    但对于某些数据,tune.svm会返回一个空模型(这可能有几个原因)。在这种情况下,如果tune.svm返回以下错误消息,那么可以使用svm函数中的默认参数。

    Error in predict.svm(ret, xhold, decision.values = TRUE) : 
     Model is empty!
    Calls: lapply ... svm.formula -> svm.default -> na.action -> predict -> predict.svm
    Execution halted
    
    1 回复  |  直到 13 年前
        1
  •  2
  •   agstudy    13 年前

    这应该起作用:

    tryCatch(
         svm.tune <- tune.svm(label~., data=data,
                                gamma=10^(-3:0), cost=10^(-3:3))
         svm(label~., data=data,
                          method="C-classification",
                          kernel="radial", cost=svm.tune$best.parameters$cost, 
                               gamma=svm.tune$best.parameters$gamma)
    }, error = function(err) {
      ## here you can your svm with defualt parameter 
       svm(label~., data=data,
                          method="C-classification",
                          kernel="radial")
    })