---
url: /dev/tutorials/relational-random-forests.md
description: >-
  Relational random forests for classification and regression: out-of-bag score,
  max_features, parallel training and grouped feature importances.
---

# Relational random forests

**A relational random forest combines predictions from many relational trees.
By default, each tree sees a sample of the rows of `X` drawn with replacement.
The classifier averages the class probabilities from those trees.**

## A harder problem

In this example, the generator assigns class 1 when at least two of three
rules hold. One uses customer attributes, one checks the share of pickup
orders, and one checks for a large express order. `flip_y=0.05` replaces a
fraction of the labels with random classes, and two additional tables contain
noise.

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

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

```text
(-1.7 * x_root_0 + 1.1 * x_root_1 >= -0.17) + (proportion(orders[type == 'pickup']) >= 0.14) + (count(orders[amount > 100.0 & type == 'express']) >= 1) >= 2
```

## One tree against a forest

```python
from sklink.ensemble import RelationalRandomForestClassifier
from sklink.tree import RelationalDecisionTreeClassifier

tree = RelationalDecisionTreeClassifier(
    db,
    entity="customers",
    key="customer_id",
    min_samples_leaf=5,
    random_state=0,
).fit(X_train, y_train)

forest = RelationalRandomForestClassifier(
    db,
    entity="customers",
    key="customer_id",
    n_estimators=50,
    max_features=None,
    min_samples_leaf=3,
    oob_score=True,
    n_jobs=1,
    random_state=0,
).fit(X_train, y_train)

print(f"tree   {tree.score(X_test, y_test):.3f}")
print(
    f"forest {forest.score(X_test, y_test):.3f}  (out of bag {forest.oob_score_:.3f})"
)
```

```text
tree   0.888
forest 0.928  (out of bag 0.905)
```

Both models are scored on the same held-out customers. The forest also
reports an out-of-bag accuracy. For each training sample,
`oob_score=True` combines predictions from the trees that left that sample
out of their bootstrap draws. You can pass a scoring function that accepts
`y_true` and `y_pred` to use a different metric.

## Choose `max_features`

At each node, `max_features` controls how many groups of candidate splits the
tree tries. A group can be a column of `X` or a table and column with its
associated expressions. The classifier defaults to `"sqrt"`, the square root
of the number of groups. A fraction such as `0.5` tries about half of them.

```python
for max_features in ["sqrt", 0.5]:
    model = RelationalRandomForestClassifier(
        db,
        entity="customers",
        key="customer_id",
        n_estimators=50,
        max_features=max_features,
        min_samples_leaf=3,
        n_jobs=1,
        random_state=0,
    ).fit(X_train, y_train)
    print(max_features, f"{model.score(X_test, y_test):.3f}")
```

```text
sqrt 0.824
0.5 0.936
```

In this run, `0.5` beat `"sqrt"`, and the earlier fit with
`max_features=None`, which tried every group, did not beat `0.5`: more groups
is not always better. On your own data,
choose `max_features` and `max_conditions` on training folds before scoring on
a held-out set. See [Model selection](./model-selection).

## Importances by table

`aggregate_importances` groups split importances by table, column,
relationship or primitive. Grouping by table credits each expression to the
table where its path ends.

```python
from sklink.inspection import aggregate_importances

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

```text
orders       0.655
customers    0.281
noise_1      0.032
noise_0      0.026
order_items  0.005
```

Expressions ending at `orders` account for about two-thirds of the forest's
total split importance. These importances come from training splits and can
favor expressions with many possible cuts. To measure how shuffling a column
of held-out `X` changes the score, see
[Permutation importance](./inspect-and-explain#permutation-importance).

## Explain a prediction of the forest

For one sample, `explain` lists the expressions used along its paths across
the trees. Splits reached by more of a tree's weighted training samples count
more toward the reported share.

```python
from sklink.inspection import explain

explanation = explain(forest, X_test.iloc[:1])[0]
print("probabilities:", [round(p, 3) for p in explanation["value"]])
for item in explanation["contributions"][:3]:
    print(f"{item['contribution']:.2f}  {item['expression']} = {item['value']}")
```

```text
probabilities: [0.962, 0.038]
0.12  proportion(orders[type == 'pickup']) = 0.0
0.03  proportion(orders[amount > 42.8 & type == 'pickup']) = 0.0
0.03  mean(orders.amount[amount > 100.86 & type == 'express']) = None
```

`None` means the customer has no matching orders, so the mean is missing.
For this customer, the pickup-order proportion accounts for the largest
share of the weighted split usage along their paths, and the forest predicts
class 0. The usage share describes how often the forest relies on a
question along the paths and carries no direction or probability units.

## Parallel and reproducible

`n_jobs` controls parallel tree growth. Set a `random_state` to reproduce the
fit. With the same seed, `n_jobs=1` and `n_jobs=-1` give the same results.
`verbose` prints progress while the trees grow.

## Regression and more than two classes

`RelationalRandomForestRegressor` averages the trees' numeric predictions.
Its criterion is `"squared_error"`, `max_features` defaults to `1.0`, and
`oob_score=True` reports R².

```python
from sklink.datasets import make_relational_regression
from sklink.ensemble import RelationalRandomForestRegressor

db_r, X_r, y_r = make_relational_regression(n_entities=500, random_state=0)
X_r_train, X_r_test, y_r_train, y_r_test = train_test_split(X_r, y_r, random_state=0)
regressor = RelationalRandomForestRegressor(
    db_r,
    entity="customers",
    key="customer_id",
    n_estimators=50,
    oob_score=True,
    random_state=0,
).fit(X_r_train, y_r_train)
print(f"test R² {regressor.score(X_r_test, y_r_test):.3f}")
```

```text
test R² 0.993
```

Classifiers handle any number of classes, as in scikit-learn: with three
labels, `predict_proba` returns three columns, in the order of `classes_`.

## Parameters at a glance

The [tree tutorial](./relational-decision-trees) explains split conditions and
depth. Use the settings below to control sampling, training and inspection
across the forest.

| Parameter | Default | What it does |
| --- | --- | --- |
| `n_estimators` | `100` | Number of trees |
| `max_features` | `"sqrt"` (classifier), `1.0` (regressor) | Candidate groups tried at each node |
| `bootstrap` | `True` | Draw a bootstrap sample of `X` for each tree |
| `max_samples` | `None` | Size of each bootstrap sample (`len(X)` draws when `None`) |
| `oob_score` | `False` | Score on rows left out of bootstrap draws. Accepts `True` or a callable and requires `bootstrap=True` |
| `class_weight` | `None` | `"balanced"`, `"balanced_subsample"` or a dict (classifier only) |
| `record_candidates` | `0` | Top split candidates saved per node in each tree |
| `n_jobs` | `None` | Trees grown in parallel worker processes |
| `random_state` | `None` | Seed for bootstrapping and `max_features` sampling |
| `verbose` | `0` | Verbosity of the parallel loop |

Fitted forests expose `estimators_` (the trees), `estimators_samples_` (the
rows each tree drew), `expressions_`, `expression_importances_` and
`feature_importances_`, plus `oob_score_` and `oob_decision_function_`
(classifier) or `oob_prediction_` (regressor) when `oob_score` is set.

Tune a forest with [Model selection](./model-selection), or add a date to each
prediction sample with [Time and cutoffs](./time-and-cutoffs).
