gpboost.Booster

class gpboost.Booster(params=None, train_set=None, model_file=None, model_str=None, silent=False, gp_model=None)[source]

Bases: object

Class for boosting model in GPBoost.

Authors:

Authors of the LightGBM Python package Fabio Sigrist

__init__(params=None, train_set=None, model_file=None, model_str=None, silent=False, gp_model=None)[source]

Initialize the Booster.

Parameters:
  • params (dict or None, optional (default=None)) – Parameters for Booster.

  • train_set (Dataset or None, optional (default=None)) – Training dataset.

  • model_file (string or None, optional (default=None)) – Path to the model file.

  • model_str (string or None, optional (default=None)) – Model will be loaded from this string.

  • silent (bool, optional (default=False)) – Whether to print messages during construction.

  • gp_model (GPModel or None, optional (default=None)) – GPModel object for Gaussian process boosting.

Methods

__init__([params, train_set, model_file, ...])

Initialize the Booster.

add_valid(data, name)

Add validation data.

attr(key)

Get attribute string from the Booster.

current_iteration()

Get the index of the current iteration.

dump_model([num_iteration, start_iteration, ...])

Dump Booster to JSON format.

eval(data, name[, feval])

Evaluate for data.

eval_train([feval])

Evaluate for training data.

eval_valid([feval])

Evaluate for validation data.

feature_importance([importance_type, iteration])

Get feature importances.

feature_name()

Get names of features.

free_dataset()

Free Booster's Datasets.

free_network()

Free Booster's network.

get_leaf_output(tree_id, leaf_id)

Get the output of a leaf.

get_split_value_histogram(feature[, bins, ...])

Get split value histogram for the specified feature.

lower_bound()

Get lower bound value of a model.

model_from_string(model_str[, verbose])

Load Booster from a string.

model_to_string([num_iteration, ...])

Save Booster and GPmodel to string.

num_feature()

Get number of features.

num_model_per_iteration()

Get number of models per iteration.

num_trees()

Get number of weak sub-models.

predict(data[, start_iteration, ...])

Make a prediction.

refit(data, label[, decay_rate])

Refit the existing Booster by new data.

reset_parameter(params)

Reset parameters of Booster.

rollback_one_iter()

Rollback one iteration.

save_model(filename[, num_iteration, ...])

Save Booster and GPModel to file.

set_attr(**kwargs)

Set attributes to the Booster.

set_network(machines[, local_listen_port, ...])

Set the network configuration.

set_train_data_name(name)

Set the name to the training Dataset.

shuffle_models([start_iteration, end_iteration])

Shuffle models.

trees_to_dataframe()

Parse the fitted model and return in an easy-to-read pandas DataFrame.

update([train_set, fobj])

Update Booster for one iteration.

upper_bound()

Get upper bound value of a model.

add_valid(data, name)[source]

Add validation data.

Parameters:
  • data (Dataset) – Validation data.

  • name (string) – Name of validation data.

Returns:

self – Booster with set validation data.

Return type:

Booster

attr(key)[source]

Get attribute string from the Booster.

Parameters:

key (string) – The name of the attribute.

Returns:

value – The attribute value. Returns None if attribute does not exist.

Return type:

string or None

current_iteration()[source]

Get the index of the current iteration.

Returns:

cur_iter – The index of the current iteration.

Return type:

int

dump_model(num_iteration=None, start_iteration=0, importance_type='split')[source]

Dump Booster to JSON format.

Parameters:
  • num_iteration (int or None, optional (default=None)) – Index of the iteration that should be dumped. If None, if the best iteration exists, it is dumped; otherwise, all iterations are dumped. If <= 0, all iterations are dumped.

  • start_iteration (int, optional (default=0)) – Start index of the iteration that should be dumped.

  • importance_type (string, optional (default="split")) – What type of feature importance should be dumped. If “split”, result contains numbers of times the feature is used in a model. If “gain”, result contains total gains of splits which use the feature.

