knitr::opts_chunk$set( collapse = TRUE, comment = "#>" # fig.path = "Readme_files/" ) library(compboost)
Compboost
object using the R6
interfaceWe use the titanic dataset with binary
classification on Survived
. First of all we store the train and test data
into two data frames and remove all rows that contains missing values (NA
s):
# Store train and test data: df = na.omit(titanic::titanic_train) df$Survived = factor(df$Survived, labels = c("no", "yes"))
For the later stopping we split the dataset into train and test:
set.seed(123) idx_train = sample(seq_len(nrow(df)), size = nrow(df) * 0.8) idx_test = setdiff(seq_len(nrow(df)), idx_train)
We define the same model as in the use-case but just on the train index without specifying an out-of-bag fraction:
cboost = Compboost$new(data = df[idx_train, ], target = "Survived") cboost$addBaselearner("Age", "spline", BaselearnerPSpline) cboost$addBaselearner("Fare", "spline", BaselearnerPSpline) cboost$addBaselearner("Sex", "ridge", BaselearnerCategoricalRidge)
The early stopping of compboost
is done by using logger objects. Logger are executed after each iteration and stores class dependent data such as the runtime or risk. Additionally, each logger can be declared as a stopper by setting use_as_stopper = TRUE
. By declaring a logger as stopper, it is used to stop the algorithm after a logger-specific criteria is reached. For example, the LoggerTime
will stop the algorithm after a pre-defined runtime is reached.
Now it is time to define a logger to track the runtime. As mentioned above, we set use_as_stopper = TRUE
. By setting the max_time
we define how long we want to train the model, here 50000 microseconds:
cboost$addLogger(logger = LoggerTime, use_as_stopper = TRUE, logger_id = "time", max_time = 50000, time_unit = "microseconds") cboost$train(2000, trace = 250) cboost
As we can see, the fittings is stopped early after r cboost$getCurrentIteration()
and does not train the full 2000 iterations. The logger data can be accessed by calling $getLoggerData()
:
tail(cboost$getLoggerData())
cboost = Compboost$new(data = df[idx_train, ], target = "Survived") cboost$addBaselearner("Age", "spline", BaselearnerPSpline) cboost$addBaselearner("Fare", "spline", BaselearnerPSpline) cboost$addBaselearner("Sex", "ridge", BaselearnerCategoricalRidge)
In machine learning, we often like to stop at the best model performance. We need either tuning or early stopping to determine what is a good number of iterations $m$. A well-known procedure is to log the out-of-bag (oob) behavior of the model and stop after the model performance starts to get worse. The required parameters for the logger are
the loss $L$ that is used for stopping: $$\mathcal{R}{\text{emp}}^{[m]} = \frac{1}{n}\sum{i=1}^n L\left(y^{(i)}, f^{[m]}(x^{(i)})\right)$$
the percentage of performance increase as lower boundary for the increase: $$\text{err}^{[m]} = \frac{\mathcal{R}{\text{emp}}^{[m- 1]} - \mathcal{R}{\text{emp}}^{[m]}}{\mathcal{R}_{\text{emp}}^{[m - 1]}}$$
Since we are interested in the oob behavior, it is necessary to prepare the oob data and response for compboost
. Therefore, it is possible to use the $prepareResponse()
and $prepareData()
member functions to create suitable objects:
oob_response = cboost$prepareResponse(df$Survived[idx_test]) oob_data = cboost$prepareData(df[idx_test,])
With these objects we can add the oob risk logger, declare it as stopper, and train the model:
cboost$addLogger(logger = LoggerOobRisk, use_as_stopper = TRUE, logger_id = "oob", used_loss = LossBinomial$new(), eps_for_break = 0, patience = 5, oob_data = oob_data, oob_response = oob_response) cboost$train(2000, trace = 250)
Note: The use of eps_for_break = 0
is a hard constrain to stop the training until the oob risk starts to increase.
Taking a look at the logger data tells us that we stopped exactly after the first five differences are bigger than zero (the oob risk of these iterations is bigger than the previous ones):
tail(cboost$getLoggerData(), n = 10) diff(tail(cboost$getLoggerData()$oob, n = 10))
library(ggplot2) ggplot(data = cboost$getLoggerData(), aes(x = `_iterations`, y = oob)) + geom_line() + xlab("Iteration") + ylab("Empirical Risk")
Taking a look at 2000 iterations shows that we have stopped quite good:
cboost$train(2000, trace = 0) ggplot(data = cboost$getLoggerData(), aes(x = `_iterations`, y = oob)) + geom_line() + xlab("Iteration") + ylab("Empirical Risk")
Note: It can happen that the model's oob behavior increases locally for a few iterations and then starts to decrease again. To capture this, we need the "patience" parameter which waits for, let's say, 5 iterations and stops the algorithm only if the improvement in all 5 iterations is smaller than our criteria. Setting this parameter to one can lead to unstable results:
df = na.omit(titanic::titanic_train) df$Survived = factor(df$Survived, labels = c("no", "yes")) set.seed(123) idx_train = sample(seq_len(nrow(df)), size = nrow(df) * 0.8) idx_test = setdiff(seq_len(nrow(df)), idx_train) cboost = Compboost$new(data = df[idx_train, ], target = "Survived", loss = LossBinomial$new()) cboost$addBaselearner("Age", "spline", BaselearnerPSpline) cboost$addBaselearner("Fare", "spline", BaselearnerPSpline) cboost$addBaselearner("Sex", "ridge", BaselearnerCategoricalRidge) oob_response = cboost$prepareResponse(df$Survived[idx_test]) oob_data = cboost$prepareData(df[idx_test,]) cboost$addLogger(logger = LoggerOobRisk, use_as_stopper = TRUE, logger_id = "oob", used_loss = LossBinomial$new(), eps_for_break = 0, patience = 1, oob_data = oob_data, oob_response = oob_response) cboost$train(2000, trace = 0) library(ggplot2) ggplot(data = cboost$getLoggerData(), aes(x = `_iterations`, y = oob)) + geom_line() + xlab("Iteration") + ylab("Empirical Risk")
max_time
from the time loggerAdd the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.