---
url: /dev/guides/tune-gradient-boosting.md
description: >-
  How learning rate, number of trees, depth, subsampling, L2 regularization and
  early stopping change scikit-link's relational gradient boosting.
---

# Tune relational gradient boosting

**Gradient boosting adds shallow relational trees one after another, so its
parameters trade the size of each step against the number of steps. Fix the
reach and the questions first, then tune the size of the trees together with
the learning rate and the number of trees, then subsampling and L2.** The relational parameters, such as
`max_relationship_depth` and `max_conditions`, work as in
[trees and forests](./tune-trees-and-forests#reach). Read
[where to start](./tuning) first for the order of the steps.

## Setup

```python
from sklearn.model_selection import StratifiedKFold, validation_curve
from sklink.datasets import make_relational_classification
from sklink.ensemble import RelationalGradientBoostingClassifier

db, X, y = make_relational_classification(
    600, signal="mixed", n_noise_tables=2, random_state=0
)
cv = StratifiedKFold(3, shuffle=True, random_state=0)


def curve(model, name, values):
    train, test = validation_curve(
        model, X, y, param_name=name, param_range=values, cv=cv
    )
    for value, a, b in zip(values, train.mean(1), test.mean(1)):
        print(f"{name}={value!s:<6} train {a:.3f}  test {b:.3f}")


boosting = RelationalGradientBoostingClassifier(
    db, entity="customers", key="customer_id", random_state=0
)
```

## Learning rate and number of trees {#learning-rate}

Each tree's contribution is multiplied by `learning_rate`. A smaller rate
needs more trees to reach the same training loss and usually generalizes
better; halving the rate needs about twice the trees. With a fixed 100
trees, a small rate may stop before it catches up, so compare rates with
early stopping, as in the next section.

```python
curve(boosting, "learning_rate", [0.03, 0.1, 0.3])
```

```text
learning_rate=0.03   train 0.998  test 0.960
learning_rate=0.1    train 1.000  test 0.967
learning_rate=0.3    train 1.000  test 0.960
```

## Stop early instead of searching the number of trees {#early-stopping}

With `n_iter_no_change`, the model holds out `validation_fraction` of the
training samples and stops when their loss has not improved by `tol` for
`n_iter_no_change` iterations, so a large `n_estimators` costs only the
trees it needs. `n_estimators_` says how many iterations it fitted. The
held-out rows are a random split of the rows of `X`, stratified for the
classifier: with cutoffs or several rows per entity, they share entities or
periods with the training rows, so stop on a held-out split of your own
instead.

```python
early = RelationalGradientBoostingClassifier(
    db,
    entity="customers",
    key="customer_id",
    learning_rate=0.05,
    n_estimators=1000,
    n_iter_no_change=10,
    random_state=0,
).fit(X, y)
print(early.n_estimators_)
```

```text
104
```

## Size of each tree {#size}

`max_depth` (default 3) sets how many questions combine in one step: depth 2
captures pairs of signals, depth 3 triples. `max_leaf_nodes` grows the tree
best-first instead, and `min_samples_leaf` keeps leaves from fitting a few
samples. With Newton trees, `min_weight_fraction_leaf` counts each sample by
its weight times its Hessian, so it bounds a leaf's share of the total
Hessian weight: a relative form of XGBoost's `min_child_weight`, on top of
`min_samples_leaf`.

```python
curve(boosting, "max_depth", [2, 3, 5])
curve(boosting, "min_samples_leaf", [1, 10, 40])
```

```text
max_depth=2      train 1.000  test 0.960
max_depth=3      train 1.000  test 0.967
max_depth=5      train 1.000  test 0.937
min_samples_leaf=1      train 1.000  test 0.967
min_samples_leaf=10     train 1.000  test 0.963
min_samples_leaf=40     train 1.000  test 0.970
```

## Subsampling and L2 regularization {#regularization}

`subsample` below 1.0 fits each tree on a random share of the samples, which
adds randomness like a forest's bootstrap. `l2_regularization` shrinks the
leaf values of the Newton trees towards zero, more for leaves with few
or confidently predicted samples, and a node splits only when its penalized
gain is positive.

```python
curve(boosting, "subsample", [0.5, 0.8, 1.0])
curve(boosting, "l2_regularization", [0.0, 1.0, 10.0])
```

```text
subsample=0.5    train 1.000  test 0.947
subsample=0.8    train 1.000  test 0.970
subsample=1.0    train 1.000  test 0.967
l2_regularization=0.0    train 1.000  test 0.967
l2_regularization=1.0    train 1.000  test 0.967
l2_regularization=10.0   train 0.999  test 0.968
```

The default stays at 0 because no penalty won consistently in our checks.
On RelBench F1 (three seeds, validation split), a penalty of 10 raised the
top 3 AUC from 0.853 to 0.861 and left the DNF AUC and the position MAE
where they were, while on synthetic data 1 and 10 moved the scores either
way by less than their spread across seeds. It costs no fit time, so it is
worth a place in a search, with values such as 1 and 10.

## Conditions and their penalty {#conditions}

Boosting fits many small trees to residuals, so a condition that only fits
noise costs more than in a single tree. `condition_penalty` (default 2 for
boosting) makes each learned condition pay the gain it would make by chance,
and `max_conditions` caps how many conditions one aggregate combines. On
small or noisy data, try a higher penalty or `max_conditions=0`.

```python
curve(boosting, "condition_penalty", [0, 2, 6])
curve(boosting, "max_conditions", [0, 2])
```

```text
condition_penalty=0      train 1.000  test 0.955
condition_penalty=2      train 1.000  test 0.967
condition_penalty=6      train 1.000  test 0.963
max_conditions=0      train 0.999  test 0.718
max_conditions=2      train 1.000  test 0.967
```

## Leaf weights of related rows {#leaf-weights}

`leaf_weights=2` adds a Relboost-style question, as in getML: each tree fits
a small tree of that depth over the rows each path reaches, on the
working responses of a random half of its samples, and asks about the sum or
the mean of the leaf weights of each sample's rows, such as
`mean_weights(orders: +0.4 [type == 'pickup'] -0.1 [type in ('economy', 'express', 'standard')])`. One
question then combines several filters of the same rows, where a learned
condition holds at most two. Each split of the small tree pays
`condition_penalty` like a learned condition. It is off by default: over
three seeds it raised the AUC on PKDD'99 loans from 0.921 to 0.924 and on a
synthetic ratio task from 0.936 to 0.945, left seven other synthetic tasks
unchanged, and moved RelBench F1 driver DNF by one seed up and one down.
Compare it with your own validation split; it fits about 10% slower.

## Newton or gradient trees {#criterion}

With the default `criterion="newton"`, each tree uses the gradient and the
Hessian of the loss, as XGBoost and LightGBM do.
`criterion="squared_error"` chooses the splits on the gradient alone and
then sets each leaf to a Newton step, as scikit-learn's
`GradientBoostingClassifier` does. `l2_regularization` needs
`criterion="newton"`.

```python
curve(boosting, "criterion", ["newton", "squared_error"])
```

```text
criterion=newton train 1.000  test 0.967
criterion=squared_error train 1.000  test 0.965
```

## Where to start a search {#ranges}

| Parameter | Default | Range to search | Notes |
| --- | --- | --- | --- |
| `learning_rate` | `0.1` | 0.02 to 0.3, log scale | Smaller with more trees |
| `n_estimators` | `100` | Large, with `n_iter_no_change` | Do not search it with early stopping |
| `max_depth` | `3` | 2 to 6 | |
| `min_samples_leaf` | `1` | 1 to 50 | |
| `subsample` | `1.0` | 0.5 to 1.0 | |
| `l2_regularization` | `0.0` | 1e-8 to 10, log scale | Needs `criterion="newton"`, and the squared error loss for the regressor |
| `condition_penalty` | `2.0` | 0 to 6 | Higher on small or noisy data |
| `max_conditions` | `2` | 0 to 2 | |
| `leaf_weights` | `0` | 0 or 2 | Off by default; compare it on your own validation split |
| `max_features` | `None` | 0.3 to 1.0 | Mostly a speed setting: faster, usually a little less accurate |
| `max_search_samples` | `2000` | 1000 to 5000, or `None` | A speed setting that only acts on nodes with more samples; `None` searches on all of them |

## Next steps

* [Tune trees and forests](./tune-trees-and-forests)
* [Relational gradient boosting](../tutorials/relational-gradient-boosting)
  for losses, staged predictions and explanations.
