sklink.plotting
Figures that show what a relational model reads, learns and predicts.
Each figure is a display object, created with from_estimator (or from_database) or from the dictionaries of sklink.inspection:
SchemaDisplay: the tables, keys and relationships given to a model, the entity and the target, and the columns the model reads.TreeDisplay: a relational decision tree, with the detail of every node and, optionally, the path of one sample.ExplanationDisplay: why one sample got its prediction, question by question for a tree and expression by expression for a forest.ImportanceDisplay: how the importance of a tree or forest flows from tables to columns to primitives.ForestDisplay: how a forest fitted: its score as trees are added, the size of its trees and where they ask each expression.SearchDisplay: the questions a tree scored at one node, the chosen one first.CutoffSplitDisplay: which cutoff dates train and which test in each split of a temporal cross-validation.LiveFit: a callback that draws the progress offitwhile it runs, and the fitted model when it ends.
In Jupyter, VS Code, Colab and marimo a display shows as interactive HTML, with inline CSS and JavaScript and nothing loaded from the network. The figure is static SVG drawn in Python, so it stays complete where JavaScript does not run. Terminals show a text summary. Every display also offers show(), save() (HTML, SVG or JSON) and to_dict().
The figures use the colors of the scikit-link visual identity and follow the light or dark theme of the notebook.
Classes:
- CutoffSplitDisplay: Which cutoffs train and which test in each split of a cross-validation.
- ExplanationDisplay: Why one sample got its prediction.
- ForestDisplay: How a relational random forest or gradient boosting model fitted.
- ImportanceDisplay: How the importance of a model flows from tables to columns to primitives.
- LiveFit: Draw the progress of
fitwhile it runs, and the model when it ends. - SchemaDisplay: Tables, keys and relationships of a database, as given to a model.
- SearchDisplay: The questions a relational tree scored at one node, the chosen one first.
- TreeDisplay: Relational decision tree, drawn from
export_dict.
sklink.plotting.CutoffSplitDisplay
CutoffSplitDisplay(cutoffs: Sequence[str], counts: Sequence[int], splits: Sequence[Mapping[str, Any]], *, label_horizon: float | None = None, gap: float | None = None, splitter: str | None = None) -> NoneBases: Display
Which cutoffs train and which test in each split of a cross-validation.
Each split is a row on one time axis: the training cutoffs as filled squares, the test cutoffs as open ones and, after the last training cutoff, how far its label looks ahead (the label horizon, then the gap). Cutoffs left out of a split because their label would reach the test period are dashed. A training cutoff at or after the first test cutoff, or whose label reaches it, trains on the future: it is drawn in coral and counted, which is what happens with KFold on temporal data.
Guides: Plot schemas, trees and predictions
Parameters:
- cutoffs (
list of str): The distinct cutoffs, in increasing order, as ISO dates or datetimes. - counts (
list of int): Number of rows ofXat each cutoff. - splits (
list of dict): One dictionary per split with"train"and"test": lists of[i, n]pairs,nrows atcutoffs[i]. - label_horizon (
(float, str, timedelta or None)): How far the label of a sample looks after its cutoff, and the extra separation required before the test period: in seconds, or a duration as inTemporalCutoffSplit. - gap (
(float, str, timedelta or None)): How far the label of a sample looks after its cutoff, and the extra separation required before the test period: in seconds, or a duration as inTemporalCutoffSplit. - splitter (
str or None): How the splitter is written, for the subtitle.
Raises:
ValueError: If the cutoffs are not increasing, a split refers to a cutoff that does not exist orcountsdoes not matchcutoffs.
See Also
sklink.model_selection.TemporalCutoffSplit : The splitter it is made for.
Examples:
>>> import numpy as np
>>> from sklink.model_selection import TemporalCutoffSplit
>>> from sklink.plotting import CutoffSplitDisplay
>>> X = np.empty((8, 1), dtype=object)
>>> X[:, 0] = np.repeat(
... np.array(["2024-01-01", "2024-02-01", "2024-03-01", "2024-04-01"],
... dtype="datetime64[D]"), 2)
>>> cv = TemporalCutoffSplit(time=0, n_splits=2, label_horizon="40D")
>>> text = CutoffSplitDisplay.from_splitter(cv, X).to_text()
>>> for line in text.splitlines()[1:]:
... print(line)
split 1: train 2024-01-01 (2 rows) · test 2024-03-01 (2 rows)
split 2: train 2024-01-01 to 2024-02-01 (4 rows) · test 2024-04-01 (2 rows)Functions:
- from_splitter: Run a splitter on
Xand draw its splits on the cutoff axis. - save: Write the figure to a file chosen by its extension.
- show: Show the figure where the code runs.
- to_dict: Return the data of the figure as a JSON-serializable dictionary.
- to_html: Return the figure as an HTML fragment with inline CSS and JavaScript.
- to_svg: Return the figure as a standalone SVG document, without interaction.
- to_text: Return a plain-text summary of the figure.
Attributes:
sklink.plotting.CutoffSplitDisplay.counts
counts = [int(c) for c in counts]sklink.plotting.CutoffSplitDisplay.cutoffs
cutoffs = cutoffssklink.plotting.CutoffSplitDisplay.from_splitter
from_splitter(splitter: Any, X: Any, y: Any = None, groups: Any = None, *, time: str | int | None = None, label_horizon: Any = None) -> CutoffSplitDisplayRun a splitter on X and draw its splits on the cutoff axis.
Parameters:
- splitter (
cross-validation splitter): ATemporalCutoffSplit, or any scikit-learn splitter, such asKFold, to see what it does with temporal data. - X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the cutoff column. - y (
array - like): Passed tosplitter.split. - groups (
array - like): Passed tosplitter.split. - time (
str or int or None): Cutoff column ofX.Noneusessplitter.time. - label_horizon (
(str, timedelta or None)): How far the label looks after the cutoff, as inTemporalCutoffSplit.Noneusessplitter.label_horizonwhen it has one.
Returns:
- display (
CutoffSplitDisplay):
Raises:
ValueError: If there is no cutoff column, or the splitter cannot splitX.
sklink.plotting.CutoffSplitDisplay.gap
gap = self._gap_ns / 1000000000.0 or Nonesklink.plotting.CutoffSplitDisplay.label_horizon
label_horizon = self._horizon_ns / 1000000000.0 or Nonesklink.plotting.CutoffSplitDisplay.save
save(path: str | Path, *, theme: Theme = 'auto') -> NoneWrite the figure to a file chosen by its extension.
Parameters:
- path (
str or path - like):.htmlwrites a standalone page with interaction,.svgthe static figure and.jsonthe output ofto_dict. - theme (
(auto, light, dark)): Theme of HTML and SVG files.
Raises:
ValueError: If the extension is not.html,.htm,.svgor.json.
sklink.plotting.CutoffSplitDisplay.show
show(*, theme: Theme = 'auto') -> NoneShow the figure where the code runs.
In a notebook the figure is displayed in the output of the cell. In a script or a terminal, it is written to a temporary HTML file that opens in the web browser; if no browser can be opened, the text summary is printed instead.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
sklink.plotting.CutoffSplitDisplay.splits
splits = checkedsklink.plotting.CutoffSplitDisplay.splitter
splitter = splittersklink.plotting.CutoffSplitDisplay.to_dict
to_dict() -> dict[str, Any]Return the data of the figure as a JSON-serializable dictionary.
Returns:
- data (
dict):"format_version","kind"(the figure),"sklink_version"and"data", the inputs the figure is drawn from.
sklink.plotting.CutoffSplitDisplay.to_html
to_html(*, theme: Theme = 'auto') -> strReturn the figure as an HTML fragment with inline CSS and JavaScript.
The fragment loads nothing from the network. Without JavaScript, as in an untrusted notebook or an exported page, it shows the same static figure.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- html (
str):
sklink.plotting.CutoffSplitDisplay.to_svg
to_svg(*, theme: Theme = 'auto') -> strReturn the figure as a standalone SVG document, without interaction.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- svg (
str):
sklink.plotting.CutoffSplitDisplay.to_text
to_text() -> strReturn a plain-text summary of the figure.
sklink.plotting.ExplanationDisplay
ExplanationDisplay(explanation: Mapping[str, Any], *, classes: Sequence[Any] | None = None, n_estimators: int | None = None) -> NoneBases: Display
Why one sample got its prediction.
For a tree, each question on the decision path of the sample is a row: the expression, the value computed for the sample from the database, and, for numeric questions, a number line with the threshold, the side the sample took and the sample itself in coral. For a forest or a gradient boosting model, each row is one of the expressions its trees asked about, with its share of the paths and the number of trees that asked; for boosting, also the signed effect of the expression on the raw prediction (the log-odds of the last class for two classes, the score of the predicted class for more, the predicted value for a regressor). The predicted class probabilities, the predicted value or the cluster close the figure.
Guides: Plot schemas, trees and predictions
Parameters:
- explanation (
dict): One entry ofsklink.inspection.explain. - classes (
list or None): Class labels of a classifier, in the order ofvalue.Nonefor a regressor. - n_estimators (
int or None): Number of trees of a forest or a boosting model, to readn_treesagainst.
Raises:
ValueError: Ifexplanationis not an entry ofexplain, orclassesdoes not match its"value".
See Also
sklink.inspection.explain : The same explanation as a dictionary. TreeDisplay : The whole tree, with the decision path of one sample.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.plotting import ExplanationDisplay
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> display = ExplanationDisplay.from_estimator(tree, shop.X, sample=0)
>>> print(display.to_text())
sample 0: class 1
1. count(orders) = 5 > 2.5, goes rightFunctions:
- from_estimator: Explain the prediction of one row of
X. - save: Write the figure to a file chosen by its extension.
- show: Show the figure where the code runs.
- to_dict: Return the data of the figure as a JSON-serializable dictionary.
- to_html: Return the figure as an HTML fragment with inline CSS and JavaScript.
- to_svg: Return the figure as a standalone SVG document, without interaction.
- to_text: Return the explanation as text, one line per question or expression.
Attributes:
sklink.plotting.ExplanationDisplay.classes
classes = None if classes is None else list(classes)sklink.plotting.ExplanationDisplay.explanation
explanation = dict(explanation)sklink.plotting.ExplanationDisplay.from_estimator
from_estimator(estimator: Any, X: Any, *, sample: int = 0) -> ExplanationDisplayExplain the prediction of one row of X.
Parameters:
- estimator (
relational tree, forest or gradient boosting model): A fitted relational tree (also a clustering tree), forest or gradient boosting model, aPipelineending with one, or a fitted search whosebest_estimator_is one. It needs its database: a detached model must be rebound. - X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit. - sample (
int): Position of the row ofXto explain.
Returns:
- display (
ExplanationDisplay):
Raises:
ValueError: Ifsampleis not a position of a row ofX.TypeError: Ifestimatoris not a relational tree, forest or gradient boosting model.NotFittedError: If it is not fitted.DetachedDatabaseError: If the model was detached from its database.
sklink.plotting.ExplanationDisplay.n_estimators
n_estimators = n_estimatorssklink.plotting.ExplanationDisplay.save
save(path: str | Path, *, theme: Theme = 'auto') -> NoneWrite the figure to a file chosen by its extension.
Parameters:
- path (
str or path - like):.htmlwrites a standalone page with interaction,.svgthe static figure and.jsonthe output ofto_dict. - theme (
(auto, light, dark)): Theme of HTML and SVG files.
Raises:
ValueError: If the extension is not.html,.htm,.svgor.json.
sklink.plotting.ExplanationDisplay.show
show(*, theme: Theme = 'auto') -> NoneShow the figure where the code runs.
In a notebook the figure is displayed in the output of the cell. In a script or a terminal, it is written to a temporary HTML file that opens in the web browser; if no browser can be opened, the text summary is printed instead.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
sklink.plotting.ExplanationDisplay.to_dict
to_dict() -> dict[str, Any]Return the data of the figure as a JSON-serializable dictionary.
Returns:
- data (
dict):"format_version","kind"(the figure),"sklink_version"and"data", the inputs the figure is drawn from.
sklink.plotting.ExplanationDisplay.to_html
to_html(*, theme: Theme = 'auto') -> strReturn the figure as an HTML fragment with inline CSS and JavaScript.
The fragment loads nothing from the network. Without JavaScript, as in an untrusted notebook or an exported page, it shows the same static figure.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- html (
str):
sklink.plotting.ExplanationDisplay.to_svg
to_svg(*, theme: Theme = 'auto') -> strReturn the figure as a standalone SVG document, without interaction.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- svg (
str):
sklink.plotting.ExplanationDisplay.to_text
to_text() -> strReturn the explanation as text, one line per question or expression.
Returns:
- text (
str):
sklink.plotting.ForestDisplay
ForestDisplay(forest: Mapping[str, Any], *, scores: Mapping[str, Any] | None = None, top: int = 12) -> NoneBases: Display
How a relational random forest or gradient boosting model fitted.
The figure has three parts. The score of the forest as trees are added: out of bag when the training data are given, and on a test set when one is given, to see whether more trees would still help. The number of leaves of each tree, one dot per tree (bars when the trees are too many to stack), with the median. And a matrix of the expressions most trees ask, one column per tree: a dot is bigger and stronger the closer to the root the tree first asks the expression.
A gradient boosting model is drawn the same way, its trees in the order they were fitted (one per class and iteration for more than two classes), with its test score by iteration.
Guides: Plot schemas, trees and predictions
Parameters:
- forest (
dict): Output ofsklink.inspection.export_dictfor a fitted relational forest or gradient boosting model. Only the estimator name, the task, the parameters and the nodes of the trees are kept. - scores (
dict or None): Scores after each tree, as returned byfrom_estimatorinto_dict()["data"]["scores"]:"metric","oob","test"and"coverage"(the share of training samples with an out-of-bag tree), each a list with one value per tree orNone, and"unit":"trees", or"iterations"for boosting. - top (
int): Number of expressions in the matrix, those asked by most trees.
Raises:
ValueError: Ifforestis not the export of a forest or gradient boosting model, a list ofscoresis longer than the forest (than its iterations, for"unit": "iterations") ortopis not a positive int.
See Also
TreeDisplay : One tree, node by node. ImportanceDisplay : The importance of tables, columns and primitives.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.ensemble import RelationalRandomForestClassifier
>>> from sklink.plotting import ForestDisplay
>>> shop = load_shop()
>>> forest = RelationalRandomForestClassifier(
... shop.database, entity="customers", key=0, n_estimators=5,
... max_depth=2, random_state=0,
... ).fit(shop.X, shop.y)
>>> display = ForestDisplay.from_estimator(forest, shop.X, shop.y)
>>> print(display.to_text().splitlines()[0])
Relational random forest classifier: 5 trees, max_depth 2Functions:
- from_estimator: Draw a fitted relational forest.
- save: Write the figure to a file chosen by its extension.
- show: Show the figure where the code runs.
- to_dict: Return the data of the figure as a JSON-serializable dictionary.
- to_html: Return the figure as an HTML fragment with inline CSS and JavaScript.
- to_svg: Return the figure as a standalone SVG document, without interaction.
- to_text: Return a plain-text summary of the figure.
Attributes:
sklink.plotting.ForestDisplay.forest
forest = {'estimator': forest.get('estimator', 'RelationalRandomForest'), 'task': forest.get('task'), 'params': {k: params[k] for k in ('n_estimators', 'max_depth', 'max_features', 'bootstrap', 'learning_rate') if k in params}, 'n_iterations': n_iterations, 'estimators': [{'nodes': [{k: n[k] for k in _NODE_KEYS if k in n} for n in e['nodes']]} for e in estimators]}sklink.plotting.ForestDisplay.from_estimator
from_estimator(estimator: Any, X: Any = None, y: Any = None, *, X_test: Any = None, y_test: Any = None, top: int = 12) -> ForestDisplayDraw a fitted relational forest.
Parameters:
- estimator (
relational forest or gradient boosting model): A fitted relational random forest or gradient boosting model, aPipelineending with one, or a fitted search whosebest_estimator_is one. - X (
DataFrame or array - like): The training data, in the order given tofit, for the out-of-bag score after each tree. It needs the database, so a detached model must be rebound, andbootstrap=True. A boosting model has no out-of-bag score and does not use them. - y (
DataFrame or array - like): The training data, in the order given tofit, for the out-of-bag score after each tree. It needs the database, so a detached model must be rebound, andbootstrap=True. A boosting model has no out-of-bag score and does not use them. - X_test (
DataFrame or array - like): Held-out data, for the score of the firstktrees, or of the firstkiterations of a boosting model. - y_test (
DataFrame or array - like): Held-out data, for the score of the firstktrees, or of the firstkiterations of a boosting model. - top (
int): Number of expressions in the matrix.
Returns:
- display (
ForestDisplay):
Raises:
TypeError: Ifestimatoris not a relational forest or gradient boosting model.NotFittedError: If it is not fitted.
sklink.plotting.ForestDisplay.save
save(path: str | Path, *, theme: Theme = 'auto') -> NoneWrite the figure to a file chosen by its extension.
Parameters:
- path (
str or path - like):.htmlwrites a standalone page with interaction,.svgthe static figure and.jsonthe output ofto_dict. - theme (
(auto, light, dark)): Theme of HTML and SVG files.
Raises:
ValueError: If the extension is not.html,.htm,.svgor.json.
sklink.plotting.ForestDisplay.scores
scores = _check_scores(scores, len(estimators), n_iterations)sklink.plotting.ForestDisplay.show
show(*, theme: Theme = 'auto') -> NoneShow the figure where the code runs.
In a notebook the figure is displayed in the output of the cell. In a script or a terminal, it is written to a temporary HTML file that opens in the web browser; if no browser can be opened, the text summary is printed instead.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
sklink.plotting.ForestDisplay.to_dict
to_dict() -> dict[str, Any]Return the data of the figure as a JSON-serializable dictionary.
Returns:
- data (
dict):"format_version","kind"(the figure),"sklink_version"and"data", the inputs the figure is drawn from.
sklink.plotting.ForestDisplay.to_html
to_html(*, theme: Theme = 'auto') -> strReturn the figure as an HTML fragment with inline CSS and JavaScript.
The fragment loads nothing from the network. Without JavaScript, as in an untrusted notebook or an exported page, it shows the same static figure.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- html (
str):
sklink.plotting.ForestDisplay.to_svg
to_svg(*, theme: Theme = 'auto') -> strReturn the figure as a standalone SVG document, without interaction.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- svg (
str):
sklink.plotting.ForestDisplay.to_text
to_text() -> strReturn a plain-text summary of the figure.
sklink.plotting.ForestDisplay.top
top = topsklink.plotting.ImportanceDisplay
ImportanceDisplay(importances: Mapping[str, float], expressions: Sequence[Mapping[str, Any]], *, top: int = 10) -> NoneBases: Display
How the importance of a model flows from tables to columns to primitives.
The three stages show the same total split three ways, as aggregate_importances splits it with by="table", by="column" and by="primitive": each expression counts for the last table of its path and for its primitive, and shares its importance equally among the columns it reads. Columns of X count for the table X. Hovering a node in a notebook highlights its flows.
The impurity-based importances of a relational tree, forest or boosting model favour expressions with many possible cuts. sklearn.inspection.permutation_importance on held-out data is less biased.
Guides: Plot schemas, trees and predictions
Parameters:
- importances (
dict of str to float): Importance of each expression by canonical name, such asaggregate_importances(model, by="expression"). - expressions (
list of dict): Output ofsklink.inspection.describe_expressions, which names the table, columns and primitive of every expression. - top (
int): Number of columns drawn; the others are drawn together asother columns.
Raises:
ValueError: Iftopis not a positive int, orimportancesnames an expression thatexpressionsdoes not describe.
See Also
sklink.inspection.aggregate_importances : The same shares as a dictionary.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.plotting import ImportanceDisplay
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> print(ImportanceDisplay.from_estimator(tree).to_text())
orders 100.0%
orders.* 100.0%
by primitive: count 100.0%Functions:
- from_estimator: Draw the importances of a fitted relational model.
- save: Write the figure to a file chosen by its extension.
- show: Show the figure where the code runs.
- to_dict: Return the data of the figure as a JSON-serializable dictionary.
- to_html: Return the figure as an HTML fragment with inline CSS and JavaScript.
- to_svg: Return the figure as a standalone SVG document, without interaction.
- to_text: Return the importance of each table with its columns, and of each primitive.
Attributes:
sklink.plotting.ImportanceDisplay.expressions
expressions = [dict(e) for e in expressions]sklink.plotting.ImportanceDisplay.from_estimator
from_estimator(estimator: Any, *, normalize: bool = True, top: int = 10, importances: Any = None) -> ImportanceDisplayDraw the importances of a fitted relational model.
Parameters:
- estimator (
relational model, featurizer or pipeline): Whataggregate_importancesaccepts: a fitted relational tree, forest or gradient boosting model, aPipelineending with one or holding aRelationalFeaturizerin front of a scikit-learn model, a fitted featurizer withimportances, or a fitted search whosebest_estimator_is one of them. A detached model works. - normalize (
bool): Passed toaggregate_importances. For a relational model,Truestarts fromexpression_importances_andFalsefrom the mean decrease in impurity before normalization, which gives other shares for a forest or a boosting model. PassFalseto draw importances that can be negative, such as permutation importances. The figure shows shares of the total of the positive importances either way and leaves out the others. - top (
int): Number of columns drawn; the others are drawn together asother columns. - importances (
array-like of shape (n_columns,)): Passed toaggregate_importances: the importance of each column that the model behind a featurizer receives, or of each output column of a featurizer.
Returns:
- display (
ImportanceDisplay):
Raises:
TypeError: Ifestimatoris none of the above, orimportancesis missing or not accepted, as inaggregate_importances.ValueError: Ifimportancesdoes not describe the columns, as inaggregate_importances.NotFittedError: If it is not fitted.
sklink.plotting.ImportanceDisplay.importances
importances = {k: float(v) for k, v in importances.items()}sklink.plotting.ImportanceDisplay.save
save(path: str | Path, *, theme: Theme = 'auto') -> NoneWrite the figure to a file chosen by its extension.
Parameters:
- path (
str or path - like):.htmlwrites a standalone page with interaction,.svgthe static figure and.jsonthe output ofto_dict. - theme (
(auto, light, dark)): Theme of HTML and SVG files.
Raises:
ValueError: If the extension is not.html,.htm,.svgor.json.
sklink.plotting.ImportanceDisplay.show
show(*, theme: Theme = 'auto') -> NoneShow the figure where the code runs.
In a notebook the figure is displayed in the output of the cell. In a script or a terminal, it is written to a temporary HTML file that opens in the web browser; if no browser can be opened, the text summary is printed instead.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
sklink.plotting.ImportanceDisplay.to_dict
to_dict() -> dict[str, Any]Return the data of the figure as a JSON-serializable dictionary.
Returns:
- data (
dict):"format_version","kind"(the figure),"sklink_version"and"data", the inputs the figure is drawn from.
sklink.plotting.ImportanceDisplay.to_html
to_html(*, theme: Theme = 'auto') -> strReturn the figure as an HTML fragment with inline CSS and JavaScript.
The fragment loads nothing from the network. Without JavaScript, as in an untrusted notebook or an exported page, it shows the same static figure.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- html (
str):
sklink.plotting.ImportanceDisplay.to_svg
to_svg(*, theme: Theme = 'auto') -> strReturn the figure as a standalone SVG document, without interaction.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- svg (
str):
sklink.plotting.ImportanceDisplay.to_text
to_text() -> strReturn the importance of each table with its columns, and of each primitive.
Returns:
- text (
str):
sklink.plotting.ImportanceDisplay.top
top = int(top)sklink.plotting.LiveFit
LiveFit(*, oob: bool = True, refresh: float = 0.25, output: Output = 'auto') -> NoneBases: Display
Draw the progress of fit while it runs, and the model when it ends.
A callback for the experimental callbacks of scikit-learn 1.9 or later: pass it to set_callbacks of a relational tree, forest or gradient boosting model. While a forest fits, each tree is a cell that fills as the tree ends (each iteration, for boosting), with the time spent and an estimate of the time left. While a tree fits, the count of its nodes grows. In a notebook the figure updates in the output of the cell (the fits run by one cell, as in a search, share it); in a terminal one line updates in place.
When the fit ends, the figure reads the fitted model: the number of trees, leaves and nodes and, for a forest grown with bootstrap=True, the out-of-bag score after each tree, and for a boosting model its training (and validation) loss. The callback keeps the last fit, so it can be shown again, saved or turned into a dictionary like any display. It never stops a fit, and an error while drawing is recorded in record_["error"] instead of failing the fit.
Guides: Plot schemas, trees and predictions
Parameters:
- oob (
bool): For a forest grown withbootstrap=True, compute the out-of-bag score after each tree once the fit ends, on the training samples that have an out-of-bag tree (seeForestDisplay). It predicts the training data with every tree, which takes about as long asoob_score=True. - refresh (
float): Least time, in seconds, between two updates of the figure. - output (
(auto, text, none)): Where progress shows:"auto"updates the figure in a notebook and a line in a terminal,"text"always writes the line (tosys.stderr; where it is not a console, as in a log, only the last line) and"none"only records the fit.
Attributes:
- record_ (
dict): The last fit:"estimator","unit"("tree","iteration"or"node"),"total"(Nonewhen not known in advance),"done","ends"(seconds from the start at which each subtask ended),"status"("running","finished","stopped"or"failed"),"elapsed","summary","scores"and"error": the last error while drawing, or why the fit was not followed.
See Also
ForestDisplay : The fitted forest, with its scores by number of trees.
Notes
Trees of a forest are reported in order, in the main process, whatever n_jobs is; the trees of a forest report no nodes. It follows one fit at a time: a fit that starts while another one runs, as in a search with a threading backend, is not recorded. The callback is not propagated to the estimators inside a meta-estimator: set it on the relational model itself.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.ensemble import RelationalRandomForestClassifier
>>> from sklink.plotting import LiveFit
>>> shop = load_shop()
>>> forest = RelationalRandomForestClassifier(
... shop.database, entity="customers", key=0, n_estimators=5,
... max_depth=2, random_state=0,
... )
>>> live = LiveFit(output="none")
>>> forest = forest.set_callbacks(live).fit(shop.X, shop.y)
>>> print(live.record_["status"], live.record_["done"])
finished 5Functions:
- on_fit_task_begin: Note the size of the fit when its root task begins.
- on_fit_task_end: Count a tree or a node as it ends; never asks to stop.
- save: Write the figure to a file chosen by its extension.
- setup: Start recording a fit; called by scikit-learn before
fitruns. - show: Show the figure where the code runs.
- teardown: Read the fitted model and draw the final figure.
- to_dict: Return the data of the figure as a JSON-serializable dictionary.
- to_html: Return the figure as an HTML fragment with inline CSS and JavaScript.
- to_svg: Return the figure as a standalone SVG document, without interaction.
- to_text: Return a plain-text summary of the last fit.
sklink.plotting.LiveFit.on_fit_task_begin
on_fit_task_begin(estimator: Any, context: Any, *, X: Any = None, y: Any = None) -> NoneNote the size of the fit when its root task begins.
sklink.plotting.LiveFit.on_fit_task_end
on_fit_task_end(estimator: Any, context: Any) -> boolCount a tree or a node as it ends; never asks to stop.
sklink.plotting.LiveFit.oob
oob = bool(oob)sklink.plotting.LiveFit.output
output = outputsklink.plotting.LiveFit.record_
record_: dict[str, Any] = _empty()sklink.plotting.LiveFit.refresh
refresh = float(refresh)sklink.plotting.LiveFit.save
save(path: str | Path, *, theme: Theme = 'auto') -> NoneWrite the figure to a file chosen by its extension.
Parameters:
- path (
str or path - like):.htmlwrites a standalone page with interaction,.svgthe static figure and.jsonthe output ofto_dict. - theme (
(auto, light, dark)): Theme of HTML and SVG files.
Raises:
ValueError: If the extension is not.html,.htm,.svgor.json.
sklink.plotting.LiveFit.setup
setup(estimator: Any, context: Any) -> NoneStart recording a fit; called by scikit-learn before fit runs.
sklink.plotting.LiveFit.show
show(*, theme: Theme = 'auto') -> NoneShow the figure where the code runs.
In a notebook the figure is displayed in the output of the cell. In a script or a terminal, it is written to a temporary HTML file that opens in the web browser; if no browser can be opened, the text summary is printed instead.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
sklink.plotting.LiveFit.teardown
teardown(estimator: Any, context: Any) -> NoneRead the fitted model and draw the final figure.
Errors here are recorded in record_["error"] and never raised: scikit-learn raises the errors of teardown, and the figure must not fail a fit that succeeded.
sklink.plotting.LiveFit.to_dict
to_dict() -> dict[str, Any]Return the data of the figure as a JSON-serializable dictionary.
Returns:
- data (
dict):"format_version","kind"(the figure),"sklink_version"and"data", the inputs the figure is drawn from.
sklink.plotting.LiveFit.to_html
to_html(*, theme: Theme = 'auto') -> strReturn the figure as an HTML fragment with inline CSS and JavaScript.
The fragment loads nothing from the network. Without JavaScript, as in an untrusted notebook or an exported page, it shows the same static figure.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- html (
str):
sklink.plotting.LiveFit.to_svg
to_svg(*, theme: Theme = 'auto') -> strReturn the figure as a standalone SVG document, without interaction.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- svg (
str):
sklink.plotting.LiveFit.to_text
to_text() -> strReturn a plain-text summary of the last fit.
sklink.plotting.SchemaDisplay
SchemaDisplay(schema: Mapping[str, Any], *, n_rows: Mapping[str, int] | None = None, entity: str | None = None, target: Mapping[str, Any] | None = None, used_columns: Sequence[str] | None = None, used_relationships: Sequence[str] | None = None, statistics: Mapping[str, Mapping[str, Any]] | None = None) -> NoneBases: Display
Tables, keys and relationships of a database, as given to a model.
Each table is a card with its columns, their semantic types and the primary (PK) and foreign (FK) keys. Relationships link a foreign key to the key it references, with n on the side of the many rows. The entity, the table of the samples, comes first and carries the target when it is known. For a fitted model, the columns and relationships that its expressions read are drawn in eucalyptus.
Database objects show this figure in notebooks.
Guides: Plot schemas, trees and predictions
Parameters:
- schema (
dict): Output ofsklink.Schema.to_dict, or the"schema"ofsklink.inspection.export_dict. - n_rows (
dict of str to int or None): Number of rows of each table. - entity (
str or None): Table of the samples, drawn first. - target (
dict or None): Summary of the target:{"task": "classification", "classes": [...], "counts": [...]}or{"task": "regression", "n": ..., "min": ..., "mean": ..., "max": ...}."counts"and the statistics are optional. - used_columns (
list of str or None): Columns read by a model, as"table.column";"table.*"marks a table whose rows are counted. - used_relationships (
list of str or None): Names of the relationships followed by a model. - statistics (
dict of str to dict or None): Fan-out of each relationship, by name: the"statistics"ofDatabase.describe(statistics=True). Each relationship then gets a histogram of the number of child rows per parent row.
Raises:
ValueError: Ifschemais not the output ofsklink.Schema.to_dict,entityis not one of its tables, ortargetis malformed.
See Also
sklink.inspection.describe_expressions : What each expression reads.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.plotting import SchemaDisplay
>>> shop = load_shop()
>>> display = SchemaDisplay.from_database(shop.database, entity="customers")
>>> display
<SchemaDisplay: 4 tables, 3 relationships>Functions:
- from_database: Draw a database.
- from_estimator: Draw the database of a fitted model and what its expressions read.
- save: Write the figure to a file chosen by its extension.
- show: Show the figure where the code runs.
- to_dict: Return the data of the figure as a JSON-serializable dictionary.
- to_html: Return the figure as an HTML fragment with inline CSS and JavaScript.
- to_svg: Return the figure as a standalone SVG document, without interaction.
- to_text: Return the tables, their columns and the relationships as text.
Attributes:
sklink.plotting.SchemaDisplay.entity
entity = entitysklink.plotting.SchemaDisplay.from_database
from_database(database: Any, *, entity: str | None = None, y: Any = None) -> SchemaDisplayDraw a database.
Parameters:
- database (
Database): Database to draw. - entity (
str or None): Table of the samples, drawn first. - y (
array-like of shape (n_samples,) or None): Target, summarized on the entity: class counts, or minimum, mean and maximum when it holds non-integer numbers.
Returns:
- display (
SchemaDisplay):
Raises:
TypeError: Ifdatabaseis not asklink.Database.ValueError: Ifentityis not a table ofdatabaseoryis not one-dimensional.
sklink.plotting.SchemaDisplay.from_estimator
from_estimator(estimator: Any, y: Any = None) -> SchemaDisplayDraw the database of a fitted model and what its expressions read.
Parameters:
- estimator (
relational tree, forest or featurizer): A fitted estimator, aPipelineending with one or holding one featurizer in front of a scikit-learn model, or a fitted search whosebest_estimator_is one of them. A detached model works, without row counts. - y (
array-like of shape (n_samples,) or None): Target used to summarize the classes or values. By default, a tree summarizes its training samples, a forest shows its classes (or that it is a regressor) and a featurizer shows no target.
Returns:
- display (
SchemaDisplay):
Raises:
TypeError: Ifestimatoris not a relational featurizer, tree or forest.NotFittedError: If it is not fitted.
sklink.plotting.SchemaDisplay.n_rows
n_rows = None if n_rows is None else {k: int(v) for k, v in n_rows.items()}sklink.plotting.SchemaDisplay.save
save(path: str | Path, *, theme: Theme = 'auto') -> NoneWrite the figure to a file chosen by its extension.
Parameters:
- path (
str or path - like):.htmlwrites a standalone page with interaction,.svgthe static figure and.jsonthe output ofto_dict. - theme (
(auto, light, dark)): Theme of HTML and SVG files.
Raises:
ValueError: If the extension is not.html,.htm,.svgor.json.
sklink.plotting.SchemaDisplay.schema
schema = dict(schema)sklink.plotting.SchemaDisplay.show
show(*, theme: Theme = 'auto') -> NoneShow the figure where the code runs.
In a notebook the figure is displayed in the output of the cell. In a script or a terminal, it is written to a temporary HTML file that opens in the web browser; if no browser can be opened, the text summary is printed instead.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
sklink.plotting.SchemaDisplay.statistics
statistics = None if statistics is None else {k: dict(v) for k, v in statistics.items()}sklink.plotting.SchemaDisplay.target
target = None if target is None else dict(target)sklink.plotting.SchemaDisplay.to_dict
to_dict() -> dict[str, Any]Return the data of the figure as a JSON-serializable dictionary.
Returns:
- data (
dict):"format_version","kind"(the figure),"sklink_version"and"data", the inputs the figure is drawn from.
sklink.plotting.SchemaDisplay.to_html
to_html(*, theme: Theme = 'auto') -> strReturn the figure as an HTML fragment with inline CSS and JavaScript.
The fragment loads nothing from the network. Without JavaScript, as in an untrusted notebook or an exported page, it shows the same static figure.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- html (
str):
sklink.plotting.SchemaDisplay.to_svg
to_svg(*, theme: Theme = 'auto') -> strReturn the figure as a standalone SVG document, without interaction.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- svg (
str):
sklink.plotting.SchemaDisplay.to_text
to_text() -> strReturn the tables, their columns and the relationships as text.
Returns:
- text (
str):
sklink.plotting.SchemaDisplay.used_columns
used_columns = None if used_columns is None else list(used_columns)sklink.plotting.SchemaDisplay.used_relationships
used_relationships = None if used_relationships is None else list(used_relationships)sklink.plotting.SearchDisplay
SearchDisplay(tree: Mapping[str, Any], *, node: int = 0) -> NoneBases: Display
The questions a relational tree scored at one node, the chosen one first.
Every recorded candidate is a row with its expression, the condition that sends samples left and, on one axis, its weighted impurity decrease. Dots are filled for aggregates whose rows are filtered ([type == 'x']), open for aggregates without a filter and gray for columns of X. The question the node asks is ringed, and the figure says by how much it beat the runner-up and the best question without a filter.
The tree keeps the record_candidates best questions of each node (five by default for a tree, none for a forest). Grow it with a larger record_candidates to see more.
Guides: Plot schemas, trees and predictions
Parameters:
- tree (
dict): Output ofsklink.inspection.export_dictfor a relational tree grown withrecord_candidates > 0. - node (
int): Id of a split node.
Raises:
ValueError: Ifnodeis not a split node oftree, or it has no recorded candidates.
See Also
TreeDisplay : The whole tree, node by node.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.plotting import SearchDisplay
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> print(SearchDisplay.from_estimator(tree).to_text().splitlines()[0])
node 0 (depth 0, 24 samples): 5 best questions recordedFunctions:
- from_estimator: Draw the questions scored at one node of a fitted relational tree.
- save: Write the figure to a file chosen by its extension.
- show: Show the figure where the code runs.
- to_dict: Return the data of the figure as a JSON-serializable dictionary.
- to_html: Return the figure as an HTML fragment with inline CSS and JavaScript.
- to_svg: Return the figure as a standalone SVG document, without interaction.
- to_text: Return a plain-text summary of the figure.
Attributes:
sklink.plotting.SearchDisplay.from_estimator
from_estimator(estimator: Any, *, node: int = 0) -> SearchDisplayDraw the questions scored at one node of a fitted relational tree.
Parameters:
- estimator (
relational tree): A fitted relational decision tree grown withrecord_candidates > 0, aPipelineending with one, or a fitted search whosebest_estimator_is one. To draw a tree of a forest grown withrecord_candidates, passforest.estimators_[i]; of a gradient boosting model,model.estimators_[i, k]. - node (
int): Id of a split node;0is the root.
Returns:
- display (
SearchDisplay):
Raises:
TypeError: Ifestimatoris not a relational tree.ValueError: Ifnodeis not a split node with recorded candidates.
sklink.plotting.SearchDisplay.node
node = nodesklink.plotting.SearchDisplay.save
save(path: str | Path, *, theme: Theme = 'auto') -> NoneWrite the figure to a file chosen by its extension.
Parameters:
- path (
str or path - like):.htmlwrites a standalone page with interaction,.svgthe static figure and.jsonthe output ofto_dict. - theme (
(auto, light, dark)): Theme of HTML and SVG files.
Raises:
ValueError: If the extension is not.html,.htm,.svgor.json.
sklink.plotting.SearchDisplay.show
show(*, theme: Theme = 'auto') -> NoneShow the figure where the code runs.
In a notebook the figure is displayed in the output of the cell. In a script or a terminal, it is written to a temporary HTML file that opens in the web browser; if no browser can be opened, the text summary is printed instead.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
sklink.plotting.SearchDisplay.to_dict
to_dict() -> dict[str, Any]Return the data of the figure as a JSON-serializable dictionary.
Returns:
- data (
dict):"format_version","kind"(the figure),"sklink_version"and"data", the inputs the figure is drawn from.
sklink.plotting.SearchDisplay.to_html
to_html(*, theme: Theme = 'auto') -> strReturn the figure as an HTML fragment with inline CSS and JavaScript.
The fragment loads nothing from the network. Without JavaScript, as in an untrusted notebook or an exported page, it shows the same static figure.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- html (
str):
sklink.plotting.SearchDisplay.to_svg
to_svg(*, theme: Theme = 'auto') -> strReturn the figure as a standalone SVG document, without interaction.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- svg (
str):
sklink.plotting.SearchDisplay.to_text
to_text() -> strReturn a plain-text summary of the figure.
sklink.plotting.SearchDisplay.tree
tree: dict[str, Any] = {'estimator': tree.get('estimator'), 'entity': tree.get('entity'), 'nodes': [self._entry], 'expressions': [{'name': n, 'definition': d} for n, d in sorted(definitions.items())]}sklink.plotting.TreeDisplay
TreeDisplay(tree: Mapping[str, Any], *, explanation: Mapping[str, Any] | None = None, max_depth: int | None = 4) -> NoneBases: Display
Relational decision tree, drawn from export_dict.
Each node is a card with its question, its number of training samples and the share of each class (the mean value, in regression; the cluster of each leaf, for a clustering tree). Edges are as wide as the samples they carry and are labeled with the condition. In a notebook, clicking a node shows its detail: the samples that reach it, how much its split lowers the impurity, what its expression reads from the database and the rules that lead to it. With a sample, its decision path is drawn in coral.
Create it with from_estimator, or from saved dictionaries with the constructor.
Guides: Plot schemas, trees and predictions
Parameters:
- tree (
dict): Output ofsklink.inspection.export_dictfor one tree, or ofjson.loadsonsklink.inspection.export_json. - explanation (
dict or None): One entry ofsklink.inspection.explainfor this tree. Its decision path is drawn in coral. - max_depth (
int or None): Deepest level drawn; deeper subtrees are folded into their top node, which shows how many nodes it hides.Nonedraws every node.
See Also
sklink.inspection.export_text : The rules of a tree as text. ExplanationDisplay : The decision path of one sample, step by step.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.plotting import TreeDisplay
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=2
... ).fit(shop.X, shop.y)
>>> display = TreeDisplay.from_estimator(tree, shop.X) # follows the first row
>>> display
<TreeDisplay: 3 nodes, depth 1>
>>> print(display.to_text())
|--- count(orders) <= 2.5
| |--- class: 0
|--- count(orders) > 2.5
| |--- class: 1Functions:
- from_estimator: Draw a fitted relational tree.
- save: Write the figure to a file chosen by its extension.
- show: Show the figure where the code runs.
- to_dict: Return the data of the figure as a JSON-serializable dictionary.
- to_html: Return the figure as an HTML fragment with inline CSS and JavaScript.
- to_svg: Return the figure as a standalone SVG document, without interaction.
- to_text: Return the rules of the drawn tree as text.
Attributes:
sklink.plotting.TreeDisplay.explanation
explanation = None if explanation is None else dict(explanation)sklink.plotting.TreeDisplay.from_estimator
from_estimator(estimator: Any, X: Any = None, *, max_depth: int | None = 4) -> TreeDisplayDraw a fitted relational tree.
Parameters:
- estimator (
relational tree): A fitted relational decision tree or clustering tree, aPipelineending with one, or a fitted search whosebest_estimator_is one. To draw a tree of a forest, passforest.estimators_[i]. - X (
DataFrame or array - like or None): Population table. The decision path of its first row is drawn in coral; it needs the database, so a detached model must be rebound. - max_depth (
int or None): Deepest level drawn.Nonedraws every node.
Returns:
- display (
TreeDisplay):
sklink.plotting.TreeDisplay.max_depth
max_depth = max_depthsklink.plotting.TreeDisplay.save
save(path: str | Path, *, theme: Theme = 'auto') -> NoneWrite the figure to a file chosen by its extension.
Parameters:
- path (
str or path - like):.htmlwrites a standalone page with interaction,.svgthe static figure and.jsonthe output ofto_dict. - theme (
(auto, light, dark)): Theme of HTML and SVG files.
Raises:
ValueError: If the extension is not.html,.htm,.svgor.json.
sklink.plotting.TreeDisplay.show
show(*, theme: Theme = 'auto') -> NoneShow the figure where the code runs.
In a notebook the figure is displayed in the output of the cell. In a script or a terminal, it is written to a temporary HTML file that opens in the web browser; if no browser can be opened, the text summary is printed instead.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
sklink.plotting.TreeDisplay.to_dict
to_dict() -> dict[str, Any]Return the data of the figure as a JSON-serializable dictionary.
Returns:
- data (
dict):"format_version","kind"(the figure),"sklink_version"and"data", the inputs the figure is drawn from.
sklink.plotting.TreeDisplay.to_html
to_html(*, theme: Theme = 'auto') -> strReturn the figure as an HTML fragment with inline CSS and JavaScript.
The fragment loads nothing from the network. Without JavaScript, as in an untrusted notebook or an exported page, it shows the same static figure.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- html (
str):
sklink.plotting.TreeDisplay.to_svg
to_svg(*, theme: Theme = 'auto') -> strReturn the figure as a standalone SVG document, without interaction.
Parameters:
- theme (
(auto, light, dark)):"auto"follows the host and the system color scheme.
Returns:
- svg (
str):
sklink.plotting.TreeDisplay.to_text
to_text() -> strReturn the rules of the drawn tree as text.
The layout is the one of sklink.inspection.export_text. Subtrees folded by max_depth read truncated branch of n nodes.
Returns:
- text (
str):
sklink.plotting.TreeDisplay.tree
tree = dict(tree)