Returns:

json_repr – JSON format of Booster.

Return type:

dict

eval(data, name, feval=None)[source]

Evaluate for data.

Parameters:
  • data (Dataset) – Data for the evaluating.

  • name (string) – Name of the data.

  • feval (callable or None, optional (default=None)) –

    Customized evaluation function. Should accept two parameters: preds, eval_data, and return (eval_name, eval_result, is_higher_better) or list of such tuples.

    predslist or numpy 1-D array

    The predicted values.

    eval_dataDataset

    The evaluation dataset.

    eval_namestring

    The name of evaluation function (without whitespaces).

    eval_resultfloat

    The eval result.

    is_higher_betterbool

    Is eval result higher better, e.g. AUC is is_higher_better.

    For binary task, the preds is probability of positive class (or margin in case of specified fobj). For multi-class task, the preds is group by class_id first, then group by row_id. If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].

Returns:

result – List with evaluation results.

Return type:

list

eval_train(feval=None)[source]

Evaluate for training data.

Parameters:

feval (callable or None, optional (default=None)) –

Customized evaluation function. Should accept two parameters: preds, train_data, and return (eval_name, eval_result, is_higher_better) or list of such tuples.

predslist or numpy 1-D array

The predicted values.

train_dataDataset

The training dataset.

eval_namestring

The name of evaluation function (without whitespaces).

eval_resultfloat

The eval result.

is_higher_betterbool

Is eval result higher better, e.g. AUC is is_higher_better.

For binary task, the preds is probability of positive class (or margin in case of specified fobj). For multi-class task, the preds is group by class_id first, then group by row_id. If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].

Returns:

result – List with evaluation results.

Return type:

list

eval_valid(feval=None)[source]

Evaluate for validation data.

Parameters:

feval (callable or None, optional (default=None)) –

Customized evaluation function. Should accept two parameters: preds, valid_data, and return (eval_name, eval_result, is_higher_better) or list of such tuples.

predslist or numpy 1-D array

The predicted values.

valid_dataDataset

The validation dataset.

eval_namestring

The name of evaluation function (without whitespaces).

eval_resultfloat

The eval result.

is_higher_betterbool

Is eval result higher better, e.g. AUC is is_higher_better.

For binary task, the preds is probability of positive class (or margin in case of specified fobj). For multi-class task, the preds is group by class_id first, then group by row_id. If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].

Returns:

result – List with evaluation results.

Return type:

list

feature_importance(importance_type='split', iteration=None)[source]

Get feature importances.

Parameters:
  • importance_type (string, optional (default="split")) – How the importance is calculated. If “split”, result contains numbers of times the feature is used in a model. If “gain”, result contains total gains of splits which use the feature.

  • iteration (int or None, optional (default=None)) – Limit number of iterations in the feature importance calculation. If None, if the best iteration exists, it is used; otherwise, all trees are used. If <= 0, all trees are used (no limits).

Returns:

result – Array with feature importances.

Return type:

numpy array

feature_name()[source]

Get names of features.

Returns:

result – List with names of features.

Return type:

list

free_dataset()[source]

Free Booster’s Datasets.

Returns:

self – Booster without Datasets.

Return type:

Booster

free_network()[source]

Free Booster’s network.

Returns:

self – Booster with freed network.

Return type:

Booster

get_leaf_output(tree_id, leaf_id)[source]

Get the output of a leaf.

Parameters:
  • tree_id (int) – The index of the tree.

  • leaf_id (int) – The index of the leaf in the tree.

Returns:

result – The output of the leaf.

Return type:

float

get_split_value_histogram(feature, bins=None, xgboost_style=False)[source]

Get split value histogram for the specified feature.

