如何在R的Caret及Knitr中抑制GBM模型的迭代输出?
Got it, I know exactly how annoying those endless GBM iteration outputs can be when knitting a document—here are a couple of clean, straightforward ways to suppress them:
1. Pass the verbose = FALSE parameter directly to GBM
The gbm package's training function has a built-in verbose flag that controls whether it prints those Iter/TrainDeviance lines. You can pass this right into the train() function in caret:
mod_gbm <- train(classe ~ ., data = TrainSet, method = "gbm", verbose = FALSE)
This will shut off the per-iteration deviance output you showed in your example.
2. Add verboseIter = FALSE to trainControl (for extra quietness)
If you also want to suppress any cross-validation iteration messages from caret itself, set up a training control object with verboseIter = FALSE, and combine it with the verbose = FALSE flag for GBM:
# Set up quiet training control ctrl <- trainControl(verboseIter = FALSE) # Train the model with both suppression flags mod_gbm <- train(classe ~ ., data = TrainSet, method = "gbm", trControl = ctrl, verbose = FALSE)
This combination ensures you won't get any extra output during the model training process—perfect for keeping your knit document clean.
3. Quick workaround with capture.output() (if you need a quick fix)
If you just need a temporary solution without adjusting parameters, you can wrap the train() call in capture.output() to redirect all output to nowhere:
capture.output( mod_gbm <- train(classe ~ ., data = TrainSet, method = "gbm"), file = NULL # Discard the output instead of saving to a file )
That said, using the parameter-based methods above is more maintainable and explicit.
内容的提问来源于stack exchange,提问作者user2165379

