---
url: /stable/tutorials/relational-gradient-boosting.md
description: >-
  Gradient boosting of relational decision trees: learning rate, early stopping,
  staged predictions and quantile regression on related tables.
---

# Relational gradient boosting

**Relational gradient boosting adds small relational trees one after another.
Each new tree corrects the errors that the trees before it left on the
training samples, asking questions such as
`count(orders[amount > 100 & type == 'express']) > 0.5`. Its trees are
shallow, and it tells you after each tree how well it does.**

The models follow scikit-learn's
[`GradientBoostingClassifier`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html)
and
[`GradientBoostingRegressor`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html):
the same main parameters and losses. With `criterion="squared_error"`,
without a database and with `max_bins` at least the number of distinct values
of each column, the log loss and squared error models make the same
predictions as scikit-learn's. By default the trees of these two losses are Newton trees, as in
XGBoost and LightGBM (see [what the trees ask](#what-the-trees-ask)).

## Fit a boosted model

The data is the one of the [forest tutorial](./relational-random-forests):
class 1 when at least two of three rules hold, with 5% of the labels replaced
at random and two tables of noise.

```python
from sklearn.model_selection import train_test_split
from sklink.datasets import make_relational_classification
from sklink.ensemble import RelationalGradientBoostingClassifier

db, X, y = make_relational_classification(
    n_entities=1000,
    signal="mixed",
    flip_y=0.05,
    n_noise_tables=2,
    random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)

boosting = RelationalGradientBoostingClassifier(
    db,
    entity="customers",
    key="customer_id",
    n_estimators=100,
    learning_rate=0.1,
    max_depth=3,
    random_state=0,
).fit(X_train, y_train)
print(f"boosting {boosting.score(X_test, y_test):.3f}")
```

```text
boosting 0.940
```

Compare it with the forest of that tutorial, scored on the same split. Every tree has
at most `max_depth=3` levels of questions. `learning_rate`
scales the contribution of each tree: smaller values need more trees and
usually generalize better.

## Watch the model improve

`staged_predict_proba` yields the predictions after each tree, so you can see
how many trees the problem needs without fitting several models.

```python
from sklearn.metrics import log_loss

for i, proba in enumerate(boosting.staged_predict_proba(X_test), start=1):
    if i in (1, 10, 50, 100):
        print(f"{i:>3} trees  test log loss {log_loss(y_test, proba):.3f}")
```

```text
  1 trees  test log loss 0.623
 10 trees  test log loss 0.336
 50 trees  test log loss 0.213
100 trees  test log loss 0.211
```

`train_score_` holds the training loss after each tree. A training loss that
keeps falling while the test loss rises means the model has started to fit
noise.

`ForestDisplay.from_estimator(boosting, X_test=X_test, y_test=y_test)`, from
`sklink.plotting`, draws
the test accuracy after each iteration, the size of each tree and where the
trees ask each expression.

## Stop early

With `n_iter_no_change`, the model sets aside `validation_fraction` of the
training rows (stratified by class) and stops as soon as the loss of the
latest tree is not `tol` below any of the last `n_iter_no_change` losses, as
scikit-learn does. All the trees fitted so far are kept.

```python
early = RelationalGradientBoostingClassifier(
    db,
    entity="customers",
    key="customer_id",
    n_estimators=500,
    n_iter_no_change=10,
    random_state=0,
).fit(X_train, y_train)
print(f"{early.n_estimators_} of 500 trees, test {early.score(X_test, y_test):.3f}")
```

```text
60 of 500 trees, test 0.928
```

`validation_score_` holds the validation loss after each tree.

## What the trees ask

The trees are relational regression trees fitted to the gradient and the
Hessian of the log loss, as in XGBoost and LightGBM: each split maximizes the
second-order gain and each leaf takes the Newton step, which
`l2_regularization` can shrink. `criterion="squared_error"` fits the trees
to the gradient alone, as scikit-learn's `GradientBoostingClassifier` does.
As in scikit-learn, the importances of their questions add up the loss
reduction of every tree before they are normalized, so the first trees, which
correct the largest errors, count the most.

```python
from sklink.inspection import aggregate_importances

for table, importance in aggregate_importances(boosting, by="table").items():
    print(f"{table:12} {importance:.3f}")
```

```text
orders       0.656
customers    0.257
noise_1      0.043
products     0.017
noise_0      0.016
order_items  0.011
```

`estimators_` has one row per iteration. For more than two classes, each
iteration fits one tree per class, in the columns of that array. Each tree is
a fitted [`RelationalDecisionTreeRegressor`](../api/sklink.tree#sklink.tree.RelationalDecisionTreeRegressor)
whose leaf values are steps on the log-odds scale, before the learning rate.
`export_text(boosting.estimators_[0, 0])`, from `sklink.inspection`, prints the
rules of the first tree.

## Explain one prediction

`explain` lists, for each customer, the expressions that the paths of the
sample ask about, most used first. Each comes with its signed effect on the log-odds: what the
questions about that expression added along the paths, scaled by the learning
rate. The baseline and the effects add up to `decision_function` exactly.
Here, the three largest effects:

```python
from sklink.inspection import explain

sample = explain(boosting, X_test.iloc[:1])[0]
largest = sorted(sample["contributions"], key=lambda c: -abs(c["effect"][0]))
print(f"baseline {sample['baseline'][0]:+.2f}")
for c in largest[:3]:
    print(f"{c['effect'][0]:+.2f}  {c['expression']} = {c['value']:.3g}")
print(f"{len(largest)} expressions, log-odds {sample['raw'][0]:+.2f}")
print(f"class {sample['prediction']}")
```

```text
baseline +0.18
-1.98  proportion(orders[type == 'pickup']) = 0
+1.35  x_root_0 = -2
+1.03  mean(orders.noise_child_2) = 0.0583
117 expressions, log-odds -2.60
class 0
```

No single expression decides for this customer: the three largest effects
pull in opposite directions, and the many others each move the log-odds a
little. Many of them come from the noise tables: each is small, but together
they matter, which is why `aggregate_importances` still gives those tables a
share. `x_root_0` is a column of the `customers` table itself, and
`noise_child_2` a column of `orders` that carries no signal: one customer can
still be pushed by noise. A positive effect pushes toward the
last class of `classes_`. With more than two classes, `effect` has one entry
per class. For a regressor, the effects
are in the units of the target. `ExplanationDisplay.from_estimator(boosting,
X_test, sample=0)` draws the same explanation.

## Predict a range with quantile regression

`RelationalGradientBoostingRegressor` supports the losses `"squared_error"`,
`"absolute_error"`, `"huber"` and `"quantile"`. Two quantile models give a
prediction interval: here, the 10th and the 90th percentiles of the target.

```python
import numpy as np
from sklink.datasets import make_relational_regression
from sklink.ensemble import RelationalGradientBoostingRegressor

db_r, X_r, y_r = make_relational_regression(n_entities=1000, noise=1.0, random_state=0)
Xr_train, Xr_test, yr_train, yr_test = train_test_split(X_r, y_r, random_state=0)

bounds = [
    RelationalGradientBoostingRegressor(
        db_r,
        entity="customers",
        key="customer_id",
        loss="quantile",
        alpha=alpha,
        random_state=0,
    ).fit(Xr_train, yr_train)
    for alpha in (0.1, 0.9)
]
low, high = (model.predict(Xr_test) for model in bounds)
inside = np.mean((yr_test >= low) & (yr_test <= high))
print(f"{inside:.0%} of the test targets fall in the 10%-90% interval")
```

```text
74% of the test targets fall in the 10%-90% interval
```

The two quantiles are 80 percentage points apart, so about 80% of the
targets should fall inside. Quantiles
learned on the training rows are often a little too narrow on new rows;
check the coverage on held-out data, as here, before relying on an interval.
`"huber"` is a robust alternative to
`"squared_error"` when a few targets are far from the rest.

## Boosting or a forest?

| | Forest | Boosting |
| --- | --- | --- |
| Trees | Deep, grown independently | Shallow, each corrects the previous ones |
| Parallel fit | Yes, `n_jobs` | No: trees depend on each other |
| Main knobs | `max_features`, `min_samples_leaf` | `learning_rate`, `n_estimators`, `max_depth` |
| Built-in validation | Out-of-bag score | Early stopping, staged predictions |

Both models compute and bin the candidate expressions once and share them
between all trees; only the ranking of high-cardinality categories is redone
for each tree. Choose between them, and tune their parameters, with
[Model selection](./model-selection).

## Parameters at a glance

| Parameter | Default | What it does |
| --- | --- | --- |
| `loss` | `"log_loss"` (classifier), `"squared_error"` (regressor) | Loss to minimize |
| `learning_rate` | `0.1` | Shrinkage of each tree |
| `n_estimators` | `100` | Number of boosting iterations |
| `max_depth` | `3` | Depth of each tree |
| `subsample` | `1.0` | Fraction of rows drawn, without replacement, for each iteration |
| `criterion` | `"newton"` | Newton trees on the gradient and Hessian, or `"squared_error"` on the gradient alone, as scikit-learn |
| `l2_regularization` | `0.0` | L2 penalty on the leaf values of the Newton trees |
| `n_iter_no_change` | `None` | Stop after this many iterations without improvement on a validation split |
| `validation_fraction` | `0.1` | Size of that validation split |
| `alpha` | `0.9` | Quantile of `"quantile"`, and where `"huber"` turns linear (regressor) |
| `max_conditions` | `2` | Conditions learned inside an aggregate (0, 1 or 2) |
| `condition_penalty` | `2.0` | Gain each learned condition must pay, against conditions that only fit noise; `0` turns it off |
| `max_search_samples` | `2000` | Samples a larger node searches its learned conditions on, before scoring the best few on all its samples; lower fits faster on large data, `None` searches on all |
| `record_candidates` | `0` | Top split candidates saved per node in each tree, for `SearchDisplay` |
| `random_state` | `None` | Seed of `subsample`, `max_features`, the samples drawn for `max_search_samples` and the validation split |

The relational parameters (`max_relationship_depth`, `max_lookup_depth`,
`primitives`, `max_bins`, ...) mean the same as in the
[tree tutorial](./relational-decision-trees).
