2

I tried to save the output of xgb.train of XGBoost as a log file by logging, but I could not record the output. How can I record it? I tried to refer to the existing Stackoverflow question but it was impossible. I would like you to show it with a concrete sample.

import sys
import logging

# ---------------------------------------------- #
# Some logging settings
# ---------------------------------------------- #

import xgboost as xgb

import numpy as np
from sklearn.model_selection import KFold
from sklearn.datasets import load_digits

rng = np.random.RandomState(31337)

print("Zeros and Ones from the Digits dataset: binary classification")
digits = load_digits(2)
y = digits['target']
X = digits['data']
kf = KFold(n_splits=2, shuffle=True, random_state=rng)
for train_index, test_index in kf.split(X):

    param = {'max_depth':2, 'eta':0.3, 'silent':1, 'objective':'binary:logistic' }

    dtrain = xgb.DMatrix(X[train_index], y[train_index])
    dtest = xgb.DMatrix(X[test_index], y[test_index])

    # specify validations set to watch performance
    watchlist  = [(dtest,'eval'), (dtrain,'train')]
    num_round = 2
    bst = xgb.train(param, dtrain, num_round, watchlist)

# I want to record this output.
# Zeros and Ones from the Digits dataset: binary classification
# [0]   eval-error:0.011111 train-error:0.011111
# [1]   eval-error:0.011111 train-error:0.005556
# [0]   eval-error:0.016667 train-error:0.005556
# [1]   eval-error:0.005556 train-error:0
1

3 Answers 3

5

xgboost prints their log into standard output directly and you cannot change the behaviour. But callbacks parameter of xgb.train has ability to record the result as same timing as internal prints.

Following code is a sample using callback to record xgboost log into logger. log_evaluation() returns a callback function called from xgboost internal and you can add the callback function to callbacks

from logging import getLogger, basicConfig, INFO

import numpy as np
import xgboost as xgb
from sklearn.datasets import load_digits
from sklearn.model_selection import KFold

# Some logging settings
basicConfig(level=INFO)
logger = getLogger(__name__)


def log_evaluation(period=1, show_stdv=True):
    """Create a callback that logs evaluation result with logger.

    Parameters
    ----------
    period : int
        The period to log the evaluation results

    show_stdv : bool, optional
         Whether show stdv if provided

    Returns
    -------
    callback : function
        A callback that logs evaluation every period iterations into logger.
    """

    def _fmt_metric(value, show_stdv=True):
        """format metric string"""
        if len(value) == 2:
            return '%s:%g' % (value[0], value[1])
        elif len(value) == 3:
            if show_stdv:
                return '%s:%g+%g' % (value[0], value[1], value[2])
            else:
                return '%s:%g' % (value[0], value[1])
        else:
            raise ValueError("wrong metric value")

    def callback(env):
        if env.rank != 0 or len(env.evaluation_result_list) == 0 or period is False:
            return
        i = env.iteration
        if i % period == 0 or i + 1 == env.begin_iteration or i + 1 == env.end_iteration:
            msg = '\t'.join([_fmt_metric(x, show_stdv) for x in env.evaluation_result_list])
            logger.info('[%d]\t%s\n' % (i, msg))

    return callback


rng = np.random.RandomState(31337)

print("Zeros and Ones from the Digits dataset: binary classification")
digits = load_digits(2)
y = digits['target']
X = digits['data']
kf = KFold(n_splits=2, shuffle=True, random_state=rng)
for train_index, test_index in kf.split(X):
    param = {'max_depth': 2, 'eta': 0.3, 'silent': 1, 'objective': 'binary:logistic'}

    dtrain = xgb.DMatrix(X[train_index], y[train_index])
    dtest = xgb.DMatrix(X[test_index], y[test_index])

    # specify validations set to watch performance
    watchlist = [(dtest, 'eval'), (dtrain, 'train')]
    num_round = 2
    # add logger
    callbacks = [log_evaluation(1, True)]
    bst = xgb.train(param, dtrain, num_round, watchlist, callbacks=callbacks)
2

The accepted solution does not work with xgboost version 1.3 and above. (Tested on 1.6.1), due to following:

In XGBoost 1.3, a new callback interface is designed for Python package.

(Source: https://xgboost.readthedocs.io/en/latest/python/callbacks.html)

You can achieve python logging for xgboost.train by defining custom logging callback and passing it as argument to xgb.train as shown below:

import logging
logger = logging.getLogger(__name__)

import xgboost

class XGBLogging(xgboost.callback.TrainingCallback):
    """log train logs to file"""

    def __init__(self, epoch_log_interval=100):
        self.epoch_log_interval = epoch_log_interval

    def after_iteration(self, model, epoch, evals_log):
        if epoch % self.epoch_log_interval == 0:
            for data, metric in evals_log.items():
                metrics = list(metric.keys())
                metrics_str = ""
                for m_key in metrics:
                    metrics_str = metrics_str + f"{m_key}: {metric[m_key][-1]}"
                logger.info(f"Epoch: {epoch}, {data}: {metrics_str}")
        # False to indicate training should not stop.
        return False

model = xgboost.train(
                xgboost_parms, 
                dtrain=dtrain,
                evals=[(dtrain,"train"),(dvalid,"valid")]
                callbacks=[XGBLogging(epoch_log_interval=100)]
            ) 
0
0
import sys
%logstart -o "test.log"
sys.stdout = open('test.log', 'a')

import xgboost as xgb

import numpy as np
from sklearn.model_selection import KFold
from sklearn.datasets import load_digits

rng = np.random.RandomState(31337)

print("Zeros and Ones from the Digits dataset: binary classification")
digits = load_digits(2)
y = digits['target']
X = digits['data']
kf = KFold(n_splits=2, shuffle=True, random_state=rng)
for train_index, test_index in kf.split(X):

    param = {'max_depth':2, 'eta':0.3, 'silent':1, 'objective':'binary:logistic' }

    dtrain = xgb.DMatrix(X[train_index], y[train_index])
    dtest = xgb.DMatrix(X[test_index], y[test_index])

    # specify validations set to watch performance
    watchlist  = [(dtest,'eval'), (dtrain,'train')]
    num_round = 2
    bst = xgb.train(param, dtrain, num_round, watchlist)

This will start saving everything in the file test.log. The output as well as the input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.