---
url: /stable/cookbook/interpretation.md
description: >-
  Recipes to read relational models: importances as a DataFrame, the tables a
  model needs, top featurizer columns, batch explanations and rules as JSON.
---

# Interpretation

**Rank the patterns a model uses, check which source columns it needs, or
trace what it read for a specific prediction.** The
[Inspect and explain tutorial](../tutorials/inspect-and-explain) walks through
the same questions step by step, and [Plot a model](../tutorials/plotting) draws
them as figures.

## Setup

Install the [`pandas` extra](../getting-started/installation), then create the
customer dataset and fit a forest. The permutation importance recipe uses
the same data and fits its own model on a training subset.

```python
import pandas as pd
from sklink.datasets import make_relational_classification
from sklink.ensemble import RelationalRandomForestClassifier

db, X, y = make_relational_classification(
    n_entities=600, signal="mixed", output="pandas", random_state=0
)
forest = RelationalRandomForestClassifier(
    db,
    entity="customers",
    key="customer_id",
    n_estimators=30,
    max_features=0.5,
    n_jobs=1,
    random_state=0,
).fit(X, y)
```

## Rank the expressions in a fitted forest {#importances-as-a-dataframe}

`aggregate_importances` reports each expression's share of the total split
improvement during training, so the values sum to 1. Its result is ordered from largest to smallest. Use `by="table"`
for a breakdown by source table, or `by="column"` to group expressions by
the raw columns they use. To measure how much a feature affects model scores
on new data, use the held-out recipe below.

```python
from sklink.inspection import aggregate_importances

importances = pd.Series(aggregate_importances(forest), name="importance")
print(importances.head(5).round(3))
```

```text
x_root_1                                                          0.221
proportion(orders[type == 'pickup'])                              0.029
mean(orders.amount[amount > 89.42 & type == 'express'])           0.024
proportion(orders[noise_child_2 <= 1.6295 & type == 'pickup'])    0.024
proportion(orders[noise_child_2 <= 1.428 & type == 'pickup'])     0.020
Name: importance, dtype: float64
```

Near-identical expressions, such as the two `noise_child_2` thresholds
above, split their importance between them; `by="column"` or
`by="primitive"` groups them. `noise_child_2` is noise added by the
generator.

## Which tables and columns does a model need?

Start with `forest.schema_` before renaming or dropping an upstream column.
It includes keys used in relationships and columns used in filters, as well
as columns the forest aggregates. Use `describe_expressions` to find the
expressions that use filters, such as the first one below.

```python
from sklink.inspection import describe_expressions

for name in sorted(forest.schema_.table_names):
    table = forest.schema_.table(name)
    print(f"{name}: {', '.join(table.column_names)}")

expressions = pd.DataFrame(describe_expressions(forest))
print(expressions.loc[expressions["conditions"].map(bool), "name"].iloc[0])
```

```text
customers: customer_id, x_root_0, x_root_1, noise_root_0, noise_root_1
order_items: order_id, product_id, quantity
orders: order_id, customer_id, type, amount, noise_child_0, noise_child_1, noise_child_2
products: product_id, category, price
proportion(orders[noise_child_2 <= 1.6295 & type == 'pickup'])
```

## Most important featurizer columns

After fitting on the training rows, transform the test rows once. Permutation
importance shuffles one output feature at a time and measures how much the
score falls. This ranks derived features such as the mean order amount.
Shuffling the raw customer IDs would change which records every feature reads.

```python
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
from sklink.feature_extraction import RelationalFeaturizer

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
featurizer = (
    RelationalFeaturizer(
        db,
        entity="customers",
        key="customer_id",
        max_relationship_depth=1,
    )
    .set_output(transform="pandas")
    .fit(X_train)
)
model = HistGradientBoostingClassifier(random_state=0).fit(
    featurizer.transform(X_train), y_train
)
result = permutation_importance(
    model, featurizer.transform(X_test), y_test, n_repeats=5, random_state=0
)
top = pd.Series(result.importances_mean, index=featurizer.get_feature_names_out())
print(top.sort_values(ascending=False).head(3).round(3))
```

```text
mean(orders.amount[type == 'express'])    0.228
proportion(orders[type == 'pickup'])      0.225
x_root_1                                  0.196
dtype: float64
```

## Explanations for a batch of customers

`explain` returns one dictionary per sample. `sample` gives the row position
in `X`, and `value` holds the probabilities in the order of `forest.classes_`.
For a forest, `contributions` ranks the expressions used most on that
sample's decision paths. A forest that never splits can return an empty list.

```python
from sklink.inspection import explain

positive_class = forest.classes_.tolist().index(1)
rows = [
    {
        "customer_id": X["customer_id"].iloc[item["sample"]],
        "probability": round(item["value"][positive_class], 3),
        "most_used_split": (
            item["contributions"][0]["expression"] if item["contributions"] else None
        ),
    }
    for item in explain(forest, X, max_samples=4)
]
print(pd.DataFrame(rows))
```

```text
   customer_id  probability most_used_split
0            0        0.967        x_root_1
1            1        0.067        x_root_1
2            2        1.000        x_root_1
3            3        1.000        x_root_1
```

## Rules to JSON

Use `export_json` to save the forest's decision rules for review. For a file
you can load and use to predict, follow [Save and deploy](../tutorials/save-and-deploy).

```python
import json

from sklink.inspection import export_json

export_json(forest, "forest.json")
with open("forest.json", encoding="utf-8") as file:
    description = json.load(file)
print(description["estimator"], len(description["estimators"]), "trees")
```

```text
RelationalRandomForestClassifier 30 trees
```
