Skip to content

Plot schemas, trees, forests and predictions ​

sklink.plotting draws a database, a fitted model or one prediction with one call: SchemaDisplay.from_estimator(model), TreeDisplay.from_estimator(model) and so on. In a notebook each figure is interactive HTML; anywhere else you can print it as text or save it as SVG, HTML or JSON. This tutorial draws every figure for one fitted tree and one forest.

The figures need no plotting library and load nothing from the network. They are drawn in Python as SVG and follow the light or dark theme of JupyterLab and VS Code, and the system light or dark setting elsewhere.

Fit a model to draw ​

The synthetic shop below has four tables and a label that depends on several of them, so the tree has something to show.

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

db, X, y = make_relational_classification(
    n_entities=400, signal="mixed", random_state=0, output="pandas"
)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, stratify=y)
tree = RelationalDecisionTreeClassifier(
    db, entity="customers", key="customer_id", max_depth=3, random_state=0
).fit(X_train, y_train)
print(f"{tree.score(X_test, y_test):.2f}")
text
0.94

The schema the model reads ​

SchemaDisplay draws the tables, their keys and how they link. Built from a fitted model, it also marks the entity, the target and, with a dot, every column the model reads. The strip below the tables shows how many child rows each parent row has, which is where skewed relationships stand out.

python
from sklink.plotting import SchemaDisplay

schema = SchemaDisplay.from_estimator(tree, y_train)
schema.save("plot-schema.svg")

Schema of the shop: customers, orders, order items and products. Dots mark the customer and order columns the tree reads; histograms show how many orders each customer has.

Before fitting anything, SchemaDisplay.from_database(db, entity="customers") draws the same tables without the model's marks: a quick check that the keys and relationships are the ones you meant.

The fitted tree ​

TreeDisplay draws every node as a card with its question, its number of samples and its class mix. Pass rows of X to trace their path: here the first test customer, in coral.

python
from sklink.plotting import TreeDisplay

view = TreeDisplay.from_estimator(tree, X_test.iloc[[0]])
view.save("plot-tree.svg")

A relational decision tree of depth three. The first question is whether a customer has an express order above 100; the path of one customer runs through two questions to a leaf of class 0.

In a notebook, clicking a node opens its detail. max_depth (default 4) limits how many levels are drawn, which keeps large trees readable.

Every display also prints as plain text, which is what a terminal shows:

python
print(view.to_text())
text
|--- exists(orders[amount > 100.0 & type == 'express']) <= 0.5
|   |--- proportion(orders[noise_child_2 > -2.82 & type == 'pickup']) <= 0.17
|   |   |--- class: 0
|   |--- proportion(orders[noise_child_2 > -2.82 & type == 'pickup']) > 0.17
|   |   |--- x_root_0 <= -0.325
|   |   |   |--- class: 1
|   |   |--- x_root_0 > -0.325
|   |   |   |--- class: 0
|--- exists(orders[amount > 100.0 & type == 'express']) > 0.5
|   |--- x_root_0 <= 0.1167
|   |   |--- noise_root_0 <= -2.452
|   |   |   |--- class: 0
|   |   |--- noise_root_0 > -2.452
|   |   |   |--- class: 1
|   |--- x_root_0 > 0.1167
|   |   |--- proportion(orders[type == 'pickup']) <= 0.17
|   |   |   |--- class: 0
|   |   |--- proportion(orders[type == 'pickup']) > 0.17
|   |   |   |--- class: 1

Why the tree chose a question ​

While it grows, the tree scores many questions at each node and keeps the best. With record_candidates (5 by default), it remembers the runners-up, and SearchDisplay compares them. A clear winner is a stable split; close runners-up mean that a small change in the data could swap the question. Forests and gradient boosting models keep none by default; set record_candidates on them and pass one of their trees, such as forest.estimators_[0] or boosting.estimators_[0, 0].

python
from sklink.plotting import SearchDisplay

search = SearchDisplay.from_estimator(tree, node=0)
search.save("plot-search.svg")
print(search.to_text())
text
node 0 (depth 0, 300 samples): 5 best questions recorded
 * 51.57  exists(orders[amount > 100.0 & type == 'express']) <= 0.5
   51.57  mean(orders.amount[amount > 91.175 & type == 'express']) <= 100
   51.57  sum(orders.amount[amount > 100.0 & type == 'express']) <= 0
   41.3  proportion(orders[amount <= 94.195 & type == 'pickup']) <= 0.1094
   33.17  mean(orders.noise_child_0[amount > 91.08500000000001 & type == 'express']) <= 1.165
A tie with the runner-up, broken by search order
Every recorded question filters the rows it aggregates

The five best questions scored at the root, the chosen one first, with the impurity decrease of each.

Why one sample got its prediction ​

ExplanationDisplay follows one sample through the tree. Each question is a number line with the threshold and the sample's value, so you see how close the sample was to going the other way.

python
from sklink.plotting import ExplanationDisplay

explanation = ExplanationDisplay.from_estimator(tree, X_test, sample=0)
explanation.save("plot-explanation.svg")
print(explanation.to_text())
text
sample 0: class 0
  1. exists(orders[amount > 100.0 & type == 'express']) = 0 <= 0.5, goes left
  2. proportion(orders[noise_child_2 > -2.82 & type == 'pickup']) = 0.07692 <= 0.17, goes left