Parameters:
  • feature (int or string) –

    The feature name or index the histogram is calculated for. If int, interpreted as index. If string, interpreted as name.

    Warning

    Categorical features are not supported.

  • bins (int, string or None, optional (default=None)) – The maximum number of bins. If None, or int and > number of unique split values and xgboost_style=True, the number of bins equals number of unique split values. If string, it should be one from the list of the supported values by numpy.histogram() function.

  • xgboost_style (bool, optional (default=False)) – Whether the returned result should be in the same form as it is in XGBoost. If False, the returned value is tuple of 2 numpy arrays as it is in numpy.histogram() function. If True, the returned value is matrix, in which the first column is the right edges of non-empty bins and the second one is the histogram values.

Returns:

  • result_tuple (tuple of 2 numpy arrays) – If xgboost_style=False, the values of the histogram of used splitting values for the specified feature and the bin edges.

  • result_array_like (numpy array or pandas DataFrame (if pandas is installed)) – If xgboost_style=True, the histogram of used splitting values for the specified feature.

lower_bound()[source]

Get lower bound value of a model.

Returns:

lower_bound – Lower bound value of the model.

Return type:

double

model_from_string(model_str, verbose=False)[source]

Load Booster from a string.

Parameters:
  • model_str (string) – Model will be loaded from this string.

  • verbose (bool, optional (default=True)) – Whether to print messages while loading model.

Returns:

self – Loaded Booster object.

Return type:

Booster

model_to_string(num_iteration=None, start_iteration=0, importance_type='split', save_raw_data=False, **kwargs)[source]

Save Booster and GPmodel to string.

Parameters:
  • num_iteration (int or None, optional (default=None)) – Index of the iteration that should be saved. If None, if the best iteration exists, it is saved; otherwise, all iterations are saved. If <= 0, all iterations are saved.

  • start_iteration (int, optional (default=0)) – Start index of the iteration that should be saved.

  • importance_type (string, optional (default="split")) – What type of feature importance should be saved. If “split”, result contains numbers of times the feature is used in a model. If “gain”, result contains total gains of splits which use the feature.

  • save_raw_data (bool (default=False)) – If true, the raw data (predictor / covariate data) for the Booster is also saved. Enable this option if you want to change ‘start_iteration’ or ‘num_iteration’ at prediction time after loading.

  • **kwargs – Other parameters for the prediction function. This is only used when there is a gp_model and when save_raw_data=False.

Returns:

str_repr – String representation of Booster and GPmodel.

Return type:

string

num_feature()[source]

Get number of features.

Returns:

num_feature – The number of features.

Return type:

int

num_model_per_iteration()[source]

Get number of models per iteration.

Returns:

model_per_iter – The number of models per iteration.

Return type:

int

num_trees()[source]

Get number of weak sub-models.

Returns:

num_trees – The number of weak sub-models.

Return type:

int

predict(data, start_iteration=0, num_iteration=None, pred_latent=False, pred_leaf=False, pred_contrib=False, data_has_header=False, is_reshape=True, group_data_pred=None, group_rand_coef_data_pred=None, gp_coords_pred=None, gp_rand_coef_data_pred=None, cluster_ids_pred=None, predict_cov_mat=False, predict_var=False, sample_posterior=False, num_post_samples=100, cov_pars=None, offset_pred=None, ignore_gp_model=False, raw_score=None, vecchia_pred_type=None, num_neighbors_pred=None, **kwargs)[source]

Make a prediction.

