Error: The tuning parameter grid should have columns mtry

Viewed 47

I'm trying to train a random forest model using caret in R. I want to tune the parameters to get the best values, using the expand.grid function. However, I keep getting this error:

Error: The tuning parameter grid should have columns mtry

This is my code. The data I use here is called scoresWithResponse:

ctrlCV = trainControl(method = 'cv', number = 10 , classProbs = TRUE , savePredictions = TRUE, summaryFunction = twoClassSummary )

rfGRID = expand.grid(interaction.depth = c(2, 3, 5, 6, 7, 8, 10),
                     n.trees = c(50,75,100,125,150,200,250), 
                     shrinkage = seq(.005, .2,.005),
                     n.minobsinnode = c(5,7,10, 12 ,15, 20),
                    nodesize = c(1:10),
                    mtry = c(1:10))

RF_loop_trn = c()
RF_loop_tst = c()

for(i in (1:5)){
  print(i)
  
  IND = createDataPartition(y = scoresWithResponse$response, p=0.75, list = FALSE)
  scoresWithResponse.trn = scoresWithResponse[IND, ]
  scoresWithResponse.tst = scoresWithResponse[-IND,]
  
  rfFit = train(response~., data = scoresWithResponse.trn,
                importance = TRUE,
                method = "rf",
                metric="ROC",
                trControl = ctrlCV,
                tuneGrid = rfGRID,
                classProbs = TRUE,
                summaryFunction = twoClassSummary
  )
  
  
  RF_loop_trn[i] = auc(roc(scoresWithResponse.trn$response,predict(rfFit,scoresWithResponse.trn, type='prob')[,1]))
  RF_loop_tst[i] = ahaveroc(scoresWithResponse.tst$response,predict(rfFit,scoresWithResponse.tst, type='prob')[,1]))
  
}

After investigating for some time, there has been several suggestions like redownloading the caret package from github, adding a . before each parameter in expand.grid, adding a dot only before the mtry parameter (something like .mtry), adding the mtry to the train function instead expand.grid.. I tried all that and they all produce the same error.

Where and how should I add the mtry parameter? what is causing this error?

1 Answers

I can't comment yet so I'll reply

Have you tried to insert the mtry argument directly into the train function? for example:

rfGRID = expand.grid(interaction.depth = c(2, 3, 5, 6, 7, 8, 10),
                     n.trees = c(50,75,100,125,150,200,250), 
                     shrinkage = seq(.005, .2,.005),
                     n.minobsinnode = c(5,7,10, 12 ,15, 20),
                    nodesize = c(1:10)
                    )


rfFit = train(response~., data = scoresWithResponse.trn,
                importance = TRUE,
                method = "rf",
                metric="ROC",
                trControl = ctrlCV,
                tuneGrid = rfGRID,
                classProbs = TRUE,
                summaryFunction = twoClassSummary,
                mtry = 1000

  )
Related