---
url: /stable/tutorials/relational-decision-trees.md
description: >-
  Fit relational decision trees that learn conditions on related tables: choose
  split conditions, handle missing values and read the fitted rules.
---

# Relational decision trees

**A relational decision tree can split on a question about related rows, such
as whether a customer has any expensive express orders. It searches for
useful aggregates, conditions and thresholds while it fits.** You pass the
database and the entity key directly to the tree.

## Fit a tree

In this synthetic dataset, a customer is in class 1 when they have at least
one express order above 100. Fit the tree on one set of customers and check
how often it gets the label right on the held-out customers.

```python
from sklearn.model_selection import train_test_split
from sklink.datasets import make_relational_classification
from sklink.inspection import export_text
from sklink.tree import RelationalDecisionTreeClassifier

db, X, y = make_relational_classification(
    n_entities=1000, signal="conditional", random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)

tree = RelationalDecisionTreeClassifier(
    db,
    entity="customers",
    key="customer_id",
    max_depth=3,
    random_state=0,
)
tree.fit(X_train, y_train)
print(f"test accuracy: {tree.score(X_test, y_test):.3f}")
print(export_text(tree))
```

```text
test accuracy: 0.996
|--- exists(orders[amount > 99.935 & type == 'express']) <= 0.500
|   |--- class: 0
|--- exists(orders[amount > 99.935 & type == 'express']) >  0.500
|   |--- class: 1
```

The tree found a single split. Within the brackets, both conditions apply to
each order. `exists(...)` returns 1 if any order matches and 0 otherwise, so the
split at 0.5 sends those customers to class 1 and everyone else to class 0.
The learned amount cutoff is close to the generator's cutoff of 100.

## How many conditions to learn

`max_conditions` sets how many conditions a question can hold inside the
brackets: 0, 1 or 2 (the default). More conditions find interactions between
columns of the same row, at the cost of a larger search.

```python
for max_conditions in [0, 1, 2]:
    model = RelationalDecisionTreeClassifier(
        db,
        entity="customers",
        key="customer_id",
        max_depth=3,
        max_conditions=max_conditions,
        random_state=0,
    ).fit(X_train, y_train)
    print(max_conditions, f"{model.score(X_test, y_test):.3f}")
```

```text
0 0.652
1 0.928
2 0.996
```

With no conditions, the tree can use customer attributes and unfiltered
aggregates such as the maximum of a customer's order amounts. With one
condition, a split can ask about express orders or large orders. Two
conditions let a single expression ask for an order that meets both criteria.

## Conditions on a parent of the rows

A condition can also read a column of the row each aggregated row points to,
such as the product of an order line. In the `multihop` problem, class 1 means
a high share of order lines whose product is a toy: `products` is three
relationships away from `customers`, one more than `max_relationship_depth`
allows. The order lines **look up** their product instead, which is one row per
line and does not count as a hop. `max_lookup_depth` (default 1) sets how many
such many-to-one steps a condition may take; the looked-up columns are also
aggregated, as in `mean(orders.order_items.products.price)`. `0` turns
lookups off.

```python
db_m, X_m, y_m = make_relational_classification(
    n_entities=800, signal="multihop", random_state=0
)
X_train_m, X_test_m, y_train_m, y_test_m = train_test_split(X_m, y_m, random_state=0)
for max_lookup_depth in [0, 1]:
    model = RelationalDecisionTreeClassifier(
        db_m,
        entity="customers",
        key="customer_id",
        max_depth=1,
        max_lookup_depth=max_lookup_depth,
    ).fit(X_train_m, y_train_m)
    question = model.expressions_[0].name
    print(max_lookup_depth, f"{model.score(X_test_m, y_test_m):.3f}", question)
```

```text
0 0.540 exists(orders.order_items[quantity <= 2.0 & quantity > 1.5])
1 0.995 proportion(orders.order_items[products.category == 'toys'])
```

Lookups only extend paths that already use all `max_relationship_depth`
hops. With `max_relationship_depth=3`, `products` is part of the path itself,
`orders.order_items.products[category == 'toys']`, and lookups start from
`products`. An order line without a product, or whose product does not exist
yet at the cutoff (see [time and cutoffs](./time-and-cutoffs)), has a missing
value there, so only `is null` holds for it.

## Read the rules

`export_text` follows the layout of `sklearn.tree.export_text`. Here the leaf
weights are training sample counts because all samples have equal weight.

```python
print(export_text(tree, class_names=["regular", "target"], show_weights=True))
```

```text
|--- exists(orders[amount > 99.935 & type == 'express']) <= 0.500
|   |--- weights: [398.000, 0.000] class: regular
|--- exists(orders[amount > 99.935 & type == 'express']) >  0.500
|   |--- weights: [0.000, 352.000] class: target
```

If the expression were a mean, a customer with no orders would have a missing
value. The tree learns which branch receives missing values. A branch marked
`or missing` in the export takes missing values along with values that meet
its threshold.

## Explain one prediction

`explain` returns, for each sample, the questions on its path with the value
computed for that sample.

```python
from sklink.inspection import explain

for step in explain(tree, X_test.iloc[:1])[0]["path"]:
    print(
        step["expression"],
        step["operator"],
        step["threshold"],
        "| value:",
        step["value"],
    )
```

```text
exists(orders[amount > 99.935 & type == 'express']) <= 0.5 | value: 0.0
```

The first held-out customer had no orders matching both conditions. Their
value of 0 follows the `<= 0.5` branch to class 0.

## Importances

`expression_importances_` gives the impurity-based importance of every
question, by canonical name. `aggregate_importances` groups them by table,
column, relationship or primitive.

```python
from sklink.inspection import aggregate_importances

print(tree.expression_importances_)
print(aggregate_importances(tree, by="column"))
```