Parameters:
  • data (string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse) – Data source for prediction. If string, it represents the path to txt file.

  • start_iteration (int, optional (default=0)) – Start index of the iteration to predict. If <= 0, starts from the first iteration.

  • num_iteration (int or None, optional (default=None)) – Total number of iterations used in the prediction. If None, if the best iteration exists and start_iteration <= 0, the best iteration is used; otherwise, all iterations from start_iteration are used (no limits). If <= 0, all iterations from start_iteration are used (no limits).

  • pred_latent (bool, optional (default=False)) – If True latent variables, both fixed effects (tree-ensemble) and random effects (gp_model) are predicted. Otherwise, the response variable (label) is predicted. Depending on how the argument ‘pred_latent’ is set, different values are returned from this function; see the ‘Returns’ section for more details. If there is no gp_model, this argument corresponds to ‘raw_score’ in LightGBM.

  • pred_leaf (bool, optional (default=False)) – Whether to predict leaf index.

  • pred_contrib (bool, optional (default=False)) –

    Whether to predict feature contributions.

    Note

    If you want to get more explanations for your model’s predictions using SHAP values, like SHAP interaction values, you can install the shap package (https://github.com/slundberg/shap). Note that unlike the shap package, with pred_contrib we return a matrix with an extra column, where the last column is the expected value.

  • data_has_header (bool, optional (default=False)) – Whether the data has header. Used only if data is string.

  • is_reshape (bool, optional (default=True)) – If True, result is reshaped to [nrow, ncol].

  • group_data_pred (numpy array or pandas DataFrame with numeric or string data or None, optional (default=None)) – Labels of group levels for grouped random effects. Used only if the Booster has a gp_model

  • group_rand_coef_data_pred (numpy array or pandas DataFrame with numeric data or None, optional (default=None)) – Covariate data for grouped random coefficients. Used only if the Booster has a gp_model

  • gp_coords_pred (numpy array or pandas DataFrame with numeric data or None, optional (default=None)) – Coordinates (features) for Gaussian process. Used only if the Booster has a gp_model

  • gp_rand_coef_data_pred (numpy array or pandas DataFrame with numeric data or None, optional (default=None)) – Covariate data for Gaussian process random coefficients. Used only if the Booster has a gp_model

  • cluster_ids_pred (list, numpy 1-D array, pandas Series / one-column DataFrame with integer data or None, optional (default=None)) – IDs / labels indicating independent realizations of random effects / Gaussian processes (same values = same process realization). Used only if the Booster has a gp_model

  • predict_cov_mat (bool, optional (default=False)) – If True, the (posterior) predictive covariance is calculated in addition to the (posterior) predictive mean. Used only if the Booster has a gp_model

  • predict_var (bool, optional (default=False)) – If True, (posterior) predictive variances are calculated in addition to the (posterior) predictive mean. Used only if the Booster has a gp_model

  • sample_posterior (bool (default=False)) – If True, samples from the posterior are drawn

  • num_post_samples (integer (default=100)) – Number of posterior samples to draw if ‘sample_posterior=True’

  • cov_pars (numpy array or None, optional (default = None)) – A vector containing covariance parameters which are used if the gp_model has not been trained or if predictions should be made for other parameters than the estimated ones

  • offset_pred (numpy array or None, optional (default=None)) – Offsets for prediction: additional fixed effects contributions that are added to the predictor for the prediction points. The length of this vector needs to equal the number of prediction points.

  • ignore_gp_model (bool, optional (default=False)) – If True, predictions are only made for the tree ensemble part and the gp_model is ignored

  • raw_score (bool or None, discontinued (default=None)) – This is discontinued. Use the renamed equivalent argument ‘pred_latent’ instead

  • vecchia_pred_type (string, optional (default=None)) – The type of Vecchia approximation used for making predictions. This is discontinued here. Use the function ‘set_prediction_data’ of the ‘gp_model’ to specify this

  • num_neighbors_pred (integer or None, optional (default=None)) – The number of neighbors for making predictions. This is discontinued here. Use the function ‘set_prediction_data’ of the ‘gp_model’ to specify this

  • **kwargs – Other parameters for the prediction.

Returns:

result – If there is a gp_model, the result dict contains the following entries.

  1. If ‘pred_latent’ is False (=default), the dict contains the following 2 entries:

    result[‘response_mean’]numpy array

    Predictive means of the response variable (Label) taking into account both the fixed effects (tree-ensemble) and the random effects (gp_model)

    result[‘response_var’]numpy array

    Predictive covariances or variances of the response variable (only if ‘predict_var’ or ‘predict_cov’ is True)

  2. If ‘pred_latent’ is True, the dict contains the following 3 entries:

    result[‘fixed_effect’]numpy array

    Predictions from the tree-ensemble.

    result[‘random_effect_mean’]numpy array

    Predictive means of the gp_model.

    result[‘random_effect_cov’]numpy array

    Predictive covariances or variances of the gp_model (only if ‘predict_var’ or ‘predict_cov’ is True)

If there is no gp_model or ‘pred_contrib’ or ‘ignore_gp_model’ are True, the result contains predictions from the tree-booster only.

Return type:

either a dict with numpy arrays or a single numpy array depending on whether there is a gp_model or not

Example

>>> gp_model = gpb.GPModel(group_data=group, likelihood="gaussian")
>>> data_train = gpb.Dataset(X, y)
>>> params = {'objective': 'regression_l2', 'verbose': 0}
>>> bst = gpb.train(params=params, train_set=data_train,  gp_model=gp_model,
>>>                 num_boost_round=100)
>>> # 1. Predict latent variable (pred_latent=True) and variance
>>> pred = bst.predict(data=Xtest, group_data_pred=group_test, predict_var=True,
>>>                    pred_latent=True)
>>> # pred_resp['fixed_effect']: predictions for the latent fixed effects / tree ensemble
>>> # pred_resp['random_effect_mean']: mean predictions for the random effects
>>> # pred_resp['random_effect_cov']: predictive (co-)variances (if predict_var=True) of the random effects
>>> # 2. Predict response variable (pred_latent=False)
>>> pred_resp = bst.predict(data=Xtest, group_data_pred=group_test, pred_latent=False)
>>> # pred_resp['response_mean']: mean predictions of the response variable
>>> #   which combines predictions from the tree ensemble and the random effects
>>> # pred_resp['response_var']: predictive variances (if predict_var=True)
refit(data, label, decay_rate=0.9, **kwargs)[source]

Refit the existing Booster by new data.

Parameters:
  • data (string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse) – Data source for refit. If string, it represents the path to txt file.

  • label (list, numpy 1-D array or pandas Series / one-column DataFrame) – Label for refit.

  • decay_rate (float, optional (default=0.9)) – Decay rate of refit, will use leaf_output = decay_rate * old_leaf_output + (1.0 - decay_rate) * new_leaf_output to refit trees.

  • **kwargs – Other parameters for refit. These parameters will be passed to predict method.

Returns:

result – Refitted Booster.

Return type:

Booster

reset_parameter(params)[source]

Reset parameters of Booster.

Parameters:

params (dict) – New parameters for Booster.

Returns:

self – Booster with new parameters.

Return type:

Booster

rollback_one_iter()[source]

Rollback one iteration.

Returns:

self – Booster with rolled back one iteration.

Return type:

Booster

save_model(filename, num_iteration=None, start_iteration=0, importance_type='split', save_raw_data=False, **kwargs)[source]

Save Booster and GPModel to file.

Parameters:
  • filename (string) – Filename to save Booster.

  • num_iteration (int or None, optional (default=None)) – Index of the iteration that should be saved. If None, if the best iteration exists, it is saved; otherwise, all iterations are saved. If <= 0, all iterations are saved.

  • start_iteration (int, optional (default=0)) – Start index of the iteration that should be saved.

  • importance_type (string, optional (default="split")) – What type of feature importance should be saved. If “split”, result contains numbers of times the feature is used in a model. If “gain”, result contains total gains of splits which use the feature.

  • save_raw_data (bool (default=False)) – If true, the raw data (predictor / covariate data) for the Booster is also saved. Enable this option if you want to change ‘start_iteration’ or ‘num_iteration’ at prediction time after loading.

  • **kwargs – Other parameters for the prediction function. This is only used when there is a gp_model and when save_raw_data=False.

Returns:

self – Returns self. After loading, the GPModel can be accessed via the ‘gp_model’ attribute.

Return type:

Booster and attached GPModel

set_attr(**kwargs)[source]

Set attributes to the Booster.

Parameters:

**kwargs – The attributes to set. Setting a value to None deletes an attribute.

Returns:

self – Booster with set attributes.

Return type:

Booster

set_network(machines, local_listen_port=12400, listen_time_out=120, num_machines=1)[source]

Set the network configuration.

Parameters:
  • machines (list, set or string) – Names of machines.

  • local_listen_port (int, optional (default=12400)) – TCP listen port for local machines.

  • listen_time_out (int, optional (default=120)) – Socket time-out in minutes.

  • num_machines (int, optional (default=1)) – The number of machines for parallel learning application.

Returns:

self – Booster with set network.

Return type:

Booster

set_train_data_name(name)[source]

Set the name to the training Dataset.

Parameters:

name (string) – Name for the training Dataset.

Returns:

self – Booster with set training Dataset name.

Return type:

Booster

shuffle_models(start_iteration=0, end_iteration=-1)[source]

Shuffle models.

Parameters:
  • start_iteration (int, optional (default=0)) – The first iteration that will be shuffled.

  • end_iteration (int, optional (default=-1)) – The last iteration that will be shuffled. If <= 0, means the last available iteration.

Returns:

self – Booster with shuffled models.

Return type:

Booster

trees_to_dataframe()[source]

Parse the fitted model and return in an easy-to-read pandas DataFrame.

The returned DataFrame has the following columns.

  • tree_index : int64, which tree a node belongs to. 0-based, so a value of 6, for example, means “this node is in the 7th tree”.

  • node_depth : int64, how far a node is from the root of the tree. The root node has a value of 1, its direct children are 2, etc.

  • node_index : string, unique identifier for a node.

  • left_child : string, node_index of the child node to the left of a split. None for leaf nodes.

  • right_child : string, node_index of the child node to the right of a split. None for leaf nodes.

  • parent_index : string, node_index of this node’s parent. None for the root node.

  • split_feature : string, name of the feature used for splitting. None for leaf nodes.

  • split_gain : float64, gain from adding this split to the tree. NaN for leaf nodes.

  • threshold : float64, value of the feature used to decide which side of the split a record will go down. NaN for leaf nodes.

  • decision_type : string, logical operator describing how to compare a value to threshold. For example, split_feature = "Column_10", threshold = 15, decision_type = "<=" means that records where Column_10 <= 15 follow the left side of the split, otherwise follows the right side of the split. None for leaf nodes.

  • missing_direction : string, split direction that missing values should go to. None for leaf nodes.

  • missing_type : string, describes what types of values are treated as missing.

  • value : float64, predicted value for this leaf node, multiplied by the learning rate.

  • weight : float64 or int64, sum of hessian (second-order derivative of objective), summed over observations that fall in this node.

  • count : int64, number of records in the training data that fall into this node.

Returns:

result – Returns a pandas DataFrame of the parsed model.

Return type:

pandas DataFrame

update(train_set=None, fobj=None)[source]

Update Booster for one iteration.

Parameters:
  • train_set (Dataset or None, optional (default=None)) – Training data. If None, last training data is used.

  • fobj (callable or None, optional (default=None)) –

    Customized objective function. Should accept two parameters: preds, train_data, and return (grad, hess).

    predslist or numpy 1-D array

    The predicted values.

    train_dataDataset

    The training dataset.

    gradlist or numpy 1-D array

    The value of the first order derivative (gradient) for each sample point.

    hesslist or numpy 1-D array

    The value of the second order derivative (Hessian) for each sample point.

    For binary task, the preds is probability of positive class (or margin in case of specified fobj). For multi-class task, the preds is group by class_id first, then group by row_id. If you want to get i-th row preds in j-th class, the access way is score[j * num_data + i] and you should group grad and hess in this way as well.

Returns:

is_finished – Whether the update was successfully finished.

Return type:

bool

upper_bound()[source]

Get upper bound value of a model.

Returns:

upper_bound – Upper bound value of the model.

Return type:

double