sklink.inspection
Read what a relational model learned, in terms of tables and columns.
Every output names expressions by their canonical name, such as count(orders[type == 'express']), never by an opaque feature index.
export_textprints the rules of a tree, assklearn.tree.export_textdoes.export_dictandexport_jsondescribe a tree, a forest or a boosting model completely enough to reimplementpredictelsewhere.explaingives the decision path of individual samples.aggregate_importancesgroups importances by table, column, relationship or primitive.describe_expressionslists what a model reads from the database.
The impurity-based importances that trees and forests compute favour expressions with many possible cuts. sklearn.inspection.permutation_importance works with every relational estimator over the columns of X and is the recommended check. sklearn.tree.plot_tree and sklearn.tree.export_graphviz need scikit-learn's own tree structure and do not support relational trees; use export_text instead.
Functions:
- aggregate_importances: Group the importances of a relational model by table, column or primitive.
- describe_expressions: List what each expression of a fitted model reads from the database.
- explain: Explain the predictions of a relational tree or ensemble for some samples.
- export_dict: Describe a fitted relational tree, forest or boosting model with JSON types.
- export_json: Write
export_dictas JSON text. - export_text: Build a text report of the rules of a fitted relational tree.
sklink.inspection.aggregate_importances
aggregate_importances(estimator: Any, *, by: Literal['expression', 'column', 'table', 'relationship', 'primitive'] = 'expression', normalize: bool = True, importances: Any = None) -> dict[str, float]Group the importances of a relational model by table, column or primitive.
The importance of each expression is shared among its parts, so that the total is the same whatever by is:
"expression": per canonical expression name, unchanged."table": to the last table of the expression's path, the table of the rows it aggregates, even when a condition looks up a column of another table (proportion(orders.order_items[products.category == 'toys'])counts fororder_items); attributes of the entity count for the entity table, and columns ofXfor"X"."relationship": in equal parts among the relationships of the path and of the condition lookups; expressions that follow none count for"(none)"."column": in equal parts among the aggregated column and the columns of the conditions, namedtable.columnafter the table that holds them (products.categoryabove); a row count without conditions counts fortable.*, and a column ofXforX.column."primitive": to the primitive of the aggregate; attributes count for"attribute"and columns ofXfor"sample_feature".
A relational tree, forest or boosting model gives its impurity-based importances. A Pipeline that puts a RelationalFeaturizer in front of a scikit-learn model gives that model's feature_importances_, or the importances you pass, such as abs(coef_) of a linear model; each column the model receives is matched by name to the featurizer column it comes from, so steps in between may scale, impute or drop columns, and a ColumnTransformer or FeatureUnion may add the name__ prefixes of its transformers (or the names of a verbose_feature_names_out format string), but one-hot encoding, names made by a function or other steps that rename columns cannot be undone. Nested pipelines and fitted searches are unwrapped. A fitted featurizer with importances in the order of its output columns covers every other case, for example sklearn.inspection.permutation_importance of the rest of the pipeline on the featurizer's output.
Impurity-based importances favour expressions with many possible cuts and are computed on the training data. sklearn.inspection.permutation_importance on held-out data, which works with every relational estimator over the columns of X, is less biased.
Guides: Inspect and explain
Parameters:
- estimator (
relational model, featurizer or pipeline): A fitted relational tree, forest or gradient boosting model, aPipelineending with one or holding oneRelationalFeaturizerin front of a scikit-learn model, a fittedRelationalFeaturizer(withimportances), or a fitted search whosebest_estimator_is one of them. A detached model works. - by (
(expression, column, table, relationship, primitive)): How to group the importances. - normalize (
bool):Truegives shares that sum to 1: for a relational model it starts fromexpression_importances_, otherwise it divides by the total, which needs importances that are not negative.Falsegives the values unchanged: for a relational model, the mean decrease in impurity weighted by the fraction of samples of each node (averaged over the trees of a forest or of a boosting model), as scikit-learn does before normalizing; otherwise the importances as given, negative permutation importances included. - importances (
array-like of shape (n_columns,)): Importance of each column the last step of a featurizer pipeline receives, or of each output column of a featurizer.Nonereadsfeature_importances_of the pipeline's last step. Not accepted with a relational tree, forest or boosting model.
Returns:
- grouped (
dict of str to float): Importance of each group, largest first (ties by name).
Raises:
ValueError: Ifbyis unknown, ifimportanceshas another length than the columns it describes, values that are not finite or, withnormalize=True, negative values or a zero total, or if a column that reaches the model does not come from one column of the featurizer.TypeError: Ifestimatoris none of the above, ifimportancesis passed with a relational tree, forest or boosting model, or if it is not passed with a featurizer alone or with a model that has nofeature_importances_.NotFittedError: If it is not fitted.
See Also
sklink.inspection.describe_expressions : What each expression reads. sklink.plotting.ImportanceDisplay : Draw the importance of tables, columns and primitives. sklearn.inspection.permutation_importance : Importance measured on the predictions, which does not favour expressions with many cuts.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> from sklink.inspection import aggregate_importances
>>> aggregate_importances(tree, by="table")
{'orders': 1.0}The same grouping for any scikit-learn model behind a featurizer:
>>> from sklearn.ensemble import RandomForestClassifier
>>> from sklearn.pipeline import make_pipeline
>>> from sklink.feature_extraction import RelationalFeaturizer
>>> pipe = make_pipeline(
... RelationalFeaturizer(shop.database, entity="customers", key=0),
... RandomForestClassifier(n_estimators=10, random_state=0),
... ).fit(shop.X, shop.y)
>>> shares = aggregate_importances(pipe, by="table")
>>> {table: round(share, 1) for table, share in shares.items()}
{'order_items': 0.5, 'orders': 0.4, 'products': 0.1, 'customers': 0.0}sklink.inspection.describe_expressions
describe_expressions(estimator: Any) -> list[dict[str, Any]]List what each expression of a fitted model reads from the database.
Use it to audit which tables, relationships and columns a featurizer, a tree, a forest or a boosting model depends on.
Guides: Inspect and explain
Parameters:
- estimator (
RelationalFeaturizer, relational tree, forest or boosting model): A fitted estimator, aPipelineending with one or holding one featurizer in front of a scikit-learn model (whose featurizer is described), or a fitted search whosebest_estimator_is one of them. A detached model works.
Returns:
- expressions (
list of dict): One dictionary per entry ofexpressions_, in order, with keys"name"(canonical name),"kind"("sample_feature","attribute","aggregate"or"leaf_sum"),"primitive"(Noneunless an aggregate;"sum_weights"or"mean_weights"for a leaf sum, whose"conditions"are those of all its terms),"table"(last table of the path;Nonefor columns ofX),"path"(relationship names, in order),"column","conditions"(dictionaries with"table"and"column"of the column the condition reads,"op","value"and"lookup", the relationships followed from the last table of the path to that column, empty for a column of that table),"window"(seconds orNone),"output_type"and"requires_time".
Raises:
TypeError: Ifestimatoris not a featurizer, tree, forest or boosting model.NotFittedError: If it is not fitted.
See Also
sklink.inspection.aggregate_importances : Importance by table, column, relationship or primitive. sklink.plotting.SchemaDisplay : Draw the tables, keys and relationships of a database.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> from sklink.inspection import describe_expressions
>>> [entry] = describe_expressions(tree)
>>> entry["name"], entry["table"], entry["path"]
('count(orders)', 'orders', ['orders.customer_id->customers'])sklink.inspection.explain
explain(estimator: Any, X: Any, *, max_samples: int | None = 10) -> list[dict[str, Any]]Explain the predictions of a relational tree or ensemble for some samples.
For a tree, each sample gets its decision path: the questions asked from the root to its leaf, with the value of each expression computed for that sample, the threshold or categories of the question and the branch taken. For a forest, each sample gets the expressions its paths use across the trees, each weighted by the fraction of training samples that reached the node, instead of one path per tree. A gradient boosting model gets the same, and also the signed effect of each expression on its raw prediction, which add up to that prediction exactly.
This is the only function of scikit-link that returns values derived from the data, because it is asked to: the values of the samples in X. It never logs them.
Guides: Inspect and explain
Parameters:
- estimator (
relational tree, forest or gradient boosting model): A fitted relational tree, forest or gradient boosting model, aPipelineending with one (the previous steps transformXfirst), 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. - max_samples (
int or None): Explain only the firstmax_samplesrows ofX;Noneexplains every row.
Returns:
- explanations (
list of dict): One dictionary per explained row, with JSON values only. Common keys are"sample"(row position inX),"prediction"and"value"(class probabilities in the order ofclasses_, or the predicted value, as a list).
For a clustering tree, "prediction" and "cluster" are the cluster of the sample and "value" the center of its leaf in the space of embedding_feature_names_.
For a tree, "leaf" is the node reached and "path" lists one step per question, with keys "node", "expression" (canonical name), "value" (category labels for categorical expressions; None when missing or not seen in fit), "missing", "threshold" (numeric questions), "categories" (the labels that go left, categorical questions), "operator" ("<=", ">", "in", "not in", "is not missing" or "is missing"; a missing value always reads "is missing" and takes the branch the tree learned for missing values) and "branch" ("left" or "right").
For a forest, "contributions" lists the expressions used along the sample's paths, most used first, with keys "expression", "value", "contribution" (fraction of the total, summing to 1) and "n_trees" (number of trees whose path asks about it).
For a gradient boosting model, the contributions are those of a forest, and each also has "effect": what the questions about the expression added to the raw prediction along the sample's paths, scaled by the learning rate, one entry per tree of an iteration (per class for more than two classes). The raw prediction is decision_function for a classifier (the log-odds of the last class for two classes, one score per class for more) and the prediction itself for a regressor. "baseline" is the raw prediction before any question (the initial prediction plus the mean step of each tree over its training rows), and "baseline" plus the sum of the effects equals "raw", the raw prediction of the sample. This is the decomposition of Saabas (2014) along the decision paths.
Raises:
DetachedDatabaseError: If the model was detached from its database.TypeError: Ifestimatoris not a relational tree, forest or gradient boosting model.NotFittedError: If it is not fitted.
See Also
sklink.plotting.ExplanationDisplay : Draw the explanation of one sample. sklink.inspection.export_text : The rules of the whole tree.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> from sklink.inspection import explain
>>> [step] = explain(tree, shop.X, max_samples=1)[0]["path"]
>>> step["expression"], step["value"], step["operator"], step["threshold"]
('count(orders)', 5.0, '>', 2.5)sklink.inspection.export_dict
export_dict(estimator: Any) -> dict[str, Any]Describe a fitted relational tree, forest or boosting model with JSON types.
The description is complete enough to reimplement predict outside Python, and holds no training data beyond thresholds, category labels and per-node sample counts. It is a one-way export: models are persisted with pickle (after sklink.detach), not loaded from this dictionary.
Every question refers to an entry of "expressions", identified by its canonical name and its to_dict definition. To predict, evaluate each expression for the sample, then walk "nodes" from node 0:
- a missing value goes left if and only if
missing_go_to_left; categorical values outside the expression's"categories"count as missing; "split": "numeric"goes left whenvalue <= threshold;"split": "categorical"goes left when the label is inleft_categories;"split": "missing"sends every present value left.
A leaf's "value" holds the class fractions (in the order of "classes") or the mean target. A forest averages the leaf values of its "estimators"; a classifier predicts the class with the largest average. A gradient boosting model ("aggregation": "sum") lists its iterations in "estimators", each a list of trees: one, or one per class for more than two classes. Its raw prediction for output k is baseline[k] + learning_rate * sum of the leaf values of tree k of every iteration; a classifier turns it into probabilities with the logistic function (two classes, probability of the second) or the softmax. A clustering tree ("task": "clustering") stores the centroid of each node in the embedding space as its "value", and each leaf has a "cluster".
When the trees were grown with record_candidates > 0, every split node also has "candidates": the best questions scored there, the one the node asks first (with its exact threshold or categories, missing side and improvement), then the others by decreasing "improvement", one entry per distinct question (with condition_penalty, the node asks the best question net of the cost of its conditions, so another may show a larger improvement; with max_search_samples, a node with more samples records only the few questions with learned conditions that it scored on all its samples). Each is a dictionary with "expression" (the canonical name), "kind" ("numeric" or "categorical"), "threshold" (a number, or None for a categorical question and for a numeric one that only separates missing values), "categories" (the labels that go left, None for numeric questions), "missing_go_to_left", "improvement" (on the scale of the node's) and "refined" (whether the gain comes from the exact refinement of an aggregate's conditions and threshold rather than from the binned pass alone). Leaves never have the key. Candidates are informative only; predicting does not use them.
Guides: Inspect and explain
Parameters:
- estimator (
relational tree, forest or boosting model): A fittedRelationalDecisionTreeClassifier,RelationalDecisionTreeRegressor,RelationalClusteringTree,RelationalRandomForestClassifier,RelationalRandomForestRegressor,RelationalGradientBoostingClassifierorRelationalGradientBoostingRegressor, aPipelineending with one, or a fitted search whosebest_estimator_is one. A detached model works.
Returns:
- description (
dict): With keysformat_version,sklink_version,estimator,task,params,entity,schema,visibility,expressions,classes(classifiers only) and eithernodes(trees) orestimators(forests, each with itsnodes; boosting models, a list of trees per iteration, withlearning_rateandbaseline).paramsdescribe non-JSON values instead of storing them: the database becomes the names of its tables.
Raises:
TypeError: Ifestimatoris not a relational tree, forest or boosting model.NotFittedError: If it is not fitted.
See Also
sklink.inspection.export_json : The same description as JSON text. sklink.inspection.export_text : The rules of a tree as text. sklink.plotting.TreeDisplay : Draw a tree from this description.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> from sklink.inspection import export_dict
>>> root = export_dict(tree)["nodes"][0]
>>> root["expression_name"], root["split"], root["threshold"]
('count(orders)', 'numeric', 2.5)sklink.inspection.export_json
export_json(estimator: Any, path: str | os.PathLike[str] | None = None) -> str | NoneWrite export_dict as JSON text.
Keys are sorted, so the same model always gives the same text.
Guides: Inspect and explain
Parameters:
- estimator (
relational tree, forest or boosting model): Same as inexport_dict. - path (
str or path - like): File to write, in UTF-8.Nonereturns the text instead.
Returns:
- text (
str or None): The JSON text whenpathisNone, elseNone.
See Also
sklink.inspection.export_dict : The same description as a dictionary. sklink.inspection.export_text : The rules of a tree as text.
Examples:
>>> from sklink.datasets import load_shop
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> shop = load_shop()
>>> tree = RelationalDecisionTreeClassifier(
... shop.database, entity="customers", key=0, max_depth=1
... ).fit(shop.X, shop.y)
>>> import json
>>> from sklink.inspection import export_json
>>> json.loads(export_json(tree))["format_version"]
1sklink.inspection.export_text
export_text(estimator: Any, *, max_depth: int | None = None, decimals: int = 3, show_weights: bool = False, class_names: Sequence[str] | None = None) -> strBuild a text report of the rules of a fitted relational tree.
The layout is the one of sklearn.tree.export_text: one line per branch, |--- prefixes and three spaces of indentation per level. Each question is written with the canonical name of its expression. Numeric questions read expr <= t / expr > t; categorical ones read expr in {...} / expr not in {...} with the category labels learned in fit; a question that only separates missing values reads expr is not missing / expr is missing.
Missing values (and categories not seen in fit) follow the branch that had more training weight, unless the tree learned otherwise; in that case the branch that receives them ends with or missing.
Guides: Inspect and explain
Parameters:
- estimator (
relational decision tree or RelationalClusteringTree): FittedRelationalDecisionTreeClassifier,RelationalDecisionTreeRegressororRelationalClusteringTree, aPipelineending with one, or a fitted search whosebest_estimator_is one. The leaves of a clustering tree readcluster: k. - max_depth (
int): Number of levels of questions shown; deeper branches are summarized astruncated branch of depth d, as in scikit-learn.Noneshows the whole tree. - decimals (
int): Decimals of thresholds and of leaf values. - show_weights (
bool): Also show, in the leaves, the weighted number of training samples of each class (classifiers) or of the cluster (clustering trees). - class_names (
sequence of str): Names of the classes, in the order ofclasses_.Noneusesclasses_.
Returns:
- report (
str): Text summary of every rule of the tree.
Raises:
TypeError: Ifestimatoris not a relational tree.NotFittedError: If it is not fitted.
See Also
sklink.inspection.export_dict : The complete description of a tree, a forest or a boosting model. sklink.inspection.export_json : The same description as JSON text. sklink.plotting.TreeDisplay : Draw the tree node by node.
Examples:
>>> from sklink.datasets import make_relational_classification
>>> from sklink.inspection import export_text
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> db, X, y = make_relational_classification(
... 300, signal="conditional", random_state=0
... )
>>> tree = RelationalDecisionTreeClassifier(
... db, entity="customers", key=0, max_depth=1, max_conditions=2
... ).fit(X, y)
>>> print(export_text(tree))
|--- exists(orders[amount > 100.1 & type == 'express']) <= 0.500
| |--- class: 0
|--- exists(orders[amount > 100.1 & type == 'express']) > 0.500
| |--- class: 1