---
url: /dev/guides/tune-trees-and-forests.md
description: >-
  The effect of each parameter of scikit-link's relational decision trees and
  random forests, measured on executed examples, with search ranges to start
  from.
---

# Tune relational trees and forests

**A relational tree has the parameters of a scikit-learn tree, which set its
size, and relational ones, which set what each question can ask about the
related tables. A forest adds the number of trees and how many candidate
questions each node scores.** Each section below varies one parameter on the
same data and prints the cross-validated accuracy, so you can see its effect
before you search it. Read [where to start](./tuning) first for the order of
the steps.

## Setup

The synthetic shop below has a label that depends on several related tables,
and two tables of pure noise, so that a model that reads too much has
something to overfit.

```python
from sklearn.model_selection import StratifiedKFold, validation_curve
from sklink.datasets import make_relational_classification
from sklink.ensemble import RelationalRandomForestClassifier
from sklink.tree import RelationalDecisionTreeClassifier

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}")


tree = RelationalDecisionTreeClassifier(
    db, entity="customers", key="customer_id", random_state=0
)
```

## Size of the tree {#size}

`max_depth` and `min_samples_leaf` bound how many questions a tree asks. A
training score far above the test score means the tree has started to learn
the noise of its training samples.

```python
curve(tree, "max_depth", [2, 4, 6, None])
curve(tree, "min_samples_leaf", [1, 5, 20, 50])
```

```text
max_depth=2      train 0.783  test 0.757
max_depth=4      train 0.997  test 0.938
max_depth=6      train 1.000  test 0.940
max_depth=None   train 1.000  test 0.940
min_samples_leaf=1      train 1.000  test 0.940
min_samples_leaf=5      train 0.984  test 0.937
min_samples_leaf=20     train 0.980  test 0.942
min_samples_leaf=50     train 0.823  test 0.782
```

## Reach: how far a question looks {#reach}

`max_relationship_depth` sets how many relationships a path follows, and
`max_lookup_depth` how many many-to-one steps it may take from the last
table, such as from an order line to its product. More reach finds signals
further away and gives the noise tables more chances. Here every signal is
close to the customer, so more reach neither helps nor hurts.

```python
curve(tree, "max_relationship_depth", [1, 2, 3])
curve(tree, "max_lookup_depth", [0, 1])
```

```text
max_relationship_depth=1      train 1.000  test 0.940
max_relationship_depth=2      train 1.000  test 0.940
max_relationship_depth=3      train 1.000  test 0.940
max_lookup_depth=0      train 1.000  test 0.940
max_lookup_depth=1      train 1.000  test 0.940
```

## Conditions inside a question {#conditions}

`max_conditions` sets how many filters one aggregate can combine, such as
express orders above 100. `max_categories` sets how many frequent
categories are tried as `==` conditions; in regression and binary
classification, columns with more also get conditions on ranked sets of
categories.

```python
curve(tree, "max_conditions", [0, 1, 2])
curve(tree, "max_categories", [4, 32])
```

```text
max_conditions=0      train 1.000  test 0.652
max_conditions=1      train 1.000  test 0.922
max_conditions=2      train 1.000  test 0.940
max_categories=4      train 1.000  test 0.940
max_categories=32     train 1.000  test 0.940
```

## Make conditions pay for themselves {#condition-penalty}

A node that tries many conditions finds one that separates its labels by
chance. `condition_penalty` makes each learned condition pay its value times
the gain one condition makes by chance at the node, times the log of the
number of conditions its path offers, before the tree asks it. It is 0 for trees and forests, and useful values go up to
about 6: higher on small or noisy data, where it prefers aggregates without
conditions. Here the label depends on conditions on orders, so the penalty
costs accuracy.

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

```text
condition_penalty=0      train 1.000  test 0.940
condition_penalty=2      train 1.000  test 0.927
condition_penalty=6      train 1.000  test 0.892
```

## Thresholds {#bins}

`max_bins` sets the candidate thresholds of a numeric expression, and
`max_condition_bins` those of a numeric column inside a condition before the
exact refinement. Fewer bins fit faster and, as here, often cost nothing;
too few can miss the right cut. The example varies `max_condition_bins`;
`max_bins` behaves the same way for the expressions themselves.

```python
curve(tree, "max_condition_bins", [4, 32])
```

```text
max_condition_bins=4      train 1.000  test 0.945
max_condition_bins=32     train 1.000  test 0.940
```

## Forests: number of trees and candidates per node {#forests}

A forest averages trees grown on bootstrap samples. `max_features` sets how
many candidate groups each node scores, where a group is one base feature or
one related table with one aggregated column: fewer makes the trees more
different from each other, more makes each tree stronger. Here `"sqrt"`
leaves too few candidates per node to find the tables that matter, and a
larger share fixes it. `n_estimators`
only needs to be large enough for the score to settle; watch the out-of-bag
score with `oob_score=True` instead of searching it.

```python
forest = RelationalRandomForestClassifier(
    db, entity="customers", key="customer_id", n_estimators=30, random_state=0
)
curve(forest, "max_features", ["sqrt", 0.5])
```

```text
max_features=sqrt   train 1.000  test 0.825
max_features=0.5    train 1.000  test 0.940
```

Forests grow their trees to leaves of one sample by default, as in
scikit-learn, and averaging keeps that from overfitting on most data. The
exception is a task where the same entity comes back at many cutoff times,
such as a driver at every race: leaves of one sample then learn the entity,
not the pattern. Search `min_samples_leaf` from 5 to 50 there. On RelBench
rel-f1 driver-dnf (validation split, two seeds), leaves of 20 samples raise
the AUC of a forest from 0.63 to 0.73, while on synthetic tasks with one
sample per entity the same leaves lower the score (AUC or R²) by up to 0.06.

## Where to start a search {#ranges}

| Parameter | Default | Range to search | Notes |
| --- | --- | --- | --- |
| `max_depth` | `None` | 3 to 12, or `None` with `min_samples_leaf` | Trees |
| `min_samples_leaf` | `1` | 1 to 50 | The main regularizer of a single tree; in forests, when entities repeat across cutoffs |
| `max_relationship_depth` | `2` | 1 to 3 | Changes the expressions: costs a full fit per value |
| `max_conditions` | `2` | 0 to 2 | Compare 0 on small data |
| `condition_penalty` | `0` | 0 to 6 | Higher on small or noisy data |
| `max_search_samples` | `None` | 1000 to 5000 on large data | A speed setting that only acts on nodes with more samples |
| `max_categories` | `32` | 8 to 64 | Larger columns are ranked either way, except in multiclass classification |
| `max_features` | `"sqrt"` (classifier), `1.0` (regressor) | `"sqrt"`, 0.3, 0.5, 1.0 | Forests |
| `n_estimators` | `100` | Until the out-of-bag score settles | Forests; do not search it |

## Next steps

* [Tune gradient boosting](./tune-gradient-boosting)
* [Relational decision trees](../tutorials/relational-decision-trees) and
  [random forests](../tutorials/relational-random-forests) for what each
  parameter does.
