Sub topic 16
Tuning hyperparameters efficiently
This chapter assumes you can train a LightGBM or CatBoost model with early stopping on a validation set. It also assumes you know what num_leaves, learning_rate and feature_fraction do. Here the question is how to spend a limited tuning budget well.
Why tuning is mostly about order
Gradient boosted trees have dozens of parameters, but most of the gain comes from a few. Searching all of them at once wastes compute. A better approach works in stages, from cheap and high-impact choices to expensive and low-impact ones.
The workflow has five steps:
- Fix a trustworthy validation scheme first. A noisy or leaky split makes every later comparison meaningless.
- Train with defaults and a moderately high learning rate. This gives a baseline and a feel for run time.
- Tune the parameters that control tree complexity and randomness.
- Lower the learning rate and let early stopping choose the number of trees.
- Evaluate once on a held-out test set that tuning never touched.
Treat the number of trees as a derived value
Do not tune n_estimators (or num_boost_round, or CatBoost iterations) directly. Set it to a large ceiling and let early stopping find the best iteration for each candidate. Then the tree count adjusts to each setting. A candidate with a small learning_rate gets more trees, and one with large leaves gets fewer.
The learning rate trades quality against time. A smaller rate usually gives a slightly better model but needs more trees. During the search, keep it at 0.05 to 0.1 so each trial is fast. Lower it only for the final fit.
Which parameters to search first
| Library | Parameter | Typical search range | Effect |
|---|---|---|---|
| LightGBM | `num_leaves` | 8 to 256 (integer) | Main complexity control for leaf-wise trees |
| LightGBM | `min_data_in_leaf` | 5 to 200 (integer) | Larger values block splits on tiny groups |
| LightGBM | `feature_fraction` | 0.5 to 1.0 | Column subsampling per tree |
| LightGBM | `bagging_fraction` with `bagging_freq=1` | 0.5 to 1.0 | Row subsampling per tree |
| LightGBM | `lambda_l2` | 1e-3 to 10 (log scale) | Shrinks leaf values |
| CatBoost | `depth` | 4 to 10 | Complexity of symmetric trees |
| CatBoost | `l2_leaf_reg` | 1 to 30 (log scale) | Shrinks leaf values |
| CatBoost | `random_strength` | 0 to 5 | Noise added to split scores |
| CatBoost | `one_hot_max_size` | 2 to 255 | Cutoff for one-hot versus target-statistics encoding |
Sample parameters that span orders of magnitude, such as lambda_l2 and l2_leaf_reg, on a log scale. A uniform draw from 0.001 to 10 puts almost every sample above 0.1.
A rule of thumb for LightGBM: keep num_leaves well below 2 ** max_depth if you set max_depth. A leaf-wise tree with 255 leaves and max_depth=5 can never use most of those leaves.
Random search as a strong baseline
Random search often matches grid search at a fraction of the cost. Only a few parameters matter for any given dataset, and random sampling tries many distinct values of each one. A grid repeats the same few values.
This example runs 20 random trials against a validation set. It uses only LightGBM, scikit-learn and NumPy.
import numpy as np
import lightgbm as lgb
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_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
X_train, X_valid, y_train, y_valid = train_test_split(
X_rest, y_rest, test_size=0.25, random_state=0
)
rng = np.random.default_rng(0)
results = []
for trial in range(20):
params = {
"objective": "regression",
"metric": "rmse",
"learning_rate": 0.1,
"num_leaves": int(rng.integers(8, 129)),
"min_data_in_leaf": int(rng.integers(5, 101)),
"feature_fraction": float(rng.uniform(0.5, 1.0)),
"lambda_l2": float(10 ** rng.uniform(-3, 1)),
"verbose": -1,
"seed": trial,
}
train_set = lgb.Dataset(X_train, label=y_train)
valid_set = lgb.Dataset(X_valid, label=y_valid, reference=train_set)
booster = lgb.train(
params,
train_set,
num_boost_round=1000,
valid_sets=[valid_set],
callbacks=[lgb.early_stopping(30, verbose=False)],
)
score = booster.best_score["valid_0"]["rmse"]
results.append((score, booster.best_iteration, params))
results.sort(key=lambda r: r[0])
best_score, best_iter, best_params = results[0]
print(f"best validation RMSE {best_score:.4f} at {best_iter} trees")
final_params = {**best_params, "learning_rate": 0.02}
train_set = lgb.Dataset(X_train, label=y_train)
valid_set = lgb.Dataset(X_valid, label=y_valid, reference=train_set)
final = lgb.train(
final_params,
train_set,
num_boost_round=5000,
valid_sets=[valid_set],
callbacks=[lgb.early_stopping(100, verbose=False)],
)
pred = final.predict(X_test, num_iteration=final.best_iteration)
rmse = float(np.sqrt(np.mean((pred - y_test) ** 2)))
print(f"test RMSE {rmse:.4f} with {final.best_iteration} trees")The code builds a new lgb.Dataset for every trial. Parameters such as min_data_in_leaf interact with LightGBM's feature pre-filtering when the Dataset is built. If you reuse one Dataset across trials, pass params={"feature_pre_filter": False} to it. Otherwise LightGBM can raise an error when a later trial changes min_data_in_leaf.
Smarter search: Bayesian and pruning methods
Libraries such as Optuna replace random draws with a model of which regions of the search space scored well. They also support pruning, which stops a trial early when its intermediate validation score is clearly worse than other trials at the same iteration. Pruning matters most when each trial takes minutes. For a search of fewer than about 30 trials, random search is usually just as good and has no extra dependency.
Avoiding a self-deceiving search
The best validation score out of many trials is biased upward. You picked it because it was the highest of many noisy numbers. Three habits limit the damage.
- Report the final metric on a test set that no trial saw. In the example above,
X_testis touched once. - Use cross-validation (
lgb.cv, orcvin CatBoost) when the data is small or the validation score is noisy. It costs about k times more per trial. - Keep the split design the same as in production. For time-ordered data, use time-based splits, not shuffled ones. For grouped rows, such as several rows per customer, keep each group on one side of the split.
Tuning CatBoost
CatBoost's defaults are strong, so a small search often suffices. Start with depth, l2_leaf_reg and learning_rate. CatBoost can also pick a learning rate automatically based on the dataset size and iteration count, so a first run with no rate set is a reasonable baseline. Symmetric trees make each tree structurally simple, so raising depth from 6 to 10 grows the number of leaves as 2 to the power of depth. Time per tree grows with it, and a depth above 8 is rarely worth the cost. If your data has high-cardinality categorical columns, one_hot_max_size and the categorical encoding settings can matter more than any numeric parameter.
Budgeting time
- Use fewer rows for early search stages, for example a 20 to 30 percent sample, and confirm the top few candidates on the full data.
- Use more threads for large data, but run parallel trials with
num_threads=1each to avoid oversubscribing cores. - Log every trial's parameters, best iteration and score so you can reproduce the winner.
Exercise
A random search of 200 trials reports a best validation RMSE of 0.42. The same model scores 0.47 on an untouched test set. Give the most likely cause and two ways to reduce the gap.
Show answer
The search overfit the validation split. Picking the best of 200 noisy scores biases the validation result downward in error. Two fixes are to use cross-validation or a larger validation set so each score is less noisy, and to run fewer trials or a narrower search space. Reporting the test score once, as the honest estimate, is also required.
Exercise
Why should you fix a moderate learning rate and a large num_boost_round with early stopping during the search, instead of searching n_estimators as a parameter?
Show answer
Early stopping finds the best tree count for each candidate automatically, so the count adapts to the other parameters. Searching it adds a dimension for no benefit. A moderate learning rate keeps each trial fast, and you lower it only for the final fit.