gpboost.tune_pars_TPE_algorithm_optuna

gpboost.tune_pars_TPE_algorithm_optuna(search_space, n_trials, X, y, gp_model=None, max_num_boost_round=1000, early_stopping_rounds=None, metric=None, folds=None, nfold=5, cv_seed=0, tpe_seed=0, params=None, verbose_train=0, verbose_eval=1, use_gp_model_for_validation=True, train_gp_model_cov_pars=True, feval=None, categorical_feature='auto')[source]

Function for choosing tuning parameters using the TPE (Tree-structured Parzen Estimator) algorithm implemented in optuna

Parameters:
  • search_space (dict) – The range for every parameter over which a search is done. The format for every entry of the dict must be ‘parameter_name’: [lower, upper]. See https://github.com/fabsig/GPBoost/blob/master/docs/Main_parameters.rst#tuning-parameters–hyperparameters-for-the-tree-boosting-part

  • n_trials (int) – The number of trials for the TPESampler.

  • X (string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse or list of numpy arrays) – Predictor variables data for creating a gpb.Dataset. If string, it represents the path to txt file.

  • y (list, numpy 1-D array, pandas Series / one-column DataFrame or None, optional (default=None)) – Response variable / label data.

  • gp_model (GPModel or None, optional (default=None)) – GPModel object for the GPBoost algorithm

  • max_num_boost_round (int, optional (default=1000)) – Maximal number of boosting iterations.

  • early_stopping_rounds (int or None, optional (default=None)) – Activates early stopping. The metric needs to improve at least every early_stopping_rounds round(s) to continue.

  • metric (string, list of strings or None, optional (default=None)) –

    Evaluation metric to be monitored when doing parameter tuning. If not None, the metric in params will be overridden.

    • Default =”test_neg_log_likelihood” if there is a GPModel

    • Non-exhaustive list of supported metrics: “test_neg_log_likelihood”, “mse”, “rmse”, “mae”, “crps_gaussian”, “auc”, “average_precision”, “binary_logloss”, “binary_error”

    • See https://gpboost.readthedocs.io/en/latest/Parameters.html#metric-parameters for a complete list of valid metrics

  • folds (generator or iterator of (train_idx, test_idx) tuples, scikit-learn splitter object or None, optional (default=None)) – If generator or iterator, it should yield the train and test indices for each fold. If object, it should be one of the scikit-learn splitter classes (https://scikit-learn.org/stable/modules/classes.html#splitter-classes) and have split method. This argument has highest priority over other data split arguments.

  • nfold (int, optional (default=5)) – Number of folds in CV.

  • cv_seed (int, optional (default=0)) – Seed used to generate folds if CV is used (passed to numpy.random.seed).

  • tpe_seed (int, optional (default=0)) – Seed for TPESampler of optuna

  • params (dict, optional (default=None)) – Other parameters not included in search_space.

  • verbose_train (int, optional (default=0)) – Controls the level of verbosity of the tree-boosting part during estimation < 0: Fatal, = 0: Error (Warning), = 1: Info, > 1: Debug

  • verbose_eval (int or None, optional (default=1)) – Whether to display information on the progress of tuning parameter choice. If None or 0, verbose is of. If = 1, summary progress information is displayed for every trial of a parameter combination. If >= 2, detailed progress is displayed at every boosting stage for every parameter combination.

  • use_gp_model_for_validation (bool, optional (default=True)) – If True, the ‘gp_model’ (Gaussian process and/or random effects) is also used (in addition to the tree model) for calculating predictions on the validation data. If False, the ‘gp_model’ (random effects part) is ignored for making predictions and only the tree ensemble is used for making predictions for calculating the validation / test error.

  • train_gp_model_cov_pars (bool, optional (default=True)) – If True, the covariance parameters of the ‘gp_model’ (Gaussian process and/or random effects) are estimated in every boosting iterations, otherwise the ‘gp_model’ parameters are not estimated. In the latter case, you need to either estimate them beforehand or provide values via the ‘init_cov_pars’ parameter when creating the ‘gp_model’

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

    Customized evaluation function. If more than one evaluation function is provided, only the first evaluation function will be used to choose tuning parameters Each 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]. To ignore the default metric corresponding to the used objective, set metric to the string "None".

  • categorical_feature (list of strings or int, or 'auto', optional (default="auto")) – Categorical features. If list of int, interpreted as indices. If list of strings, interpreted as feature names (need to specify feature_name as well). If ‘auto’ and data is pandas DataFrame, pandas unordered categorical columns are used. All values in categorical features should be less than int32 max value (2147483647). Large values could be memory consuming. Consider using consecutive integers starting from zero. All negative values in categorical features will be treated as missing values. The output cannot be monotonically constrained with respect to a categorical feature.

Returns:

return – Dictionary with the best parameter combination and score The dictionary has the following format: {‘best_params’: best_params, ‘best_num_boost_round’: best_num_boost_round, ‘best_score’: best_score}

Return type:

dict

Example

>>> # Define search space
>>> # Note: if the best combination found below is close to the bounday for a paramter, you might want to extend the corresponding range
>>> search_space = { 'learning_rate': [0.001, 10],
>>>   'min_data_in_leaf': [1, 1000],
>>>   'max_depth': [-1,-1], # -1 means no depth limit as we tune 'num_leaves'. Can also additionally tune 'max_depth', e.g., 'max_depth': [-1,10]
>>>   'num_leaves': [2, 1024],
>>>   'lambda_l2': [0, 100],
>>>   'max_bin': [63, np.min([10000,n])],
>>>   'line_search_step_length': [True, False] }
>>> metric = "mse" # Define metric
>>> if likelihood in ("bernoulli_probit", "bernoulli_logit"):
>>>   metric = "binary_logloss"
>>> # Note: can also use metric = "test_neg_log_likelihood". For more options, see https://github.com/fabsig/GPBoost/blob/master/docs/Parameters.rst#metric-parameters
>>> gp_model = gpb.GPModel(group_data=group, likelihood=likelihood)
>>> # Run parameter optimization using the TPE algorithm and 4-fold CV
>>> opt_params = gpb.tune_pars_TPE_algorithm_optuna(search_space=search_space, n_trials=100,
>>>                                                 X=X, y=y, gp_model=gp_model,
>>>                                                 max_num_boost_round=1000, early_stopping_rounds=20,
>>>                                                 nfold=5, metric=metric,
>>>                                                 cv_seed=4, tpe_seed=1)
>>> print("Best parameters: " + str(opt_params['best_params']))
>>> print("Best number of iterations: " + str(opt_params['best_iter']))
>>> print("Best score: " + str(opt_params['best_score']))
>>>
>>> # Alternatively and faster: using manually defined validation data instead of cross-validation
>>> np.random.seed(10)
>>> permute_aux = np.random.permutation(n)
>>> train_tune_idx = permute_aux[0:int(0.8 * n)] # use 20% of the data as validation data
>>> valid_tune_idx = permute_aux[int(0.8 * n):n]
>>> folds = [(train_tune_idx, valid_tune_idx)]
>>> opt_params = gpb.tune_pars_TPE_algorithm_optuna(search_space=search_space, n_trials=100,
>>>                                                 X=X, y=y, gp_model=gp_model,
>>>                                                 max_num_boost_round=1000, early_stopping_rounds=20,
>>>                                                 folds=folds, metric=metric,
>>>                                                 cv_seed=4, tpe_seed=1)
Authors:

Fabio Sigrist