---
url: /dev/api/sklink.tree.md
description: >-
  API reference of sklink.tree. Decision trees that ask about aggregates of
  related tables.
---

::: v-pre

# `sklink.tree` {#sklink.tree}

Decision trees that ask about aggregates of related tables.

**Classes:**

* [**RelationalDecisionTreeClassifier**](#sklink.tree.RelationalDecisionTreeClassifier): Decision tree classifier whose questions can aggregate related tables.
* [**RelationalDecisionTreeRegressor**](#sklink.tree.RelationalDecisionTreeRegressor): Decision tree regressor whose questions can aggregate related tables.
* [**RelationalTree**](#sklink.tree.RelationalTree): Fitted tree structure as parallel arrays, one entry per node.
* [**SplitCandidates**](#sklink.tree.SplitCandidates): Best questions scored at the split nodes of a tree, the chosen one first.

## `sklink.tree.RelationalDecisionTreeClassifier` {#sklink.tree.RelationalDecisionTreeClassifier}

```python
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) -> None
```

Bases: [ClassifierMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.ClassifierMixin.html), 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](../tutorials/relational-decision-trees), [Tune trees and forests](../guides/tune-trees-and-forests)

**Parameters:**

* **database** ([Database](./sklink.database#sklink.database.Database)): Related tables. `None` gives a standard tree on `X`.
* **entity** ([str](https://docs.python.org/3/library/stdtypes.html#str)): Table whose rows are the samples; required with a database.
* **key** (([str](https://docs.python.org/3/library/stdtypes.html#str), [int](https://docs.python.org/3/library/functions.html#int) or sequence)): Column(s) of `X` holding the entity key.
* **time** ([str](https://docs.python.org/3/library/stdtypes.html#str) or [int](https://docs.python.org/3/library/functions.html#int)): Column of `X` with the cutoff of each sample. `None` is the static
  mode: every related row is visible.
* **criterion** ((gini, entropy, log_loss)): Impurity measure, as in scikit-learn.
* **max_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum depth of the tree.
* **min_samples_split** ([int](https://docs.python.org/3/library/functions.html#int) or [float](https://docs.python.org/3/library/functions.html#float)): Minimum number of samples to split a node.
* **min_samples_leaf** ([int](https://docs.python.org/3/library/functions.html#int) or [float](https://docs.python.org/3/library/functions.html#float)): Minimum number of samples in each leaf.
* **min_weight_fraction_leaf** ([float](https://docs.python.org/3/library/functions.html#float)): Minimum fraction of the total sample weight in each leaf.
* **max_features** (([int](https://docs.python.org/3/library/functions.html#int), [float](https://docs.python.org/3/library/functions.html#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](https://docs.python.org/3/library/functions.html#int)): Grow best-first with at most this many leaves.
* **min_impurity_decrease** ([float](https://docs.python.org/3/library/functions.html#float)): A node is split only if the weighted impurity decrease reaches this.
* **class_weight** (([dict](https://docs.python.org/3/library/stdtypes.html#dict), balanced or None)): Weights of the classes, as in scikit-learn.
* **max_relationship_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum number of relationship hops of a path.
* **max_lookup_depth** ([int](https://docs.python.org/3/library/functions.html#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 as
  `proportion(orders.order_items[products.category == 'toys'])`. These
  lookups start where `max_relationship_depth` stops and do not count as
  hops of it. The columns of the looked-up tables are also aggregated without
  conditions, such as `mean(orders.order_items.products.price)`. `0` keeps
  conditions and aggregates on the last table of the path. A numeric column of
  a looked-up table gets `max(2, max_condition_bins // 4)` candidate cuts.
* **primitives** ("default" or sequence of str): Primitives of the unconditioned aggregates.
* **max_conditions** ([int](https://docs.python.org/3/library/functions.html#int)): Conditions learned inside an aggregate: 0, 1 or 2. With 2, the second
  condition is searched for the best few first ones, such as
  `count(orders[amount > 100.0 & type == 'express'])`; 1 fits about
  twice as fast.
* **condition_penalty** ([float](https://docs.python.org/3/library/functions.html#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; `0` disables it.
* **max_search_samples** ([int](https://docs.python.org/3/library/functions.html#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. With
  `record_candidates`, such a node records only those few among the
  questions with learned conditions. `None` searches on all samples.
* **max_bins** ([int](https://docs.python.org/3/library/functions.html#int)): Thresholds per base feature, as quantiles of the training samples.
* **max_condition_bins** ([int](https://docs.python.org/3/library/functions.html#int)): Candidate cuts per numeric condition column before refinement; a
  quarter of it, at least 2, for a column of a looked-up table (see
  `max_lookup_depth`).
* **max_categories** ([int](https://docs.python.org/3/library/functions.html#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, in `fit`, 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 as
  `count(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](https://docs.python.org/3/library/functions.html#int)): Number of best questions kept for each split node, the one it asks
  first, in `tree_.candidates`; [`sklink.inspection.export_dict`](./sklink.inspection#sklink.inspection.export_dict)
  lists them. `0` keeps none and leaves `tree_.candidates` at
  `None`.
* **allow_reverse_paths** ([bool](https://docs.python.org/3/library/functions.html#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](https://docs.python.org/3/library/functions.html#int), RandomState or None)): Controls the sampling of `max_features` and the samples drawn for
  `max_search_samples`.

**Attributes:**

* **tree\_** ([RelationalTree](#sklink.tree.RelationalTree)): Fitted structure.
* **expressions\_** (tuple of Expression): Distinct questions used by the nodes; `tree_.expression` indexes it.
* **classes\_** (ndarray of shape (n_classes,)): Class labels.
* **n\_classes\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of classes.
* **feature_importances\_** (ndarray of shape (n_features_in\_,)): Impurity-based importance per column of `X`; questions that are not
  columns of `X` count for the key column.
* **expression_importances\_** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Importance per canonical expression name.
* [**schema\_**](#sklink.tree.RelationalDecisionTreeClassifier.schema_) ([Schema](./sklink.database#sklink.database.Schema) or None): Part of the database schema the model reads.
* **visibility\_** ([Visibility](./sklink.engine#sklink.engine.Visibility)): Visibility rules used during fit.
* **categories\_** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Category vocabulary of each categorical expression used.
* **bin_edges\_** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Candidate thresholds of each numeric base expression used.
* **n\_features_in\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of columns of `X`.
* **feature_names_in\_** (ndarray of shape (n_features_in\_,)): Column names of `X` when it has them.
* **n\_outputs\_** ([int](https://docs.python.org/3/library/functions.html#int)): Always 1.

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.

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`](https://scikit-learn.org/stable/modules/generated/sklearn.callback.ProgressBar.html). 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:**

```pycon
>>> 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.0
```

**Functions:**

* [**apply**](#sklink.tree.RelationalDecisionTreeClassifier.apply): Index of the leaf that each sample ends up in.
* [**decision_path**](#sklink.tree.RelationalDecisionTreeClassifier.decision_path): Nodes that each sample goes through.
* [**fit**](#sklink.tree.RelationalDecisionTreeClassifier.fit): Grow the tree.
* [**get_depth**](#sklink.tree.RelationalDecisionTreeClassifier.get_depth): Depth of the tree (a single leaf has depth 0).
* [**get_n_leaves**](#sklink.tree.RelationalDecisionTreeClassifier.get_n_leaves): Return the number of leaves of the tree.
* [**predict**](#sklink.tree.RelationalDecisionTreeClassifier.predict): Most probable class of each sample.
* [**predict_log_proba**](#sklink.tree.RelationalDecisionTreeClassifier.predict_log_proba): Logarithm of `predict_proba`.
* [**predict_proba**](#sklink.tree.RelationalDecisionTreeClassifier.predict_proba): Class probabilities: weighted class fractions of the leaf.

### `sklink.tree.RelationalDecisionTreeClassifier.allow_reverse_paths` {#sklink.tree.RelationalDecisionTreeClassifier.allow_reverse_paths}

```python
allow_reverse_paths = allow_reverse_paths
```

### `sklink.tree.RelationalDecisionTreeClassifier.apply` {#sklink.tree.RelationalDecisionTreeClassifier.apply}

```python
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 in `fit`.

**Returns:**

* **X\_leaves** (ndarray of shape (n_samples,)): Node index of the leaf of each sample.

### `sklink.tree.RelationalDecisionTreeClassifier.class_weight` {#sklink.tree.RelationalDecisionTreeClassifier.class_weight}

```python
class_weight = class_weight
```

### `sklink.tree.RelationalDecisionTreeClassifier.condition_penalty` {#sklink.tree.RelationalDecisionTreeClassifier.condition_penalty}

```python
condition_penalty = condition_penalty
```

### `sklink.tree.RelationalDecisionTreeClassifier.criterion` {#sklink.tree.RelationalDecisionTreeClassifier.criterion}

```python
criterion = criterion
```

### `sklink.tree.RelationalDecisionTreeClassifier.database` {#sklink.tree.RelationalDecisionTreeClassifier.database}

```python
database = database
```

### `sklink.tree.RelationalDecisionTreeClassifier.decision_path` {#sklink.tree.RelationalDecisionTreeClassifier.decision_path}

```python
decision_path(X: Any) -> scipy.sparse.csr_array
```

Nodes that each sample goes through.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as in `fit`.

**Returns:**

* **indicator** (sparse array of shape (n_samples, n_nodes)): Nonzero entries mark the visited nodes.

### `sklink.tree.RelationalDecisionTreeClassifier.entity` {#sklink.tree.RelationalDecisionTreeClassifier.entity}

```python
entity = entity
```

### `sklink.tree.RelationalDecisionTreeClassifier.fit` {#sklink.tree.RelationalDecisionTreeClassifier.fit}

```python
fit(X: Any, y: Any, sample_weight: Any = None) -> Self
```

Grow 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 of `X` with rows
  repeated, bins included, and a row of weight zero is ignored as if
  it were not in `X`. 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](#sklink.tree.RelationalDecisionTreeClassifier)): Fitted estimator.

### `sklink.tree.RelationalDecisionTreeClassifier.get_depth` {#sklink.tree.RelationalDecisionTreeClassifier.get_depth}

```python
get_depth() -> int
```

Depth of the tree (a single leaf has depth 0).

**Returns:**

* **depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum distance between the root and a leaf.

### `sklink.tree.RelationalDecisionTreeClassifier.get_n_leaves` {#sklink.tree.RelationalDecisionTreeClassifier.get_n_leaves}

```python
get_n_leaves() -> int
```

Return the number of leaves of the tree.

**Returns:**

* **n\_leaves** ([int](https://docs.python.org/3/library/functions.html#int)): Number of leaves.

### `sklink.tree.RelationalDecisionTreeClassifier.handle_unknown_entity` {#sklink.tree.RelationalDecisionTreeClassifier.handle_unknown_entity}

```python
handle_unknown_entity = handle_unknown_entity
```

### `sklink.tree.RelationalDecisionTreeClassifier.key` {#sklink.tree.RelationalDecisionTreeClassifier.key}

```python
key = key
```

### `sklink.tree.RelationalDecisionTreeClassifier.max_bins` {#sklink.tree.RelationalDecisionTreeClassifier.max_bins}

```python
max_bins = max_bins
```

### `sklink.tree.RelationalDecisionTreeClassifier.max_categories` {#sklink.tree.RelationalDecisionTreeClassifier.max_categories}

```python
max_categories = max_categories
```

### `sklink.tree.RelationalDecisionTreeClassifier.max_condition_bins` {#sklink.tree.RelationalDecisionTreeClassifier.max_condition_bins}

```python
max_condition_bins = max_condition_bins
```

### `sklink.tree.RelationalDecisionTreeClassifier.max_conditions` {#sklink.tree.RelationalDecisionTreeClassifier.max_conditions}

```python
max_conditions = max_conditions
```

### `sklink.tree.RelationalDecisionTreeClassifier.max_depth` {#sklink.tree.RelationalDecisionTreeClassifier.max_depth}

```python
max_depth = max_depth
```

### `sklink.tree.RelationalDecisionTreeClassifier.max_features` {#sklink.tree.RelationalDecisionTreeClassifier.max_features}

```python
max_features = max_features
```

### `sklink.tree.RelationalDecisionTreeClassifier.max_leaf_nodes` {#sklink.tree.RelationalDecisionTreeClassifier.max_leaf_nodes}

```python
max_leaf_nodes = max_leaf_nodes
```

### `sklink.tree.RelationalDecisionTreeClassifier.max_lookup_depth` {#sklink.tree.RelationalDecisionTreeClassifier.max_lookup_depth}

```python
max_lookup_depth = max_lookup_depth
```

### `sklink.tree.RelationalDecisionTreeClassifier.max_relationship_depth` {#sklink.tree.RelationalDecisionTreeClassifier.max_relationship_depth}

```python
max_relationship_depth = max_relationship_depth
```

### `sklink.tree.RelationalDecisionTreeClassifier.max_search_samples` {#sklink.tree.RelationalDecisionTreeClassifier.max_search_samples}

```python
max_search_samples = max_search_samples
```

### `sklink.tree.RelationalDecisionTreeClassifier.min_impurity_decrease` {#sklink.tree.RelationalDecisionTreeClassifier.min_impurity_decrease}

```python
min_impurity_decrease = min_impurity_decrease
```

### `sklink.tree.RelationalDecisionTreeClassifier.min_samples_leaf` {#sklink.tree.RelationalDecisionTreeClassifier.min_samples_leaf}

```python
min_samples_leaf = min_samples_leaf
```

### `sklink.tree.RelationalDecisionTreeClassifier.min_samples_split` {#sklink.tree.RelationalDecisionTreeClassifier.min_samples_split}

```python
min_samples_split = min_samples_split
```

### `sklink.tree.RelationalDecisionTreeClassifier.min_weight_fraction_leaf` {#sklink.tree.RelationalDecisionTreeClassifier.min_weight_fraction_leaf}

```python
min_weight_fraction_leaf = min_weight_fraction_leaf
```

### `sklink.tree.RelationalDecisionTreeClassifier.predict` {#sklink.tree.RelationalDecisionTreeClassifier.predict}

```python
predict(X: Any) -> np.ndarray
```

Most probable class of each sample.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as in `fit`.

**Returns:**

* **y\_pred** (ndarray of shape (n_samples,)): Predicted labels.

### `sklink.tree.RelationalDecisionTreeClassifier.predict_log_proba` {#sklink.tree.RelationalDecisionTreeClassifier.predict_log_proba}

```python
predict_log_proba(X: Any) -> np.ndarray
```

Logarithm of `predict_proba`.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as in `fit`.

**Returns:**

* **log_proba** (ndarray of shape (n_samples, n_classes)): Columns in the order of `classes_`.

### `sklink.tree.RelationalDecisionTreeClassifier.predict_proba` {#sklink.tree.RelationalDecisionTreeClassifier.predict_proba}

```python
predict_proba(X: Any) -> np.ndarray
```

Class 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 in `fit`.

**Returns:**

* **proba** (ndarray of shape (n_samples, n_classes)): Columns in the order of `classes_`.

### `sklink.tree.RelationalDecisionTreeClassifier.primitives` {#sklink.tree.RelationalDecisionTreeClassifier.primitives}

```python
primitives = primitives
```

### `sklink.tree.RelationalDecisionTreeClassifier.random_state` {#sklink.tree.RelationalDecisionTreeClassifier.random_state}

```python
random_state = random_state
```

### `sklink.tree.RelationalDecisionTreeClassifier.record_candidates` {#sklink.tree.RelationalDecisionTreeClassifier.record_candidates}

```python
record_candidates = record_candidates
```

### `sklink.tree.RelationalDecisionTreeClassifier.schema_` {#sklink.tree.RelationalDecisionTreeClassifier.schema\_}

```python
schema_: Schema | None
```

### `sklink.tree.RelationalDecisionTreeClassifier.time` {#sklink.tree.RelationalDecisionTreeClassifier.time}

```python
time = time
```

## `sklink.tree.RelationalDecisionTreeRegressor` {#sklink.tree.RelationalDecisionTreeRegressor}

```python
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) -> None
```

Bases: [RegressorMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.RegressorMixin.html), 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](../tutorials/relational-decision-trees), [Tune trees and forests](../guides/tune-trees-and-forests)

**Parameters:**

* **database** ([Database](./sklink.database#sklink.database.Database)): Related tables. `None` gives a standard tree on `X`.
* **entity** ([str](https://docs.python.org/3/library/stdtypes.html#str)): Table whose rows are the samples; required with a database.
* **key** (([str](https://docs.python.org/3/library/stdtypes.html#str), [int](https://docs.python.org/3/library/functions.html#int) or sequence)): Column(s) of `X` holding the entity key.
* **time** ([str](https://docs.python.org/3/library/stdtypes.html#str) or [int](https://docs.python.org/3/library/functions.html#int)): Column of `X` with the cutoff of each sample.
* **criterion** (squared_error): Impurity measure.
* **max_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum depth of the tree.
* **min_samples_split** ([int](https://docs.python.org/3/library/functions.html#int) or [float](https://docs.python.org/3/library/functions.html#float)): Minimum number of samples to split a node.
* **min_samples_leaf** ([int](https://docs.python.org/3/library/functions.html#int) or [float](https://docs.python.org/3/library/functions.html#float)): Minimum number of samples in each leaf.
* **min_weight_fraction_leaf** ([float](https://docs.python.org/3/library/functions.html#float)): Minimum fraction of the total sample weight in each leaf.
* **max_features** (([int](https://docs.python.org/3/library/functions.html#int), [float](https://docs.python.org/3/library/functions.html#float), {sqrt, log2} or None)): Number of candidate groups tried at each node.
* **max_leaf_nodes** ([int](https://docs.python.org/3/library/functions.html#int)): Grow best-first with at most this many leaves.
* **min_impurity_decrease** ([float](https://docs.python.org/3/library/functions.html#float)): A node is split only if the weighted impurity decrease reaches this.
* **max_relationship_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum number of relationship hops of a path.
* **max_lookup_depth** ([int](https://docs.python.org/3/library/functions.html#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 as
  `proportion(orders.order_items[products.category == 'toys'])`. These
  lookups start where `max_relationship_depth` stops and do not count as
  hops of it. The columns of the looked-up tables are also aggregated without
  conditions, such as `mean(orders.order_items.products.price)`. `0` keeps
  conditions and aggregates on the last table of the path. A numeric column of
  a looked-up table gets `max(2, max_condition_bins // 4)` candidate cuts.
* **primitives** ("default" or sequence of str): Primitives of the unconditioned aggregates.
* **max_conditions** ([int](https://docs.python.org/3/library/functions.html#int)): Conditions learned inside an aggregate: 0, 1 or 2. With 2, the second
  condition is searched for the best few first ones, such as
  `count(orders[amount > 100.0 & type == 'express'])`; 1 fits about
  twice as fast.
* **condition_penalty** ([float](https://docs.python.org/3/library/functions.html#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; `0` disables it.
* **max_search_samples** ([int](https://docs.python.org/3/library/functions.html#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. With
  `record_candidates`, such a node records only those few among the
  questions with learned conditions. `None` searches on all samples.
* **max_bins** ([int](https://docs.python.org/3/library/functions.html#int)): Thresholds per base feature.
* **max_condition_bins** ([int](https://docs.python.org/3/library/functions.html#int)): Candidate cuts per numeric condition column before refinement; a
  quarter of it, at least 2, for a column of a looked-up table (see
  `max_lookup_depth`).
* **max_categories** ([int](https://docs.python.org/3/library/functions.html#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, in `fit`, 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 as
  `count(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](https://docs.python.org/3/library/functions.html#int)): Number of best questions kept for each split node, the one it asks
  first, in `tree_.candidates`. `0` keeps none.
* **allow_reverse_paths** ([bool](https://docs.python.org/3/library/functions.html#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](https://docs.python.org/3/library/functions.html#int), RandomState or None)): Controls the sampling of `max_features` and the samples drawn for
  `max_search_samples`.

**Attributes:**

* **tree\_** ([RelationalTree](#sklink.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 of `X`.
* **expression_importances\_** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Importance per canonical expression name.
* [**schema\_**](#sklink.tree.RelationalDecisionTreeRegressor.schema_) ([Schema](./sklink.database#sklink.database.Schema) or None): Part of the database schema the model reads.
* **visibility\_** ([Visibility](./sklink.engine#sklink.engine.Visibility)): Visibility rules used during fit.
* **categories\_** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Category vocabulary of each categorical expression used.
* **bin_edges\_** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Candidate thresholds of each numeric base expression used.
* **n\_features_in\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of columns of `X`.
* **feature_names_in\_** (ndarray of shape (n_features_in\_,)): Column names of `X` when it has them.
* **n\_outputs\_** ([int](https://docs.python.org/3/library/functions.html#int)): Always 1.

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.

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:**

```pycon
>>> 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.99
```

**Functions:**

* [**apply**](#sklink.tree.RelationalDecisionTreeRegressor.apply): Index of the leaf that each sample ends up in.
* [**decision_path**](#sklink.tree.RelationalDecisionTreeRegressor.decision_path): Nodes that each sample goes through.
* [**fit**](#sklink.tree.RelationalDecisionTreeRegressor.fit): Grow the tree.
* [**get_depth**](#sklink.tree.RelationalDecisionTreeRegressor.get_depth): Depth of the tree (a single leaf has depth 0).
* [**get_n_leaves**](#sklink.tree.RelationalDecisionTreeRegressor.get_n_leaves): Return the number of leaves of the tree.
* [**predict**](#sklink.tree.RelationalDecisionTreeRegressor.predict): Mean target of the leaf of each sample.

### `sklink.tree.RelationalDecisionTreeRegressor.allow_reverse_paths` {#sklink.tree.RelationalDecisionTreeRegressor.allow_reverse_paths}

```python
allow_reverse_paths = allow_reverse_paths
```

### `sklink.tree.RelationalDecisionTreeRegressor.apply` {#sklink.tree.RelationalDecisionTreeRegressor.apply}

```python
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 in `fit`.

**Returns:**

* **X\_leaves** (ndarray of shape (n_samples,)): Node index of the leaf of each sample.

### `sklink.tree.RelationalDecisionTreeRegressor.condition_penalty` {#sklink.tree.RelationalDecisionTreeRegressor.condition_penalty}

```python
condition_penalty = condition_penalty
```

### `sklink.tree.RelationalDecisionTreeRegressor.criterion` {#sklink.tree.RelationalDecisionTreeRegressor.criterion}

```python
criterion = criterion
```

### `sklink.tree.RelationalDecisionTreeRegressor.database` {#sklink.tree.RelationalDecisionTreeRegressor.database}

```python
database = database
```

### `sklink.tree.RelationalDecisionTreeRegressor.decision_path` {#sklink.tree.RelationalDecisionTreeRegressor.decision_path}

```python
decision_path(X: Any) -> scipy.sparse.csr_array
```

Nodes that each sample goes through.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as in `fit`.

**Returns:**

* **indicator** (sparse array of shape (n_samples, n_nodes)): Nonzero entries mark the visited nodes.

### `sklink.tree.RelationalDecisionTreeRegressor.entity` {#sklink.tree.RelationalDecisionTreeRegressor.entity}

```python
entity = entity
```

### `sklink.tree.RelationalDecisionTreeRegressor.fit` {#sklink.tree.RelationalDecisionTreeRegressor.fit}

```python
fit(X: Any, y: Any, sample_weight: Any = None) -> Self
```

Grow 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 of `X` with rows
  repeated, bins included, and a row of weight zero is ignored as if
  it were not in `X`. 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](#sklink.tree.RelationalDecisionTreeRegressor)): Fitted estimator.

### `sklink.tree.RelationalDecisionTreeRegressor.get_depth` {#sklink.tree.RelationalDecisionTreeRegressor.get_depth}

```python
get_depth() -> int
```

Depth of the tree (a single leaf has depth 0).

**Returns:**

* **depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum distance between the root and a leaf.

### `sklink.tree.RelationalDecisionTreeRegressor.get_n_leaves` {#sklink.tree.RelationalDecisionTreeRegressor.get_n_leaves}

```python
get_n_leaves() -> int
```

Return the number of leaves of the tree.

**Returns:**

* **n\_leaves** ([int](https://docs.python.org/3/library/functions.html#int)): Number of leaves.

### `sklink.tree.RelationalDecisionTreeRegressor.handle_unknown_entity` {#sklink.tree.RelationalDecisionTreeRegressor.handle_unknown_entity}

```python
handle_unknown_entity = handle_unknown_entity
```

### `sklink.tree.RelationalDecisionTreeRegressor.key` {#sklink.tree.RelationalDecisionTreeRegressor.key}

```python
key = key
```

### `sklink.tree.RelationalDecisionTreeRegressor.max_bins` {#sklink.tree.RelationalDecisionTreeRegressor.max_bins}

```python
max_bins = max_bins
```

### `sklink.tree.RelationalDecisionTreeRegressor.max_categories` {#sklink.tree.RelationalDecisionTreeRegressor.max_categories}

```python
max_categories = max_categories
```

### `sklink.tree.RelationalDecisionTreeRegressor.max_condition_bins` {#sklink.tree.RelationalDecisionTreeRegressor.max_condition_bins}

```python
max_condition_bins = max_condition_bins
```

### `sklink.tree.RelationalDecisionTreeRegressor.max_conditions` {#sklink.tree.RelationalDecisionTreeRegressor.max_conditions}

```python
max_conditions = max_conditions
```

### `sklink.tree.RelationalDecisionTreeRegressor.max_depth` {#sklink.tree.RelationalDecisionTreeRegressor.max_depth}

```python
max_depth = max_depth
```

### `sklink.tree.RelationalDecisionTreeRegressor.max_features` {#sklink.tree.RelationalDecisionTreeRegressor.max_features}

```python
max_features = max_features
```

### `sklink.tree.RelationalDecisionTreeRegressor.max_leaf_nodes` {#sklink.tree.RelationalDecisionTreeRegressor.max_leaf_nodes}

```python
max_leaf_nodes = max_leaf_nodes
```

### `sklink.tree.RelationalDecisionTreeRegressor.max_lookup_depth` {#sklink.tree.RelationalDecisionTreeRegressor.max_lookup_depth}

```python
max_lookup_depth = max_lookup_depth
```

### `sklink.tree.RelationalDecisionTreeRegressor.max_relationship_depth` {#sklink.tree.RelationalDecisionTreeRegressor.max_relationship_depth}

```python
max_relationship_depth = max_relationship_depth
```

### `sklink.tree.RelationalDecisionTreeRegressor.max_search_samples` {#sklink.tree.RelationalDecisionTreeRegressor.max_search_samples}

```python
max_search_samples = max_search_samples
```

### `sklink.tree.RelationalDecisionTreeRegressor.min_impurity_decrease` {#sklink.tree.RelationalDecisionTreeRegressor.min_impurity_decrease}

```python
min_impurity_decrease = min_impurity_decrease
```

### `sklink.tree.RelationalDecisionTreeRegressor.min_samples_leaf` {#sklink.tree.RelationalDecisionTreeRegressor.min_samples_leaf}

```python
min_samples_leaf = min_samples_leaf
```

### `sklink.tree.RelationalDecisionTreeRegressor.min_samples_split` {#sklink.tree.RelationalDecisionTreeRegressor.min_samples_split}

```python
min_samples_split = min_samples_split
```

### `sklink.tree.RelationalDecisionTreeRegressor.min_weight_fraction_leaf` {#sklink.tree.RelationalDecisionTreeRegressor.min_weight_fraction_leaf}

```python
min_weight_fraction_leaf = min_weight_fraction_leaf
```

### `sklink.tree.RelationalDecisionTreeRegressor.predict` {#sklink.tree.RelationalDecisionTreeRegressor.predict}

```python
predict(X: Any) -> np.ndarray
```

Mean 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 in `fit`.

**Returns:**

* **y\_pred** (ndarray of shape (n_samples,)): Predicted values.

### `sklink.tree.RelationalDecisionTreeRegressor.primitives` {#sklink.tree.RelationalDecisionTreeRegressor.primitives}

```python
primitives = primitives
```

### `sklink.tree.RelationalDecisionTreeRegressor.random_state` {#sklink.tree.RelationalDecisionTreeRegressor.random_state}

```python
random_state = random_state
```

### `sklink.tree.RelationalDecisionTreeRegressor.record_candidates` {#sklink.tree.RelationalDecisionTreeRegressor.record_candidates}

```python
record_candidates = record_candidates
```

### `sklink.tree.RelationalDecisionTreeRegressor.schema_` {#sklink.tree.RelationalDecisionTreeRegressor.schema\_}

```python
schema_: Schema | None
```

### `sklink.tree.RelationalDecisionTreeRegressor.time` {#sklink.tree.RelationalDecisionTreeRegressor.time}

```python
time = time
```

## `sklink.tree.RelationalTree` {#sklink.tree.RelationalTree}

```python
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) -> None
```

Fitted 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, `-1` for leaves.
* [**expression**](#sklink.tree.RelationalTree.expression) (ndarray of shape (node_count,)): Index in `expressions_` of the question of each node, `-2` for
  leaves.
* [**threshold**](#sklink.tree.RelationalTree.threshold) (ndarray of shape (node_count,)): Threshold of each numeric node; the first left category code of a
  categorical node and `-2` for leaves.
* [**is_categorical**](#sklink.tree.RelationalTree.is_categorical) (ndarray of shape (node_count,)): Whether the question of each node is a category subset.
* [**categories_left**](#sklink.tree.RelationalTree.categories_left) (list of ndarray): Category codes that go left, per node (empty for numeric questions).
* [**missing_go_to_left**](#sklink.tree.RelationalTree.missing_go_to_left) (ndarray of shape (node_count,)): Side of the samples whose value is missing, per node.
* [**impurity**](#sklink.tree.RelationalTree.impurity) (ndarray of shape (node_count,)): Impurity of each node.
* [**n\_node_samples**](#sklink.tree.RelationalTree.n_node_samples) (ndarray of shape (node_count,)): Training samples with positive weight that reach each node.
* [**weighted_n_node_samples**](#sklink.tree.RelationalTree.weighted_n_node_samples) (ndarray of shape (node_count,)): Their total weight.
* [**value**](#sklink.tree.RelationalTree.value) (ndarray of shape (node_count, 1, n_values)): Class fractions or mean target of each node.
* [**improvement**](#sklink.tree.RelationalTree.improvement) (ndarray of shape (node_count,)): Weighted impurity decrease of the split of each node (`0` for leaves).
* [**candidates**](#sklink.tree.RelationalTree.candidates) ([SplitCandidates](#sklink.tree.SplitCandidates) or None): Best questions scored at each split node, or `None` when the tree
  was grown with `record_candidates=0`.

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**](#sklink.tree.RelationalTree.apply): Leaf of every sample.
* [**decision_path**](#sklink.tree.RelationalTree.decision_path): Nodes visited by every sample.
* [**go_left**](#sklink.tree.RelationalTree.go_left): Which samples go to the left child of `node`.

### `sklink.tree.RelationalTree.apply` {#sklink.tree.RelationalTree.apply}

```python
apply(values: Array) -> npt.NDArray[np.int64]
```

Leaf of every sample.

**Parameters:**

* **values** (ndarray of shape (n_samples, n_expressions)): `values[:, j]` is expression `j` of `expressions_`.

**Returns:**

* **leaves** (ndarray of shape (n_samples,)): Node id of the leaf of each sample.

### `sklink.tree.RelationalTree.candidates` {#sklink.tree.RelationalTree.candidates}

```python
candidates: SplitCandidates | None = None
```

### `sklink.tree.RelationalTree.categories_left` {#sklink.tree.RelationalTree.categories_left}

```python
categories_left: list[npt.NDArray[np.int64]]
```

### `sklink.tree.RelationalTree.children_left` {#sklink.tree.RelationalTree.children_left}

```python
children_left: npt.NDArray[np.int64]
```

### `sklink.tree.RelationalTree.children_right` {#sklink.tree.RelationalTree.children_right}

```python
children_right: npt.NDArray[np.int64]
```

### `sklink.tree.RelationalTree.decision_path` {#sklink.tree.RelationalTree.decision_path}

```python
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 expression `j` of `expressions_`.

**Returns:**

* samples, nodes : ndarray of shape (n_visits,): Visited `(sample, node)` pairs, sorted by sample then node.

### `sklink.tree.RelationalTree.expression` {#sklink.tree.RelationalTree.expression}

```python
expression: npt.NDArray[np.int64]
```

### `sklink.tree.RelationalTree.feature` {#sklink.tree.RelationalTree.feature}

```python
feature: npt.NDArray[np.int64]
```

Alias of `expression`, named as in scikit-learn's trees.

### `sklink.tree.RelationalTree.go_left` {#sklink.tree.RelationalTree.go_left}

```python
go_left(node: int, values: Array) -> npt.NDArray[np.bool_]
```

Which samples go to the left child of `node`.

**Parameters:**

* **node** ([int](https://docs.python.org/3/library/functions.html#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,)): `True` for the samples that go left.

### `sklink.tree.RelationalTree.improvement` {#sklink.tree.RelationalTree.improvement}

```python
improvement: Array
```

### `sklink.tree.RelationalTree.impurity` {#sklink.tree.RelationalTree.impurity}

```python
impurity: Array
```

### `sklink.tree.RelationalTree.is_categorical` {#sklink.tree.RelationalTree.is_categorical}

```python
is_categorical: npt.NDArray[np.bool_]
```

### `sklink.tree.RelationalTree.max_depth` {#sklink.tree.RelationalTree.max_depth}

```python
max_depth: int
```

Depth of the deepest leaf (the root has depth 0).

### `sklink.tree.RelationalTree.missing_go_to_left` {#sklink.tree.RelationalTree.missing_go_to_left}

```python
missing_go_to_left: npt.NDArray[np.bool_]
```

### `sklink.tree.RelationalTree.n_leaves` {#sklink.tree.RelationalTree.n_leaves}

```python
n_leaves: int
```

Number of leaves.

### `sklink.tree.RelationalTree.n_node_samples` {#sklink.tree.RelationalTree.n_node_samples}

```python
n_node_samples: npt.NDArray[np.int64]
```

### `sklink.tree.RelationalTree.node_count` {#sklink.tree.RelationalTree.node_count}

```python
node_count: int
```

Number of nodes.

### `sklink.tree.RelationalTree.threshold` {#sklink.tree.RelationalTree.threshold}

```python
threshold: Array
```

### `sklink.tree.RelationalTree.value` {#sklink.tree.RelationalTree.value}

```python
value: Array
```

### `sklink.tree.RelationalTree.weighted_n_node_samples` {#sklink.tree.RelationalTree.weighted_n_node_samples}

```python
weighted_n_node_samples: Array
```

## `sklink.tree.SplitCandidates` {#sklink.tree.SplitCandidates}

```python
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, ...]) -> None
```

Best 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**](#sklink.tree.SplitCandidates.offsets) (ndarray of shape (node_count + 1,)): Start of the candidates of each node in the per-candidate arrays.
* [**expression**](#sklink.tree.SplitCandidates.expression) (ndarray of shape (n_candidates,)): Index in `names` of the question of each candidate.
* [**is_categorical**](#sklink.tree.SplitCandidates.is_categorical) (ndarray of shape (n_candidates,)): Whether the candidate is a category subset.
* [**threshold**](#sklink.tree.SplitCandidates.threshold) (ndarray of shape (n_candidates,)): Numeric threshold (go left when `value <= threshold`); NaN for
  categorical candidates.
* [**category_offsets**](#sklink.tree.SplitCandidates.category_offsets) (ndarray of shape (n_candidates + 1,)): Start of the left category codes of each candidate in
  `category_codes` (none for numeric candidates).
* [**category_codes**](#sklink.tree.SplitCandidates.category_codes) (ndarray of shape (n_codes,)): Left category codes, into `vocabularies[expression[j]]`.
* [**missing_go_to_left**](#sklink.tree.SplitCandidates.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**](#sklink.tree.SplitCandidates.improvement) (ndarray of shape (n_candidates,)): Weighted impurity decrease, on the scale of `RelationalTree.improvement`.
* [**refined**](#sklink.tree.SplitCandidates.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.
  `False` for questions scored only in the first, binned pass.
* [**names**](#sklink.tree.SplitCandidates.names) (tuple of str): Canonical names of the distinct questions of the candidates;
  `expression` indexes it. Names, not expression objects, keep the
  table small; [`sklink.expressions.parse`](./sklink.expressions#sklink.expressions.parse) reads a relational one
  back, and a name that is a column of `X` is that column.
* [**vocabularies**](#sklink.tree.SplitCandidates.vocabularies) (tuple of ndarray or None): Category labels of each entry of `names` (`None` if numeric).

sklink.tree.RelationalTree : The fitted structure that holds this table in
`candidates`.
sklink.plotting.SearchDisplay : Draw the questions scored at one node.

**Functions:**

* [**categories**](#sklink.tree.SplitCandidates.categories): Left category codes of candidate `j` (empty for numeric ones).
* [**of_node**](#sklink.tree.SplitCandidates.of_node): Positions of the candidates of `node` in the per-candidate arrays.

### `sklink.tree.SplitCandidates.categories` {#sklink.tree.SplitCandidates.categories}

```python
categories(j: int) -> npt.NDArray[np.int64]
```

Left category codes of candidate `j` (empty for numeric ones).

**Parameters:**

* **j** ([int](https://docs.python.org/3/library/functions.html#int)): Position of the candidate.

**Returns:**

* **codes** (ndarray of int): Codes into `vocabularies[expression[j]]`.

### `sklink.tree.SplitCandidates.category_codes` {#sklink.tree.SplitCandidates.category_codes}

```python
category_codes: npt.NDArray[np.int64]
```

### `sklink.tree.SplitCandidates.category_offsets` {#sklink.tree.SplitCandidates.category_offsets}

```python
category_offsets: npt.NDArray[np.int64]
```

### `sklink.tree.SplitCandidates.expression` {#sklink.tree.SplitCandidates.expression}

```python
expression: npt.NDArray[np.int64]
```

### `sklink.tree.SplitCandidates.improvement` {#sklink.tree.SplitCandidates.improvement}

```python
improvement: Array
```

### `sklink.tree.SplitCandidates.is_categorical` {#sklink.tree.SplitCandidates.is_categorical}

```python
is_categorical: npt.NDArray[np.bool_]
```

### `sklink.tree.SplitCandidates.missing_go_to_left` {#sklink.tree.SplitCandidates.missing_go_to_left}

```python
missing_go_to_left: npt.NDArray[np.bool_]
```

### `sklink.tree.SplitCandidates.names` {#sklink.tree.SplitCandidates.names}

```python
names: tuple[str, ...]
```

### `sklink.tree.SplitCandidates.of_node` {#sklink.tree.SplitCandidates.of_node}

```python
of_node(node: int) -> range
```

Positions of the candidates of `node` in the per-candidate arrays.

**Parameters:**

* **node** ([int](https://docs.python.org/3/library/functions.html#int)): Node id.

**Returns:**

* **positions** ([range](https://docs.python.org/3/library/stdtypes.html#range)): Empty for leaves.

### `sklink.tree.SplitCandidates.offsets` {#sklink.tree.SplitCandidates.offsets}

```python
offsets: npt.NDArray[np.int64]
```

### `sklink.tree.SplitCandidates.refined` {#sklink.tree.SplitCandidates.refined}

```python
refined: npt.NDArray[np.bool_]
```

### `sklink.tree.SplitCandidates.threshold` {#sklink.tree.SplitCandidates.threshold}

```python
threshold: Array
```

### `sklink.tree.SplitCandidates.vocabularies` {#sklink.tree.SplitCandidates.vocabularies}

```python
vocabularies: tuple[np.ndarray | None, ...]
```

:::
