Inspect and explain relational models
Use describe_expressions to see what a fitted model reads, aggregate_importances to see what it uses across samples, and explain to trace one prediction. Fit a tree and a forest on the same synthetic customers to try each view.
from sklink.datasets import make_relational_classification
from sklink.ensemble import RelationalRandomForestClassifier
from sklink.tree import RelationalDecisionTreeClassifier
db, X, y = make_relational_classification(
n_entities=600, signal="mixed", random_state=0
)
tree = RelationalDecisionTreeClassifier(
db,
entity="customers",
key="customer_id",
max_depth=3,
random_state=0,
).fit(X, y)
forest = RelationalRandomForestClassifier(
db,
entity="customers",
key="customer_id",
n_estimators=30,
max_features=0.5,
n_jobs=1,
random_state=0,
).fit(X, y)What a model reads
Before dropping a column from the source data, check whether an expression uses it. describe_expressions lists the table and column being aggregated as well as any columns used in the conditions.
from sklink.inspection import describe_expressions
for item in describe_expressions(tree):
print(
item["kind"], "|", item["table"], "|", item["column"], "|", item["conditions"]
)aggregate | orders | None | [{'table': 'orders', 'column': 'noise_child_2', 'op': '>', 'value': -1.6165, 'lookup': []}, {'table': 'orders', 'column': 'type', 'op': '==', 'value': 'pickup', 'lookup': []}]
aggregate | orders | None | [{'table': 'orders', 'column': 'amount', 'op': '>', 'value': 99.04, 'lookup': []}, {'table': 'orders', 'column': 'type', 'op': '==', 'value': 'express', 'lookup': []}]
aggregate | orders | None | [{'table': 'orders', 'column': 'amount', 'op': '>', 'value': 115.5, 'lookup': []}]
attribute | customers | x_root_1 | []
aggregate | orders | amount | [{'table': 'orders', 'column': 'amount', 'op': '>', 'value': 82.94, 'lookup': []}, {'table': 'orders', 'column': 'type', 'op': '==', 'value': 'express', 'lookup': []}]
aggregate | orders | amount | [{'table': 'orders', 'column': 'amount', 'op': '<=', 'value': 77.66, 'lookup': []}]The first expression filters orders using noise_child_2 and type. Its column is None because it computes a proportion of rows. Checking the column field alone would miss both dependencies.
Rules as text
export_text puts each expression in its place in the tree. Follow the indented branches from the first split to a line that gives a class.
from sklink.inspection import export_text
print(export_text(tree, decimals=1))|--- proportion(orders[noise_child_2 > -1.6165 & type == 'pickup']) <= 0.1 or missing
| |--- proportion(orders[amount > 99.04 & type == 'express']) <= 0.1
| | |--- count(orders[amount > 115.5]) <= 9.5
| | | |--- class: 0
| | |--- count(orders[amount > 115.5]) > 9.5
| | | |--- class: 1
| |--- proportion(orders[amount > 99.04 & type == 'express']) > 0.1
| | |--- x_root_1 <= -0.2
| | | |--- class: 1
| | |--- x_root_1 > -0.2
| | | |--- class: 0
|--- proportion(orders[noise_child_2 > -1.6165 & type == 'pickup']) > 0.1
| |--- mean(orders.amount[amount > 82.94 & type == 'express']) <= 98.8 or missing
| | |--- x_root_1 <= 0.1
| | | |--- class: 1
| | |--- x_root_1 > 0.1
| | | |--- class: 0
| |--- mean(orders.amount[amount > 82.94 & type == 'express']) > 98.8
| | |--- mean(orders.amount[amount <= 77.66]) <= 76.0
| | | |--- class: 1
| | |--- mean(orders.amount[amount <= 77.66]) > 76.0
| | | |--- class: 0Importances, grouped
aggregate_importances groups split importance by expression, table, column, relationship or primitive. For example, grouping by column splits the importance of a mean between the column it averages and the columns in its filter.
from sklink.inspection import aggregate_importances
for by in ["table", "primitive"]:
groups = aggregate_importances(forest, by=by)
print(by, {name: round(value, 2) for name, value in list(groups.items())[:4]})table {'orders': 0.74, 'customers': 0.24, 'order_items': 0.01}
primitive {'mean': 0.4, 'attribute': 0.24, 'proportion': 0.23, 'exists': 0.05}Grouping by table credits about three quarters of the total to expressions ending at orders. Grouping by primitive gives mean the largest share. Pass normalize=False to get the mean decrease in impurity weighted by the share of training samples reaching each node, before normalization.
Permutation importance
Permutation importance measures how much the score drops when you shuffle a column of held-out X. In this example, X has one column, customer_id, so shuffling it attaches each row to another customer's relational data.
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = RelationalDecisionTreeClassifier(
db,
entity="customers",
key="customer_id",
max_depth=3,
random_state=0,
).fit(X_train, y_train)
result = permutation_importance(model, X_test, y_test, n_repeats=5, random_state=0)
print(f"customer_id: {result.importances_mean[0]:.3f}")customer_id: 0.435Accuracy drops sharply after shuffling the key. This measures the effect of changing the customer and all the rows reached from it together. For a pipeline with a featurizer, you can also measure individual output features.
Explain predictions
explain returns one dictionary per sample. A tree explanation records the expression value and branch at each split. A forest explanation ranks the expressions along all of the sample's paths by how much of the weighted split usage they account for.
from sklink.inspection import explain
sample = explain(tree, X.iloc[:1])[0]
print("prediction:", sample["prediction"], [round(p, 3) for p in sample["value"]])
for step in sample["path"]:
print(f" {step['expression']} = {step['value']:.2f} -> {step['branch']}")
sample = explain(forest, X.iloc[:1])[0]
for item in sample["contributions"][:3]:
print(
f" {item['contribution']:.2f} {item['expression']} ({item['n_trees']} trees)"
)prediction: 1 [0.006, 0.994]
proportion(orders[noise_child_2 > -1.6165 & type == 'pickup']) = 0.44 -> right
mean(orders.amount[amount > 82.94 & type == 'express']) = 108.11 -> right
mean(orders.amount[amount <= 77.66]) = 60.73 -> left
0.06 x_root_1 (10 trees)
0.04 proportion(orders[type == 'pickup']) (5 trees)
0.03 mean(orders.amount[amount > 89.42 & type == 'express']) (2 trees)The customer's first value takes the right branch because it exceeds the root threshold. The next two steps end at a leaf that predicts class 1. In the forest, x_root_1 appears on this customer's paths in the most trees and has the largest share of weighted split usage. Use max_samples to control how many rows are explained. The default is 10.
The figure traces those three splits for the same customer. Each marker shows the customer's value relative to the threshold at that node. Open the diagram to see the full expression names.
To generate this view in a notebook or export it, as with the other figures of Plot a model:
from sklink.plotting import ExplanationDisplay
view = ExplanationDisplay.from_estimator(tree, X, sample=0)
view.save("customer-path.svg")Export to JSON
export_dict returns the fitted schema, expression definitions and split rules as JSON-compatible values. export_json writes the same description to a file. To use it in another language, evaluate the expressions against the tables, then apply the exported split rules to those values.
from sklink.inspection import export_dict
description = export_dict(tree)
print(sorted(description))
root = description["nodes"][0]
print(root["expression_name"], root["threshold"])['classes', 'entity', 'estimator', 'expressions', 'format_version', 'nodes', 'params', 'schema', 'sklink_version', 'task', 'visibility']
proportion(orders[noise_child_2 > -1.6165 & type == 'pickup']) 0.095The JSON export is for inspection or an external implementation. To load the fitted Python estimator again, follow Save and deploy.
Functions at a glance
| Function | Works with | Returns |
|---|---|---|
describe_expressions | Featurizer, tree, forest, boosting | What each expression reads |
export_text | Tree, clustering tree | Rules as text, like sklearn.tree.export_text |
aggregate_importances | Tree, forest, boosting | Importances grouped by table, column, relationship or primitive |
explain | Tree, forest, boosting, clustering tree | Decision path or contributions per sample; signed effects for boosting |
export_dict, export_json | Tree, forest, boosting | A JSON description of the fitted model |
You can also pass a Pipeline that ends with a supported model or a fitted search whose best_estimator_ is a supported model.