Two questions on number lines, each with the threshold and the value of the first test customer.

For a forest, the same display lists the expressions on the sample's paths across the trees, each weighted by the share of training samples that reach those nodes; the weights sum to 1. It shows which expressions the prediction relied on, not in which direction they moved it.

Where the importance comes from ​

ImportanceDisplay groups the importance of a tree or forest from tables, to columns, to primitives such as mean or proportion. It answers questions a flat list cannot, such as how much of the model rests on the orders table.

python
from sklink.plotting import ImportanceDisplay

importance = ImportanceDisplay.from_estimator(tree)
importance.save("plot-importance.svg")

Flows of importance from tables to columns to primitives.

How a forest fitted ​

ForestDisplay shows the score as trees are added, the size of the trees and which expressions each tree asks, and how close to its root. A score curve that is still rising asks for more trees; a flat one says you can use fewer. It draws a gradient boosting model too, with its test score after each iteration.

python
from sklink.ensemble import RelationalRandomForestClassifier
from sklink.plotting import ForestDisplay

forest = RelationalRandomForestClassifier(
    db, entity="customers", key="customer_id", n_estimators=50, random_state=0
).fit(X_train, y_train)
forest_view = ForestDisplay.from_estimator(
    forest, X_train, y_train, X_test=X_test, y_test=y_test
)
forest_view.save("plot-forest.svg")

Out-of-bag and test accuracy by number of trees, the number of leaves per tree, and which expressions each of the 50 trees asks.

The out-of-bag curve needs the training data (X_train, y_train); the test curve needs X_test and y_test. Both are optional.

Temporal splits ​

With a cutoff per sample, CutoffSplitDisplay draws which cutoff dates train and which test in each split of a TemporalCutoffSplit. It makes gaps and label horizons visible before you trust a score.

python
from sklink.model_selection import TemporalCutoffSplit
from sklink.plotting import CutoffSplitDisplay

db_time, X_time, y_time = make_relational_classification(
    n_entities=200, with_time=True, n_cutoffs=6, random_state=0
)
cv = TemporalCutoffSplit(time="cutoff", n_splits=3, gap="30D")
splits = CutoffSplitDisplay.from_splitter(cv, X_time, y_time)
splits.save("plot-cutoffs.svg")
print(splits.to_text())
text
TemporalCutoffSplit(n_splits=3, gap='30D'): 3 splits over 6 cutoffs, gap 30 days
  split 1: train 2024-03-31 to 2024-09-27 (600 rows) · test 2024-12-26 (200 rows)
  split 2: train 2024-03-31 to 2024-12-26 (800 rows) · test 2025-03-26 (200 rows)
  split 3: train 2024-03-31 to 2025-03-26 (1,000 rows) · test 2025-06-24 (200 rows)

Three temporal splits over six cutoff dates: each trains on earlier cutoffs and tests on a later one, 30 days apart.

Watch a fit while it runs ​

With scikit-learn 1.9 or later, LiveFit is a callback that draws the progress of fit while it runs: trees done and the time left for a forest, iterations for gradient boosting, nodes grown for a tree. When the fit ends it becomes a display like the others.

python
from sklink.plotting import LiveFit

live = LiveFit(output="none")  # "auto" draws in a notebook or a terminal
forest.set_callbacks(live).fit(X_train, y_train)
print(live.record_["status"], live.record_["done"])
text
finished 50

Save, share and redraw ​

Every display has the same methods:

MethodReturns or writes
show()Shows the figure where the code runs: a notebook output or the browser
save(path)An .svg, .html or .json file, chosen by the extension
to_svg()A standalone SVG document, without interaction
to_html()An HTML fragment with inline CSS and JavaScript
to_text()A plain-text summary, also what a terminal prints
to_dict()The data of the figure, JSON-serializable

The constructors also accept the dictionaries of sklink.inspection, such as export_dict(tree). You can redraw a figure from saved JSON on a machine that has neither the model nor the data, with the same display class:

python
import json
from sklink.plotting import TreeDisplay

with open("tree.json") as f:
    TreeDisplay(**json.load(f)["data"])

Figures at a glance ​

DisplayBuilt withShows
SchemaDisplayfrom_database(db), from_estimator(model, y)Tables, keys, relationships, the columns a model reads
TreeDisplayfrom_estimator(tree, X=None)The fitted tree, with the path of some samples
SearchDisplayfrom_estimator(tree, node=0)The questions scored at one node
ExplanationDisplayfrom_estimator(model, X, sample=0)Why one sample got its prediction
ImportanceDisplayfrom_estimator(model)Importance by table, column and primitive
ForestDisplayfrom_estimator(forest, X, y, X_test=, y_test=)Score by number of trees (or boosting iterations), tree sizes, expressions per tree
CutoffSplitDisplayfrom_splitter(cv, X, y)Train and test cutoffs of each temporal split
LiveFitmodel.set_callbacks(LiveFit())The progress of a fit, then its summary

Next: inspect and explain a model with the functions behind these figures, or save and deploy it.

Released under the MIT License.