Home > Software design >  How to build a model using tuned (existing) parameters in caret?
How to build a model using tuned (existing) parameters in caret?

Time:10-09

I am trying to build a SVM model using the caret package. After tuning the parameters, how can we build the model using the optimal parameters so we don't need to tune the parameters in the future when we use the model? Thanks.

library(caret)
data("mtcars")

set.seed(100)
mydata = mtcars[, -c(8,9)]
model_svmr <- train(
  hp ~ ., 
  data = mydata, 
  tuneLength = 10, 
  method = "svmRadial", 
  metric = "RMSE", 
  preProcess = c('center', 'scale'),
  trControl = trainControl(
    method = "repeatedcv", 
    number = 5, 
    repeats = 2, 
    verboseIter = TRUE
    )
  )

model_svmr$bestTune

The results show that sigma=0.1263203, C=4. How can we build a SVM model using the tuned parameters?

CodePudding user response:

From this page in the caret package's documentation:

In cases where the model tuning values are known, train can be used to fit the model to the entire training set without any resampling or parameter tuning. Using the method = "none" option in trainControl can be used.

In your case, that would look like:

library(caret)
data("mtcars")

set.seed(100)
mydata2 <- mtcars[, -c(8, 9)]
model_svmr <- train(
  hp ~ .,
  data = mydata,
  method = "svmRadial",
  trControl = trainControl(method = "none"),    # Telling caret not to re-tune
  tuneGrid = data.frame(sigma=0.1263203, C=4)   # Specifying the parameters
)

where we have removed any parameters relating to the tuning, namely tunelength, metric and preProcess.

Note that plot.train, resamples, confusionMatrix.train and several other functions will not work with this object but predict.train and others will.

  • Related