sklink.tree
Decision trees that ask about aggregates of related tables.
Classes:
- RelationalDecisionTreeClassifier: Decision tree classifier whose questions can aggregate related tables.
- RelationalDecisionTreeRegressor: Decision tree regressor whose questions can aggregate related tables.
- RelationalTree: Fitted tree structure as parallel arrays, one entry per node.
- SplitCandidates: Best questions scored at the split nodes of a tree, the chosen one first.
sklink.tree.RelationalDecisionTreeClassifier
RelationalDecisionTreeClassifier(database: Database | None = None, *, entity: str | None = None, key: str | int | Sequence[str | int] | None = None, time: str | int | None = None, criterion: Literal['gini', 'entropy', 'log_loss'] = 'gini', max_depth: int | None = None, min_samples_split: int | float = 2, min_samples_leaf: int | float = 1, min_weight_fraction_leaf: float = 0.0, max_features: int | float | Literal['sqrt', 'log2'] | None = None, max_leaf_nodes: int | None = None, min_impurity_decrease: float = 0.0, class_weight: dict[Any, float] | Literal['balanced'] | None = None, max_relationship_depth: int = 2, max_lookup_depth: int = 1, primitives: Literal['default'] | Sequence[str] = 'default', max_conditions: int = 2, condition_penalty: float = 0.0, max_search_samples: int | None = None, max_bins: int = 255, max_condition_bins: int = 32, max_categories: int = 32, record_candidates: int = 5, allow_reverse_paths: bool = False, handle_unknown_entity: Literal['error', 'empty'] = 'error', random_state: int | np.random.RandomState | None = None) -> NoneBases: ClassifierMixin, BaseRelationalTree
Decision tree classifier whose questions can aggregate related tables.
Each node asks either about a column of X or of the entity, or about an aggregate over rows of a related table, such as count(orders[amount > 137.5 & type == 'express']) <= 2.5. The conditions inside the aggregate, their thresholds and the outer threshold are all learned while growing the tree. With database=None it is a standard CART tree on the columns of X.
Guides: Relational decision trees, Tune trees and forests
Parameters:
- database (
Database): Related tables.Nonegives a standard tree onX. - entity (
str): Table whose rows are the samples; required with a database. - key (
(str, int or sequence)): Column(s) ofXholding the entity key. - time (
str or int): Column ofXwith the cutoff of each sample.Noneis the static mode: every related row is visible. - criterion (
(gini, entropy, log_loss)): Impurity measure, as in scikit-learn. - max_depth (
int): Maximum depth of the tree. - min_samples_split (
int or float): Minimum number of samples to split a node. - min_samples_leaf (
int or float): Minimum number of samples in each leaf. - min_weight_fraction_leaf (
float): Minimum fraction of the total sample weight in each leaf. - max_features (
(int, float, {sqrt, log2} or None)): Number of candidate groups tried at each node. A group is one base feature, or one related table with one aggregated column (or its rows), so that wide tables do not dominate the sampling. - max_leaf_nodes (
int): Grow best-first with at most this many leaves. - min_impurity_decrease (
float): A node is split only if the weighted impurity decrease reaches this. - class_weight (
(dict, balanced or None)): Weights of the classes, as in scikit-learn. - max_relationship_depth (
int): Maximum number of relationship hops of a path. - max_lookup_depth (
int): Maximum number of lookups (many-to-one steps after the last table of a path) from the rows a path aggregates to the columns its conditions read, such asproportion(orders.order_items[products.category == 'toys']). These lookups start wheremax_relationship_depthstops and do not count as hops of it. The columns of the looked-up tables are also aggregated without conditions, such asmean(orders.order_items.products.price).0keeps conditions and aggregates on the last table of the path. A numeric column of a looked-up table getsmax(2, max_condition_bins // 4)candidate cuts. - primitives (
"default" or sequence of str): Primitives of the unconditioned aggregates. - max_conditions (
int): Conditions learned inside an aggregate: 0, 1 or 2. With 2, the second condition is searched for the best few first ones, such ascount(orders[amount > 100.0 & type == 'express']); 1 fits about twice as fast. - condition_penalty (
float): Gain each learned condition must pay before it is chosen: this value times the gain one condition makes by chance at the node (the node impurity for the Gini index and the squared error, a constant for the entropy, times the mean sample weight per row) and the log of the number of conditions its path offers. The best of many conditions gains by chance alone, so this Bonferroni-style correction keeps conditions that only fit noise out of small nodes; a question whose conditions do not pay for themselves is not asked. Improvements and importances stay the impurity decrease itself. Higher values prefer aggregates without conditions on small or noisy data;0disables it. - max_search_samples (
int or None): Samples on which a node searches its aggregates with learned conditions. A node with more samples searches them on this many, drawn at random once per tree, with the leaf limits scaled to that share, then scores the best few on all its samples, so that the condition search costs the same at any size of the data. Withrecord_candidates, such a node records only those few among the questions with learned conditions.Nonesearches on all samples. - max_bins (
int): Thresholds per base feature, as quantiles of the training samples. - max_condition_bins (
int): Candidate cuts per numeric condition column before refinement; a quarter of it, at least 2, for a column of a looked-up table (seemax_lookup_depth). - max_categories (
int): Most frequent categories tried in==conditions. In regression and binary classification, a categorical column with more categories among the reachable rows also gets conditions on sets of categories: its categories are ranked once, infit, by the mean target of the training samples whose rows have them (shrunk towards the overall mean, so that rare categories rank in the middle), and a condition keeps the categories on one side of a cut of that ranking, such ascount(orders[merchant in ('m017', 'm203', ...)]). Categories that the rows of fewer than 5 training entities have are not ranked (an entity counts once, at any number of cutoffs and with any weight), so that a column of identifiers does not sort the samples by their own target. - record_candidates (
int): Number of best questions kept for each split node, the one it asks first, intree_.candidates;sklink.inspection.export_dictlists them.0keeps none and leavestree_.candidatesatNone. - allow_reverse_paths (
bool): Allow paths that read rows of other entities through shared tables. - handle_unknown_entity (
(error, empty)): What to do with keys that are not in the entity table. - random_state (
(int, RandomState or None)): Controls the sampling ofmax_featuresand the samples drawn formax_search_samples.
Attributes:
- tree_ (
RelationalTree): Fitted structure. - expressions_ (
tuple of Expression): Distinct questions used by the nodes;tree_.expressionindexes it. - classes_ (
ndarray of shape (n_classes,)): Class labels. - n_classes_ (
int): Number of classes. - feature_importances_ (
ndarray of shape (n_features_in_,)): Impurity-based importance per column ofX; questions that are not columns ofXcount for the key column. - expression_importances_ (
dict): Importance per canonical expression name. - schema_ (
Schema or None): Part of the database schema the model reads. - visibility_ (
Visibility): Visibility rules used during fit. - categories_ (
dict): Category vocabulary of each categorical expression used. - bin_edges_ (
dict): Candidate thresholds of each numeric base expression used. - n_features_in_ (
int): Number of columns ofX. - feature_names_in_ (
ndarray of shape (n_features_in_,)): Column names ofXwhen it has them. - n_outputs_ (
int): Always 1.
See Also
sklink.tree.RelationalDecisionTreeRegressor : The same tree for a numeric target. sklink.ensemble.RelationalRandomForestClassifier : Averages many such trees grown on bootstrap samples. sklink.feature_extraction.RelationalFeaturizer : Relational features as columns, for any scikit-learn estimator. sklink.inspection.export_text : Print the rules of a fitted tree.
Notes
A categorical feature, such as mode(orders.merchant) or a categorical column of X, splits on a set of its categories: those of the node are ordered by their mean target and the set is a prefix of that order, as in scikit-learn's HistGradientBoostingClassifier. As there, a category that fewer than 10 samples of the node have is not ordered and goes right, as a category that no sample of the node has does: ordered by their own targets, categories of one or two samples each would give a split that only memorizes them. Sample weights count here, and in the smoothing of ranked categories, in units of their mean over the distinct training samples (samples with the same entity, cutoff and columns of X are one): integer weights count as repeated rows, and normalized weights or class_weight change nothing.
With scikit-learn 1.9 or later the tree supports scikit-learn's experimental callbacks: set them with set_callbacks, for example sklearn.callback.ProgressBar. The "fit" task has one subtask per node, named "node", whose task_id is the node id in tree_ (where its split, size and improvement are once fitted); the number of nodes is not known in advance. A node ends once it is split or is final as a leaf; with max_leaf_nodes that can be after other nodes began. As scikit-learn specifies, a true return of on_fit_task_end asks to stop the iterations: for a node, it stops the growth. No other node is searched, the nodes not yet split stay leaves (the nodes that began still end, the others are not reported) and the tree is fitted as it stands. The "fit" task gets X, y and, when given, metadata={"sample_weight": ...}, and its end the fitted tree. Callbacks that never ask to stop change nothing that is learned. With scikit-learn 1.8 there is no set_callbacks.
Examples:
>>> from sklink.datasets import make_relational_classification
>>> from sklink.tree import RelationalDecisionTreeClassifier
>>> db, X, y = make_relational_classification(
... 300, signal="conditional", output="numpy", random_state=0
... )
>>> tree = RelationalDecisionTreeClassifier(
... db, entity="customers", key=0, max_depth=1, max_conditions=2
... ).fit(X, y)
>>> tree.score(X, y)
1.0Functions:
- apply: Index of the leaf that each sample ends up in.
- decision_path: Nodes that each sample goes through.
- fit: Grow the tree.
- get_depth: Depth of the tree (a single leaf has depth 0).
- get_n_leaves: Return the number of leaves of the tree.
- predict: Most probable class of each sample.
- predict_log_proba: Logarithm of
predict_proba. - predict_proba: Class probabilities: weighted class fractions of the leaf.
sklink.tree.RelationalDecisionTreeClassifier.allow_reverse_paths
allow_reverse_paths = allow_reverse_pathssklink.tree.RelationalDecisionTreeClassifier.apply
apply(X: Any) -> npt.NDArray[np.int64]Index of the leaf that each sample ends up in.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- X_leaves (
ndarray of shape (n_samples,)): Node index of the leaf of each sample.
sklink.tree.RelationalDecisionTreeClassifier.class_weight
class_weight = class_weightsklink.tree.RelationalDecisionTreeClassifier.condition_penalty
condition_penalty = condition_penaltysklink.tree.RelationalDecisionTreeClassifier.criterion
criterion = criterionsklink.tree.RelationalDecisionTreeClassifier.database
database = databasesklink.tree.RelationalDecisionTreeClassifier.decision_path
decision_path(X: Any) -> scipy.sparse.csr_arrayNodes that each sample goes through.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- indicator (
sparse array of shape (n_samples, n_nodes)): Nonzero entries mark the visited nodes.
sklink.tree.RelationalDecisionTreeClassifier.entity
entity = entitysklink.tree.RelationalDecisionTreeClassifier.fit
fit(X: Any, y: Any, sample_weight: Any = None) -> SelfGrow the tree.
With scikit-learn 1.9 or later, callbacks set with set_callbacks follow the fit: see RelationalDecisionTreeClassifier.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table: entity key, optional cutoff and sample features. - y (
array-like of shape (n_samples,)): Class labels. - sample_weight (
array-like of shape (n_samples,)): Sample weights; a sample's weight does not depend on its number of related rows. Integer weights give the tree ofXwith rows repeated, bins included, and a row of weight zero is ignored as if it were not inX. Where the search counts samples (see Notes), weights count in units of their mean per distinct sample, so that scaling all of them changes nothing.
Returns:
- self (
RelationalDecisionTreeClassifier): Fitted estimator.
sklink.tree.RelationalDecisionTreeClassifier.get_depth
get_depth() -> intDepth of the tree (a single leaf has depth 0).
Returns:
- depth (
int): Maximum distance between the root and a leaf.
sklink.tree.RelationalDecisionTreeClassifier.get_n_leaves
get_n_leaves() -> intReturn the number of leaves of the tree.
Returns:
- n_leaves (
int): Number of leaves.
sklink.tree.RelationalDecisionTreeClassifier.handle_unknown_entity
handle_unknown_entity = handle_unknown_entitysklink.tree.RelationalDecisionTreeClassifier.key
key = keysklink.tree.RelationalDecisionTreeClassifier.max_bins
max_bins = max_binssklink.tree.RelationalDecisionTreeClassifier.max_categories
max_categories = max_categoriessklink.tree.RelationalDecisionTreeClassifier.max_condition_bins
max_condition_bins = max_condition_binssklink.tree.RelationalDecisionTreeClassifier.max_conditions
max_conditions = max_conditionssklink.tree.RelationalDecisionTreeClassifier.max_depth
max_depth = max_depthsklink.tree.RelationalDecisionTreeClassifier.max_features
max_features = max_featuressklink.tree.RelationalDecisionTreeClassifier.max_leaf_nodes
max_leaf_nodes = max_leaf_nodessklink.tree.RelationalDecisionTreeClassifier.max_lookup_depth
max_lookup_depth = max_lookup_depthsklink.tree.RelationalDecisionTreeClassifier.max_relationship_depth
max_relationship_depth = max_relationship_depthsklink.tree.RelationalDecisionTreeClassifier.max_search_samples
max_search_samples = max_search_samplessklink.tree.RelationalDecisionTreeClassifier.min_impurity_decrease
min_impurity_decrease = min_impurity_decreasesklink.tree.RelationalDecisionTreeClassifier.min_samples_leaf
min_samples_leaf = min_samples_leafsklink.tree.RelationalDecisionTreeClassifier.min_samples_split
min_samples_split = min_samples_splitsklink.tree.RelationalDecisionTreeClassifier.min_weight_fraction_leaf
min_weight_fraction_leaf = min_weight_fraction_leafsklink.tree.RelationalDecisionTreeClassifier.predict
predict(X: Any) -> np.ndarrayMost probable class of each sample.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- y_pred (
ndarray of shape (n_samples,)): Predicted labels.
sklink.tree.RelationalDecisionTreeClassifier.predict_log_proba
predict_log_proba(X: Any) -> np.ndarrayLogarithm of predict_proba.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- log_proba (
ndarray of shape (n_samples, n_classes)): Columns in the order ofclasses_.
sklink.tree.RelationalDecisionTreeClassifier.predict_proba
predict_proba(X: Any) -> np.ndarrayClass probabilities: weighted class fractions of the leaf.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- proba (
ndarray of shape (n_samples, n_classes)): Columns in the order ofclasses_.
sklink.tree.RelationalDecisionTreeClassifier.primitives
primitives = primitivessklink.tree.RelationalDecisionTreeClassifier.random_state
random_state = random_statesklink.tree.RelationalDecisionTreeClassifier.record_candidates
record_candidates = record_candidatessklink.tree.RelationalDecisionTreeClassifier.schema_
schema_: Schema | Nonesklink.tree.RelationalDecisionTreeClassifier.time
time = timesklink.tree.RelationalDecisionTreeRegressor
RelationalDecisionTreeRegressor(database: Database | None = None, *, entity: str | None = None, key: str | int | Sequence[str | int] | None = None, time: str | int | None = None, criterion: Literal['squared_error'] = 'squared_error', max_depth: int | None = None, min_samples_split: int | float = 2, min_samples_leaf: int | float = 1, min_weight_fraction_leaf: float = 0.0, max_features: int | float | Literal['sqrt', 'log2'] | None = None, max_leaf_nodes: int | None = None, min_impurity_decrease: float = 0.0, max_relationship_depth: int = 2, max_lookup_depth: int = 1, primitives: Literal['default'] | Sequence[str] = 'default', max_conditions: int = 2, condition_penalty: float = 0.0, max_search_samples: int | None = None, max_bins: int = 255, max_condition_bins: int = 32, max_categories: int = 32, record_candidates: int = 5, allow_reverse_paths: bool = False, handle_unknown_entity: Literal['error', 'empty'] = 'error', random_state: int | np.random.RandomState | None = None) -> NoneBases: RegressorMixin, BaseRelationalTree
Decision tree regressor whose questions can aggregate related tables.
Same questions and parameters as RelationalDecisionTreeClassifier without class_weight; the criterion is "squared_error".
Guides: Relational decision trees, Tune trees and forests
Parameters:
- database (
Database): Related tables.Nonegives a standard tree onX. - entity (
str): Table whose rows are the samples; required with a database. - key (
(str, int or sequence)): Column(s) ofXholding the entity key. - time (
str or int): Column ofXwith the cutoff of each sample. - criterion (
squared_error): Impurity measure. - max_depth (
int): Maximum depth of the tree. - min_samples_split (
int or float): Minimum number of samples to split a node. - min_samples_leaf (
int or float): Minimum number of samples in each leaf. - min_weight_fraction_leaf (
float): Minimum fraction of the total sample weight in each leaf. - max_features (
(int, float, {sqrt, log2} or None)): Number of candidate groups tried at each node. - max_leaf_nodes (
int): Grow best-first with at most this many leaves. - min_impurity_decrease (
float): A node is split only if the weighted impurity decrease reaches this. - max_relationship_depth (
int): Maximum number of relationship hops of a path. - max_lookup_depth (
int): Maximum number of lookups (many-to-one steps after the last table of a path) from the rows a path aggregates to the columns its conditions read, such asproportion(orders.order_items[products.category == 'toys']). These lookups start wheremax_relationship_depthstops and do not count as hops of it. The columns of the looked-up tables are also aggregated without conditions, such asmean(orders.order_items.products.price).0keeps conditions and aggregates on the last table of the path. A numeric column of a looked-up table getsmax(2, max_condition_bins // 4)candidate cuts. - primitives (
"default" or sequence of str): Primitives of the unconditioned aggregates. - max_conditions (
int): Conditions learned inside an aggregate: 0, 1 or 2. With 2, the second condition is searched for the best few first ones, such ascount(orders[amount > 100.0 & type == 'express']); 1 fits about twice as fast. - condition_penalty (
float): Gain each learned condition must pay before it is chosen: this value times the gain one condition makes by chance at the node (the node impurity for the Gini index and the squared error, a constant for the entropy, times the mean sample weight per row) and the log of the number of conditions its path offers. The best of many conditions gains by chance alone, so this Bonferroni-style correction keeps conditions that only fit noise out of small nodes; a question whose conditions do not pay for themselves is not asked. Improvements and importances stay the impurity decrease itself. Higher values prefer aggregates without conditions on small or noisy data;0disables it. - max_search_samples (
int or None): Samples on which a node searches its aggregates with learned conditions. A node with more samples searches them on this many, drawn at random once per tree, with the leaf limits scaled to that share, then scores the best few on all its samples, so that the condition search costs the same at any size of the data. Withrecord_candidates, such a node records only those few among the questions with learned conditions.Nonesearches on all samples. - max_bins (
int): Thresholds per base feature. - max_condition_bins (
int): Candidate cuts per numeric condition column before refinement; a quarter of it, at least 2, for a column of a looked-up table (seemax_lookup_depth). - max_categories (
int): Most frequent categories tried in==conditions. In regression and binary classification, a categorical column with more categories among the reachable rows also gets conditions on sets of categories: its categories are ranked once, infit, by the mean target of the training samples whose rows have them (shrunk towards the overall mean, so that rare categories rank in the middle), and a condition keeps the categories on one side of a cut of that ranking, such ascount(orders[merchant in ('m017', 'm203', ...)]). Categories that the rows of fewer than 5 training entities have are not ranked (an entity counts once, at any number of cutoffs and with any weight), so that a column of identifiers does not sort the samples by their own target. - record_candidates (
int): Number of best questions kept for each split node, the one it asks first, intree_.candidates.0keeps none. - allow_reverse_paths (
bool): Allow paths that read rows of other entities through shared tables. - handle_unknown_entity (
(error, empty)): What to do with keys that are not in the entity table. - random_state (
(int, RandomState or None)): Controls the sampling ofmax_featuresand the samples drawn formax_search_samples.
Attributes:
- tree_ (
RelationalTree): Fitted structure. - expressions_ (
tuple of Expression): Distinct questions used by the nodes. - feature_importances_ (
ndarray of shape (n_features_in_,)): Impurity-based importance per column ofX. - expression_importances_ (
dict): Importance per canonical expression name. - schema_ (
Schema or None): Part of the database schema the model reads. - visibility_ (
Visibility): Visibility rules used during fit. - categories_ (
dict): Category vocabulary of each categorical expression used. - bin_edges_ (
dict): Candidate thresholds of each numeric base expression used. - n_features_in_ (
int): Number of columns ofX. - feature_names_in_ (
ndarray of shape (n_features_in_,)): Column names ofXwhen it has them. - n_outputs_ (
int): Always 1.
See Also
sklink.tree.RelationalDecisionTreeClassifier : The same tree for class labels. sklink.ensemble.RelationalRandomForestRegressor : Averages many such trees grown on bootstrap samples. sklink.feature_extraction.RelationalFeaturizer : Relational features as columns, for any scikit-learn estimator. sklink.inspection.export_text : Print the rules of a fitted tree.
Notes
Categorical features split on sets of categories, and a category that fewer than 10 samples of the node have goes right, as described for RelationalDecisionTreeClassifier. With scikit-learn 1.9 or later, set_callbacks follows the fit node by node, as described there too.
Examples:
>>> from sklink.datasets import make_relational_regression
>>> from sklink.tree import RelationalDecisionTreeRegressor
>>> db, X, y = make_relational_regression(300, output="numpy", random_state=0)
>>> tree = RelationalDecisionTreeRegressor(
... db, entity="customers", key=0, max_depth=3
... ).fit(X, y)
>>> round(tree.score(X, y), 2)
0.99Functions:
- apply: Index of the leaf that each sample ends up in.
- decision_path: Nodes that each sample goes through.
- fit: Grow the tree.
- get_depth: Depth of the tree (a single leaf has depth 0).
- get_n_leaves: Return the number of leaves of the tree.
- predict: Mean target of the leaf of each sample.
sklink.tree.RelationalDecisionTreeRegressor.allow_reverse_paths
allow_reverse_paths = allow_reverse_pathssklink.tree.RelationalDecisionTreeRegressor.apply
apply(X: Any) -> npt.NDArray[np.int64]Index of the leaf that each sample ends up in.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- X_leaves (
ndarray of shape (n_samples,)): Node index of the leaf of each sample.
sklink.tree.RelationalDecisionTreeRegressor.condition_penalty
condition_penalty = condition_penaltysklink.tree.RelationalDecisionTreeRegressor.criterion
criterion = criterionsklink.tree.RelationalDecisionTreeRegressor.database
database = databasesklink.tree.RelationalDecisionTreeRegressor.decision_path
decision_path(X: Any) -> scipy.sparse.csr_arrayNodes that each sample goes through.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- indicator (
sparse array of shape (n_samples, n_nodes)): Nonzero entries mark the visited nodes.
sklink.tree.RelationalDecisionTreeRegressor.entity
entity = entitysklink.tree.RelationalDecisionTreeRegressor.fit
fit(X: Any, y: Any, sample_weight: Any = None) -> SelfGrow the tree.
With scikit-learn 1.9 or later, callbacks set with set_callbacks follow the fit: see RelationalDecisionTreeClassifier.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table: entity key, optional cutoff and sample features. - y (
array-like of shape (n_samples,)): Target values. - sample_weight (
array-like of shape (n_samples,)): Sample weights; a sample's weight does not depend on its number of related rows. Integer weights give the tree ofXwith rows repeated, bins included, and a row of weight zero is ignored as if it were not inX. Where the search counts samples (see Notes), weights count in units of their mean per distinct sample, so that scaling all of them changes nothing.
Returns:
- self (
RelationalDecisionTreeRegressor): Fitted estimator.
sklink.tree.RelationalDecisionTreeRegressor.get_depth
get_depth() -> intDepth of the tree (a single leaf has depth 0).
Returns:
- depth (
int): Maximum distance between the root and a leaf.
sklink.tree.RelationalDecisionTreeRegressor.get_n_leaves
get_n_leaves() -> intReturn the number of leaves of the tree.
Returns:
- n_leaves (
int): Number of leaves.
sklink.tree.RelationalDecisionTreeRegressor.handle_unknown_entity
handle_unknown_entity = handle_unknown_entitysklink.tree.RelationalDecisionTreeRegressor.key
key = keysklink.tree.RelationalDecisionTreeRegressor.max_bins
max_bins = max_binssklink.tree.RelationalDecisionTreeRegressor.max_categories
max_categories = max_categoriessklink.tree.RelationalDecisionTreeRegressor.max_condition_bins
max_condition_bins = max_condition_binssklink.tree.RelationalDecisionTreeRegressor.max_conditions
max_conditions = max_conditionssklink.tree.RelationalDecisionTreeRegressor.max_depth
max_depth = max_depthsklink.tree.RelationalDecisionTreeRegressor.max_features
max_features = max_featuressklink.tree.RelationalDecisionTreeRegressor.max_leaf_nodes
max_leaf_nodes = max_leaf_nodessklink.tree.RelationalDecisionTreeRegressor.max_lookup_depth
max_lookup_depth = max_lookup_depthsklink.tree.RelationalDecisionTreeRegressor.max_relationship_depth
max_relationship_depth = max_relationship_depthsklink.tree.RelationalDecisionTreeRegressor.max_search_samples
max_search_samples = max_search_samplessklink.tree.RelationalDecisionTreeRegressor.min_impurity_decrease
min_impurity_decrease = min_impurity_decreasesklink.tree.RelationalDecisionTreeRegressor.min_samples_leaf
min_samples_leaf = min_samples_leafsklink.tree.RelationalDecisionTreeRegressor.min_samples_split
min_samples_split = min_samples_splitsklink.tree.RelationalDecisionTreeRegressor.min_weight_fraction_leaf
min_weight_fraction_leaf = min_weight_fraction_leafsklink.tree.RelationalDecisionTreeRegressor.predict
predict(X: Any) -> np.ndarrayMean target of the leaf of each sample.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- y_pred (
ndarray of shape (n_samples,)): Predicted values.
sklink.tree.RelationalDecisionTreeRegressor.primitives
primitives = primitivessklink.tree.RelationalDecisionTreeRegressor.random_state
random_state = random_statesklink.tree.RelationalDecisionTreeRegressor.record_candidates
record_candidates = record_candidatessklink.tree.RelationalDecisionTreeRegressor.schema_
schema_: Schema | Nonesklink.tree.RelationalDecisionTreeRegressor.time
time = timesklink.tree.RelationalTree
RelationalTree(children_left: npt.NDArray[np.int64], children_right: npt.NDArray[np.int64], expression: npt.NDArray[np.int64], threshold: Array, is_categorical: npt.NDArray[np.bool_], categories_left: list[npt.NDArray[np.int64]], missing_go_to_left: npt.NDArray[np.bool_], impurity: Array, n_node_samples: npt.NDArray[np.int64], weighted_n_node_samples: Array, value: Array, improvement: Array, candidates: SplitCandidates | None = None) -> NoneFitted tree structure as parallel arrays, one entry per node.
expression[i] indexes the estimator's expressions_; leaves have children_left[i] == children_right[i] == -1. A sample goes left when the value is <= threshold[i] (numeric) or its category code is in categories_left[i] (categorical); missing values go left when missing_go_to_left[i]. value holds class fractions (classification) or the mean target (regression), with shape (node_count, 1, n_values).
Attributes:
- children_left, children_right (
ndarray of shape (node_count,)): Child node ids,-1for leaves. - expression (
ndarray of shape (node_count,)): Index inexpressions_of the question of each node,-2for leaves. - threshold (
ndarray of shape (node_count,)): Threshold of each numeric node; the first left category code of a categorical node and-2for leaves. - is_categorical (
ndarray of shape (node_count,)): Whether the question of each node is a category subset. - categories_left (
list of ndarray): Category codes that go left, per node (empty for numeric questions). - missing_go_to_left (
ndarray of shape (node_count,)): Side of the samples whose value is missing, per node. - impurity (
ndarray of shape (node_count,)): Impurity of each node. - n_node_samples (
ndarray of shape (node_count,)): Training samples with positive weight that reach each node. - weighted_n_node_samples (
ndarray of shape (node_count,)): Their total weight. - value (
ndarray of shape (node_count, 1, n_values)): Class fractions or mean target of each node. - improvement (
ndarray of shape (node_count,)): Weighted impurity decrease of the split of each node (0for leaves). - candidates (
SplitCandidates or None): Best questions scored at each split node, orNonewhen the tree was grown withrecord_candidates=0.
See Also
sklink.tree.SplitCandidates : The questions scored at each split node. sklink.inspection.export_dict : The same structure as a dictionary, with the canonical name of each question. sklink.plotting.TreeDisplay : Draw the tree node by node.
Functions:
- apply: Leaf of every sample.
- decision_path: Nodes visited by every sample.
- go_left: Which samples go to the left child of
node.
sklink.tree.RelationalTree.apply
apply(values: Array) -> npt.NDArray[np.int64]Leaf of every sample.
Parameters:
- values (
ndarray of shape (n_samples, n_expressions)):values[:, j]is expressionjofexpressions_.
Returns:
- leaves (
ndarray of shape (n_samples,)): Node id of the leaf of each sample.
sklink.tree.RelationalTree.candidates
candidates: SplitCandidates | None = Nonesklink.tree.RelationalTree.categories_left
categories_left: list[npt.NDArray[np.int64]]sklink.tree.RelationalTree.children_left
children_left: npt.NDArray[np.int64]sklink.tree.RelationalTree.children_right
children_right: npt.NDArray[np.int64]sklink.tree.RelationalTree.decision_path
decision_path(values: Array) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]Nodes visited by every sample.
Parameters:
- values (
ndarray of shape (n_samples, n_expressions)):values[:, j]is expressionjofexpressions_.
Returns:
samples, nodes : ndarray of shape (n_visits,): Visited(sample, node)pairs, sorted by sample then node.
sklink.tree.RelationalTree.expression
expression: npt.NDArray[np.int64]sklink.tree.RelationalTree.feature
feature: npt.NDArray[np.int64]Alias of expression, named as in scikit-learn's trees.
sklink.tree.RelationalTree.go_left
go_left(node: int, values: Array) -> npt.NDArray[np.bool_]Which samples go to the left child of node.
Parameters:
- node (
int): Id of a split node. - values (
ndarray of shape (n_samples,)): Value of the node's expression for each sample; categorical values are codes, missing values NaN.
Returns:
- left (
ndarray of shape (n_samples,)):Truefor the samples that go left.
sklink.tree.RelationalTree.improvement
improvement: Arraysklink.tree.RelationalTree.impurity
impurity: Arraysklink.tree.RelationalTree.is_categorical
is_categorical: npt.NDArray[np.bool_]sklink.tree.RelationalTree.max_depth
max_depth: intDepth of the deepest leaf (the root has depth 0).
sklink.tree.RelationalTree.missing_go_to_left
missing_go_to_left: npt.NDArray[np.bool_]sklink.tree.RelationalTree.n_leaves
n_leaves: intNumber of leaves.
sklink.tree.RelationalTree.n_node_samples
n_node_samples: npt.NDArray[np.int64]sklink.tree.RelationalTree.node_count
node_count: intNumber of nodes.
sklink.tree.RelationalTree.threshold
threshold: Arraysklink.tree.RelationalTree.value
value: Arraysklink.tree.RelationalTree.weighted_n_node_samples
weighted_n_node_samples: Arraysklink.tree.SplitCandidates
SplitCandidates(offsets: npt.NDArray[np.int64], expression: npt.NDArray[np.int64], is_categorical: npt.NDArray[np.bool_], threshold: Array, category_offsets: npt.NDArray[np.int64], category_codes: npt.NDArray[np.int64], missing_go_to_left: npt.NDArray[np.bool_], improvement: Array, refined: npt.NDArray[np.bool_], names: tuple[str, ...], vocabularies: tuple[np.ndarray | None, ...]) -> NoneBest questions scored at the split nodes of a tree, the chosen one first.
The candidates of node i are entries offsets[i] to offsets[i + 1] - 1 of the per-candidate arrays; a leaf has none. The first entry of a split node is the question the node asks, with exactly its threshold or categories, missing side and improvement; the others follow by decreasing improvement. With condition_penalty, the node asks the best question net of the cost of its conditions, so another may show a larger improvement. No two entries of a node ask the same question (same expression and threshold or categories). The table pickles compressed, so that it adds little to the size of a saved tree.
Attributes:
- offsets (
ndarray of shape (node_count + 1,)): Start of the candidates of each node in the per-candidate arrays. - expression (
ndarray of shape (n_candidates,)): Index innamesof the question of each candidate. - is_categorical (
ndarray of shape (n_candidates,)): Whether the candidate is a category subset. - threshold (
ndarray of shape (n_candidates,)): Numeric threshold (go left whenvalue <= threshold); NaN for categorical candidates. - category_offsets (
ndarray of shape (n_candidates + 1,)): Start of the left category codes of each candidate incategory_codes(none for numeric candidates). - category_codes (
ndarray of shape (n_codes,)): Left category codes, intovocabularies[expression[j]]. - missing_go_to_left (
ndarray of shape (n_candidates,)): Side of the missing values. For the chosen question it is the side the node uses; for the others, the side found while scoring them. - improvement (
ndarray of shape (n_candidates,)): Weighted impurity decrease, on the scale ofRelationalTree.improvement. - refined (
ndarray of shape (n_candidates,)): Whether the gain comes from the refinement step, which moves the conditions of an aggregate and its threshold to their exact best cuts.Falsefor questions scored only in the first, binned pass. - names (
tuple of str): Canonical names of the distinct questions of the candidates;expressionindexes it. Names, not expression objects, keep the table small;sklink.expressions.parsereads a relational one back, and a name that is a column ofXis that column. - vocabularies (
tuple of ndarray or None): Category labels of each entry ofnames(Noneif numeric).
See Also
sklink.tree.RelationalTree : The fitted structure that holds this table in candidates. sklink.plotting.SearchDisplay : Draw the questions scored at one node.
Functions:
- categories: Left category codes of candidate
j(empty for numeric ones). - of_node: Positions of the candidates of
nodein the per-candidate arrays.
sklink.tree.SplitCandidates.categories
categories(j: int) -> npt.NDArray[np.int64]Left category codes of candidate j (empty for numeric ones).
Parameters:
- j (
int): Position of the candidate.
Returns:
- codes (
ndarray of int): Codes intovocabularies[expression[j]].
sklink.tree.SplitCandidates.category_codes
category_codes: npt.NDArray[np.int64]sklink.tree.SplitCandidates.category_offsets
category_offsets: npt.NDArray[np.int64]sklink.tree.SplitCandidates.expression
expression: npt.NDArray[np.int64]sklink.tree.SplitCandidates.improvement
improvement: Arraysklink.tree.SplitCandidates.is_categorical
is_categorical: npt.NDArray[np.bool_]sklink.tree.SplitCandidates.missing_go_to_left
missing_go_to_left: npt.NDArray[np.bool_]sklink.tree.SplitCandidates.names
names: tuple[str, ...]sklink.tree.SplitCandidates.of_node
of_node(node: int) -> rangePositions of the candidates of node in the per-candidate arrays.
Parameters:
- node (
int): Node id.
Returns:
- positions (
range): Empty for leaves.
sklink.tree.SplitCandidates.offsets
offsets: npt.NDArray[np.int64]sklink.tree.SplitCandidates.refined
refined: npt.NDArray[np.bool_]sklink.tree.SplitCandidates.threshold
threshold: Arraysklink.tree.SplitCandidates.vocabularies
vocabularies: tuple[np.ndarray | None, ...]