```text
{"exists(orders[amount > 99.935 & type == 'express'])": 1.0}
{'orders.amount': 0.5, 'orders.type': 0.5}
```

The tree uses one expression, so it gets all the importance. Grouping by
column splits that importance evenly between the two columns in its filter.

## Regression

Use `RelationalDecisionTreeRegressor` for numeric targets. It uses squared
error to choose splits and predicts the mean target of the training samples
in each leaf. Here the target depends on how many express orders exceed 100.

```python
from sklink.datasets import make_relational_regression
from sklink.tree import RelationalDecisionTreeRegressor

db_r, X_r, y_r, formula = make_relational_regression(
    n_entities=800, signal="conditional", return_rule=True, random_state=0
)
print(formula)
regressor = RelationalDecisionTreeRegressor(
    db_r, entity="customers", key="customer_id", max_depth=3
).fit(X_r, y_r)
print(export_text(regressor, max_depth=1))
```

```text
count(orders[amount > 100.0 & type == 'express'])
|--- count(orders[amount > 99.635 & type == 'express']) <= 2.000
|   |--- exists(orders[amount > 100.03 & type == 'express']) <= 0.500
|   |   |--- value: [-0.000]
|   |--- exists(orders[amount > 100.03 & type == 'express']) >  0.500
|   |   |--- truncated branch of depth 2
|--- count(orders[amount > 99.635 & type == 'express']) >  2.000
|   |--- count(orders[amount > 100.1 & type == 'express']) <= 5.500
|   |   |--- truncated branch of depth 2
|   |--- count(orders[amount > 100.1 & type == 'express']) >  5.500
|   |   |--- truncated branch of depth 2
```

`max_depth` in `export_text` limits how much of the tree is printed; deeper
branches appear as `truncated branch of depth d`, as in scikit-learn.

## Without a database

With `database=None` the tree uses the columns of `X` as a tabular model. For
a tabular baseline, supply the sample-level features you want it to learn
from. In this tutorial `X` contains customer IDs, which are lookup keys in
relational mode.

## Parameters at a glance

Tree shape and stopping rules work as in scikit-learn:

| Parameter | Default | What it does |
| --- | --- | --- |
| `criterion` | `"gini"` | `"gini"`, `"entropy"` or `"log_loss"`; `"squared_error"` for the regressor |
| `max_depth` | `None` | Maximum depth |
| `min_samples_split` | `2` | Minimum samples to split a node |
| `min_samples_leaf` | `1` | Minimum samples in each leaf |
| `min_weight_fraction_leaf` | `0.0` | Minimum fraction of the total sample weight in a leaf |
| `max_features` | `None` | Candidate groups tried at each node (see below) |
| `max_leaf_nodes` | `None` | Grow best-first with at most this many leaves |
| `min_impurity_decrease` | `0.0` | Minimum impurity decrease to split |
| `class_weight` | `None` | Class weights, or `"balanced"` (classifier only) |
| `random_state` | `None` | Seed for the sampling of `max_features` and of the samples drawn for `max_search_samples` |

The relational search has its own parameters:

| Parameter | Default | What it does |
| --- | --- | --- |
| `database`, `entity`, `key`, `time` | `None` | As in the featurizer |
| `max_relationship_depth` | `2` | Relationships a path may follow |
| `max_lookup_depth` | `1` | Many-to-one steps from the aggregated rows to a parent's columns, for conditions and aggregates |
| `primitives` | `"default"` | Aggregations of questions without conditions |
| `max_conditions` | `2` | Conditions learned inside an aggregate: 0, 1 or 2 |
| `condition_penalty` | `0.0` | Gain each learned condition must pay, against conditions that only fit noise on small nodes |
| `max_search_samples` | `None` | Samples a larger node searches its learned conditions on, before scoring the best few on all its samples; `None` searches on all |
| `max_bins` | `255` | Candidate thresholds per numeric expression, from quantiles |
| `max_condition_bins` | `32` | Candidate cuts per numeric condition column before refinement |
| `max_categories` | `32` | Most frequent categories tried in `==` conditions; columns with more also get conditions on ranked sets of categories. Not the featurizer's `max_categories` (default 10) |
| `record_candidates` | `5` | Top split candidates saved per node for inspection |
| `allow_reverse_paths` | `False` | Allow paths through shared tables to other entities |
| `handle_unknown_entity` | `"error"` | `"error"` or `"empty"` for unknown keys |

`max_features` samples **groups** of candidate splits. A group is one column
of `X`, or a table and column together with the expressions that use them.

A categorical column with more than `max_categories` categories, such as a
merchant or a product id, also gets conditions on sets of categories in
regression and binary classification, such as
`count(orders[merchant in ('m017', 'm203', ...)])`. The tree ranks the
categories in `fit` by the mean target of the training samples whose rows
have them, shrunk towards the overall mean so that rare categories rank in
the middle, and a condition keeps one side of a cut of that ranking.
Categories that fewer than 5 training entities have are not ranked, so a
column of identifiers cannot sort the samples by their own target. A forest
ranks them again in each tree, on its bootstrap sample, and gradient boosting
at each iteration, on the residuals. A categorical feature such as
`mode(orders.merchant)` splits on a set of categories ordered by mean target;
categories that fewer than 10 samples of the node have, or that fewer than 5
training entities reach, are not ordered and go right, so a column with one
value per entity, such as a name, does not memorize the entities through their
samples at many cutoffs.

Only aggregates that can be computed from running sums, such as `count`,
`sum`, `mean`, `exists` and `proportion`, carry learned conditions. Other
primitives, such as `mode` or `nunique`, are asked about without conditions.

See how these trees work together in a
[relational random forest](./relational-random-forests).
