Sub topic 16
Tuning hyperparameters efficiently
This chapter assumes you can train a LightGBM or CatBoost model with early stopping on a validation set, and that you know RMSE, log loss and AUC. Tuning means searching for settings that lower validation error without wasting compute.
Tune in a sensible order
Most of the gain comes from a few parameters. Fix the cheap ones first, then search the rest.
- Set
learning_rateto a moderate value such as 0.05 to 0.1. Let early stopping choose the number of trees. Never tune the tree count by hand. - Search tree complexity:
num_leavesandmin_data_in_leafin LightGBM,depthandl2_leaf_regin CatBoost. - Search randomness:
feature_fraction,bagging_fractionandbagging_freq. - At the end, lower
learning_rate(for example to 0.02) and retrain. Early stopping will pick a larger tree count.
| Parameter | Typical search range | Scale |
|---|---|---|
| `num_leaves` | 8 to 256 | log |
| `min_data_in_leaf` | 5 to 200 | log |
| `feature_fraction` | 0.5 to 1.0 | linear |
| `lambda_l2` | 1e-3 to 10 | log |
Prefer random or guided search to grids
A grid wastes trials on values of unimportant parameters. Random search tries a new value of every parameter on each trial. Guided search (Bayesian optimization, as in Optuna) uses past trials to choose the next one. Sample parameters like lambda_l2 on a log scale, because the useful values span orders of magnitude.
Example with Optuna
This script tunes LightGBM on the California housing data. Each trial uses early stopping, so the tree count is never a search parameter. It assumes optuna is installed (pip install optuna).
import lightgbm as lgb
import optuna
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
X, y = fetch_california_housing(return_X_y=True, as_frame=True)
X_train, X_valid, y_train, y_valid = train_test_split(
X, y, test_size=0.2, random_state=0
)
def objective(trial):
params = {
"n_estimators": 2000,
"learning_rate": 0.05,
"num_leaves": trial.suggest_int("num_leaves", 8, 256, log=True),
"min_child_samples": trial.suggest_int("min_child_samples", 5, 200, log=True),
"colsample_bytree": trial.suggest_float("colsample_bytree", 0.5, 1.0),
"reg_lambda": trial.suggest_float("reg_lambda", 1e-3, 10.0, log=True),
"subsample": 0.8,
"subsample_freq": 1,
"verbose": -1,
}
model = lgb.LGBMRegressor(**params)
model.fit(
X_train,
y_train,
eval_set=[(X_valid, y_valid)],
eval_metric="rmse",
callbacks=[lgb.early_stopping(50, verbose=False)],
)
trial.set_user_attr("best_iteration", model.best_iteration_)
return model.best_score_["valid_0"]["rmse"]
optuna.logging.set_verbosity(optuna.logging.WARNING)
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=30)
print(study.best_value)
print(study.best_params)
print(study.best_trial.user_attrs["best_iteration"])The sklearn names differ from the native ones: min_child_samples is min_data_in_leaf, colsample_bytree is feature_fraction, subsample is bagging_fraction, and reg_lambda is lambda_l2.
Common errors
- Tuning on the early-stopping set. The validation set picks both the tree count and the best parameters, so its score is optimistic. Keep a separate test set, or use nested cross-validation, for the final estimate.
- Overfitting the search. With few rows, hundreds of trials fit noise in the validation split. Use cross-validation or fewer trials.
- Searching too wide. Start with a few parameters and a small budget. Widen only if the best value sits at a range edge.
- Ignoring cost. Use a smaller subsample or a higher
learning_rateduring search, then retrain with the final settings.
Exercise
Your Optuna study's best num_leaves is 256, the top of the search range. What should you do, and why?
Show answer
Extend the range upward (and consider raising min_data_in_leaf to control overfitting), then rerun. A best value at the range edge means the true optimum may lie outside the range you searched.
Exercise
Why is the number of trees left out of the search space in the example?
Show answer
Early stopping picks the best tree count for each trial. Searching it as well wastes trials and makes scores harder to compare.