---
url: /stable/api/sklink.ensemble.md
description: >-
  API reference of sklink.ensemble. Ensembles of relational models: forests,
  gradient boosting, isolation forests.
---

::: v-pre

# `sklink.ensemble` {#sklink.ensemble}

Ensembles of relational models: forests, gradient boosting, isolation forests.

**Classes:**

* [**RelationalGradientBoostingClassifier**](#sklink.ensemble.RelationalGradientBoostingClassifier): Gradient boosting of relational decision trees for classification.
* [**RelationalGradientBoostingRegressor**](#sklink.ensemble.RelationalGradientBoostingRegressor): Gradient boosting of relational decision trees for regression.
* [**RelationalIsolationForest**](#sklink.ensemble.RelationalIsolationForest): Isolation forest that finds unusual entities from their related rows.
* [**RelationalRandomForestClassifier**](#sklink.ensemble.RelationalRandomForestClassifier): Random forest of relational decision tree classifiers.
* [**RelationalRandomForestRegressor**](#sklink.ensemble.RelationalRandomForestRegressor): Random forest of relational decision tree regressors.

## `sklink.ensemble.RelationalGradientBoostingClassifier` {#sklink.ensemble.RelationalGradientBoostingClassifier}

```python
RelationalGradientBoostingClassifier(database: Database | None = None, *, entity: str | None = None, key: str | int | Sequence[str | int] | None = None, time: str | int | None = None, loss: Literal['log_loss'] = 'log_loss', learning_rate: float = 0.1, n_estimators: int = 100, subsample: float = 1.0, criterion: Literal['newton', 'squared_error'] = 'newton', min_samples_split: int | float = 2, min_samples_leaf: int | float = 1, min_weight_fraction_leaf: float = 0.0, max_depth: int | None = 3, min_impurity_decrease: float = 0.0, max_features: int | float | Literal['sqrt', 'log2'] | None = None, max_leaf_nodes: int | None = None, l2_regularization: float = 0.0, validation_fraction: float = 0.1, n_iter_no_change: int | None = None, tol: float = 0.0001, max_relationship_depth: int = 2, max_lookup_depth: int = 1, primitives: Literal['default'] | Sequence[str] = 'default', max_conditions: int = 2, condition_penalty: float = 2.0, max_search_samples: int | None = 2000, leaf_weights: int = 0, max_bins: int = 255, max_condition_bins: int = 32, max_categories: int = 32, record_candidates: int = 0, allow_reverse_paths: bool = False, handle_unknown_entity: Literal['error', 'empty'] = 'error', random_state: int | np.random.RandomState | None = None, verbose: int = 0) -> None
```

Bases: [ClassifierMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.ClassifierMixin.html), BaseRelationalGradientBoosting

Gradient boosting of relational decision trees for classification.

Each iteration fits a [`RelationalDecisionTreeRegressor`](./sklink.tree#sklink.tree.RelationalDecisionTreeRegressor)
to the gradient and the Hessian of the log loss: its splits maximize the
second-order gain and its leaves take Newton steps, as in XGBoost and
LightGBM (`criterion="squared_error"` fits the gradient alone, as
[`sklearn.ensemble.GradientBoostingClassifier`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html) does). With more
than two classes, every iteration fits one tree per class. The trees ask
questions about aggregates of related tables, optionally under learned
conditions, such as `count(orders[amount > 100]) > 2`. Candidate
expressions are evaluated and binned once for the whole fit and shared by
all trees. With `database=None` it is a standard gradient boosting
classifier on the columns of `X`.

**Guides:** [Relational gradient boosting](../tutorials/relational-gradient-boosting), [Tune gradient boosting](../guides/tune-gradient-boosting), [Case study: churn end to end](../case-studies/subscription-churn)

**Parameters:**

* **database** ([Database](./sklink.database#sklink.database.Database)): Related tables. `None` gives a standard boosting model 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 static.
* **loss** (log_loss): Loss to optimize: the binomial or multinomial log loss.
* **learning_rate** ([float](https://docs.python.org/3/library/functions.html#float)): Shrinkage of the contribution of each tree.
* **n\_estimators** ([int](https://docs.python.org/3/library/functions.html#int)): Number of boosting iterations.
* **subsample** ([float](https://docs.python.org/3/library/functions.html#float)): Fraction of the training rows, drawn without replacement, that each
  iteration fits its trees on (stochastic gradient boosting).
* **criterion** ((newton, squared_error)): How the trees are fitted. `"newton"` splits on the second-order gain
  `G_L**2 / (H_L + l2) + G_R**2 / (H_R + l2)` of the sums of
  gradients `G` and Hessians `H` of the samples in each child, and
  sets every leaf to `G / (H + l2)`, as XGBoost and LightGBM do (the
  Hessians then weigh the samples in `min_weight_fraction_leaf` and
  `min_impurity_decrease`).
  `"squared_error"` splits on the squared error of the gradient and
  sets every leaf to a Newton step afterwards, as
  [`sklearn.ensemble.GradientBoostingClassifier`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html) does with
  `criterion="squared_error"`.
* **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_depth** ([int](https://docs.python.org/3/library/functions.html#int) or None): Maximum depth of each tree.
* **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_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 (see the tree).
* **max_leaf_nodes** ([int](https://docs.python.org/3/library/functions.html#int)): Grow each tree best-first with at most this many leaves.
* **l2_regularization** ([float](https://docs.python.org/3/library/functions.html#float)): L2 penalty `l2` on the leaf values of the Newton trees (see
  `criterion`), added to the sum of sample weights times Hessians of
  each node, as in XGBoost, LightGBM and
  [`HistGradientBoostingClassifier`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.HistGradientBoostingClassifier.html): integer
  weights count as repeated rows, and scaling all the weights by `c`
  needs `c * l2` for the same model. Larger values shrink the
  leaves of few or confidently predicted samples; a node then splits
  only when the penalized gain of its best split is positive. Only with
  `criterion="newton"`. The Numba kernels score the penalized
  splits too (see the `tree_kernels` option of
  [`sklink.set_config`](./sklink#sklink.set_config)).
* **validation_fraction** ([float](https://docs.python.org/3/library/functions.html#float)): Fraction of the rows set aside to decide early stopping; used only
  when `n_iter_no_change` is set. The split is stratified by class.
* **n\_iter_no_change** ([int](https://docs.python.org/3/library/functions.html#int)): Stop when the validation loss has not improved by `tol` in this many
  iterations. `None` fits `n_estimators` iterations on all rows.
* **tol** ([float](https://docs.python.org/3/library/functions.html#float)): Minimum improvement of the validation loss for early stopping.
* **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,
  not counted by `max_relationship_depth`) from the rows a path aggregates
  to the columns its conditions read and that are aggregated without
  conditions, such as `mean(orders.order_items.products.price)` (see the
  tree).
* **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 first one, such as
  `count(orders[amount > 100.0 & type == 'express'])`; 1 fits faster.
* **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. Lower values fit faster on large data;
  `None` searches on all samples.
* **leaf_weights** ([int](https://docs.python.org/3/library/functions.html#int)): Depth, from 0 (none) to 4, of a small tree over the rows of each path
  whose leaf weights are candidates, as in getML's Relboost. Each
  boosting tree fits one such tree per path, at the first node that
  searches the path (the root, unless `max_features` leaves the path
  out there) and on a random half of the node's samples: the rows carry
  the working response of their sample, and the sum and the mean of the
  leaf weights of each sample's rows are then candidate questions at
  every node, each split paying
  `condition_penalty` like a learned condition. Such a question is a
  [`LeafSum`](./sklink.expressions#sklink.expressions.LeafSum), as
  `mean_weights(orders: +0.4 [type == 'pickup'] -0.1 [type in
  ('economy', 'express', 'standard')])`.
* **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.
* **max_categories** ([int](https://docs.python.org/3/library/functions.html#int)): Most frequent categories tried in `==` conditions. A categorical
  column with more categories among the reachable rows also gets
  conditions on sets of categories, as in
  [`RelationalDecisionTreeRegressor`](./sklink.tree#sklink.tree.RelationalDecisionTreeRegressor), ranked for
  each tree by the mean residual (negative gradient) of its iteration.
* **record_candidates** ([int](https://docs.python.org/3/library/functions.html#int)): Number of best questions each tree keeps for each split node, in
  `tree_.candidates` of its estimator, for
  [`SearchDisplay`](./sklink.plotting#sklink.plotting.SearchDisplay) (see the tree). `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 `subsample`, the sampling of `max_features`, the samples
  drawn for `max_search_samples` and the early-stopping split.
* **verbose** ([int](https://docs.python.org/3/library/functions.html#int)): Print the losses of every iteration when positive.

**Attributes:**

* **estimators\_** (ndarray of RelationalDecisionTreeRegressor of shape (n_estimators\_, K)): Fitted trees, `K = 1` for two classes and the number of classes
  otherwise. Their leaf values are raw (log-odds) steps, before the
  learning rate.
* **n\_estimators\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of iterations fitted: `n_estimators` unless early stopping
  or a callback ended the fit sooner.
* **classes\_** (ndarray of shape (n_classes,)): Class labels.
* **n\_classes\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of classes.
* **train_score\_** (ndarray of shape (n_estimators\_,)): Mean log loss of the training rows of each iteration (the rows drawn
  by `subsample`) after that iteration.
* **validation_score\_** (ndarray of shape (n_estimators\_,)): Mean log loss of the validation rows after each iteration; only with
  `n_iter_no_change`.
* **expressions\_** (tuple of Expression): Distinct questions used by all trees.
* **feature_importances\_** (ndarray of shape (n_features_in\_,)): Impurity-based importance per column of `X`: the unnormalized
  importances of the trees, averaged and normalized to sum to one, as
  in scikit-learn's gradient boosting.
* **expression_importances\_** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Importance per canonical expression name, computed in the same way,
  in decreasing order.
* [**schema\_**](#sklink.ensemble.RelationalGradientBoostingClassifier.schema_) ([Schema](./sklink.database#sklink.database.Schema) or None): Part of the database schema the model reads.
* **visibility\_** (Visibility): Visibility rules used during fit.
* **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.

sklink.ensemble.RelationalRandomForestClassifier : Averages deep trees
grown independently on bootstrap samples.

Each leaf takes the Newton step `sum(w * (y - p)) / (sum(w * p * (1 -
p)) + l2)` over its training rows, scaled by `(K - 1) / K` for
`K > 2` classes as in scikit-learn. The Newton trees choose their
splits for that step; with `criterion="squared_error"` the trees split
on the squared error of the gradient (Friedman's gradient boosting) and
the model is scikit-learn's gradient boosting in flat mode. A Hessian
below `1e-6`, of a sample predicted with a probability within about
`1e-6` of 0 or 1, counts as `1e-6` in the Newton trees: in the
working response and in the leaf sums `H`.

With scikit-learn 1.9 or later the model supports scikit-learn's
experimental callbacks: the `"fit"` task has `n_estimators` subtasks
named `"iteration"`, and a true return of `on_fit_task_end` for one of
them stops the fit after that iteration.

J. H. Friedman, "Greedy function approximation: a gradient boosting
machine", *Annals of Statistics* 29(5), 2001.

T. Chen and C. Guestrin, "XGBoost: a scalable tree boosting system",
*KDD*, 2016.

S. Natarajan, T. Khot, K. Kersting, B. Gutmann and J. Shavlik,
"Gradient-based boosting for statistical relational learning: the
relational dependency network case", *Machine Learning* 86, 2012.

**Examples:**

```pycon
>>> from sklink.datasets import make_relational_classification
>>> from sklink.ensemble import RelationalGradientBoostingClassifier
>>> db, X, y = make_relational_classification(
...     300, signal="conditional", output="numpy", random_state=0
... )
>>> model = RelationalGradientBoostingClassifier(
...     db, entity="customers", key=0, n_estimators=20, random_state=0
... ).fit(X, y)
>>> model.predict_proba(X).shape
(300, 2)
```

**Functions:**

* [**apply**](#sklink.ensemble.RelationalGradientBoostingClassifier.apply): Leaf index of every sample in every tree.
* [**decision_function**](#sklink.ensemble.RelationalGradientBoostingClassifier.decision_function): Raw scores: log-odds of the second class, or one score per class.
* [**fit**](#sklink.ensemble.RelationalGradientBoostingClassifier.fit): Fit the boosted trees.
* [**predict**](#sklink.ensemble.RelationalGradientBoostingClassifier.predict): Most probable class.
* [**predict_log_proba**](#sklink.ensemble.RelationalGradientBoostingClassifier.predict_log_proba): Logarithm of the class probabilities.
* [**predict_proba**](#sklink.ensemble.RelationalGradientBoostingClassifier.predict_proba): Class probabilities.
* [**staged_decision_function**](#sklink.ensemble.RelationalGradientBoostingClassifier.staged_decision_function): Raw scores after each iteration (see `decision_function`).
* [**staged_predict**](#sklink.ensemble.RelationalGradientBoostingClassifier.staged_predict): Predicted classes after each iteration.
* [**staged_predict_proba**](#sklink.ensemble.RelationalGradientBoostingClassifier.staged_predict_proba): Class probabilities after each iteration.

### `sklink.ensemble.RelationalGradientBoostingClassifier.allow_reverse_paths` {#sklink.ensemble.RelationalGradientBoostingClassifier.allow_reverse_paths}

```python
allow_reverse_paths = allow_reverse_paths
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.alpha` {#sklink.ensemble.RelationalGradientBoostingClassifier.alpha}

```python
alpha = alpha
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.apply` {#sklink.ensemble.RelationalGradientBoostingClassifier.apply}

```python
apply(X: Any) -> npt.NDArray[np.int64]
```

Leaf index of every sample in every tree.

**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, n_estimators\_, n_trees_per_iteration)): Leaf of each sample in each tree; the last axis has one entry per
  class for more than two classes, and one otherwise.

### `sklink.ensemble.RelationalGradientBoostingClassifier.condition_penalty` {#sklink.ensemble.RelationalGradientBoostingClassifier.condition_penalty}

```python
condition_penalty = condition_penalty
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.criterion` {#sklink.ensemble.RelationalGradientBoostingClassifier.criterion}

```python
criterion = criterion
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.database` {#sklink.ensemble.RelationalGradientBoostingClassifier.database}

```python
database = database
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.decision_function` {#sklink.ensemble.RelationalGradientBoostingClassifier.decision_function}

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

Raw scores: log-odds of the second class, or one score per class.

**Parameters:**

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

**Returns:**

* **score** (ndarray of shape (n_samples,) or (n_samples, n_classes)): One column for two classes, one per class otherwise.

### `sklink.ensemble.RelationalGradientBoostingClassifier.entity` {#sklink.ensemble.RelationalGradientBoostingClassifier.entity}

```python
entity = entity
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.fit` {#sklink.ensemble.RelationalGradientBoostingClassifier.fit}

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

Fit the boosted trees.

**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 row of weight zero is ignored as if it were not
  in `X`; integer weights are equivalent to repeated rows.

**Returns:**

* **self** ([RelationalGradientBoostingClassifier](#sklink.ensemble.RelationalGradientBoostingClassifier)): Fitted estimator.

### `sklink.ensemble.RelationalGradientBoostingClassifier.handle_unknown_entity` {#sklink.ensemble.RelationalGradientBoostingClassifier.handle_unknown_entity}

```python
handle_unknown_entity = handle_unknown_entity
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.key` {#sklink.ensemble.RelationalGradientBoostingClassifier.key}

```python
key = key
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.l2_regularization` {#sklink.ensemble.RelationalGradientBoostingClassifier.l2_regularization}

```python
l2_regularization = l2_regularization
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.leaf_weights` {#sklink.ensemble.RelationalGradientBoostingClassifier.leaf_weights}

```python
leaf_weights = leaf_weights
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.learning_rate` {#sklink.ensemble.RelationalGradientBoostingClassifier.learning_rate}

```python
learning_rate = learning_rate
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.loss` {#sklink.ensemble.RelationalGradientBoostingClassifier.loss}

```python
loss = loss
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.max_bins` {#sklink.ensemble.RelationalGradientBoostingClassifier.max_bins}

```python
max_bins = max_bins
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.max_categories` {#sklink.ensemble.RelationalGradientBoostingClassifier.max_categories}

```python
max_categories = max_categories
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.max_condition_bins` {#sklink.ensemble.RelationalGradientBoostingClassifier.max_condition_bins}

```python
max_condition_bins = max_condition_bins
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.max_conditions` {#sklink.ensemble.RelationalGradientBoostingClassifier.max_conditions}

```python
max_conditions = max_conditions
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.max_depth` {#sklink.ensemble.RelationalGradientBoostingClassifier.max_depth}

```python
max_depth = max_depth
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.max_features` {#sklink.ensemble.RelationalGradientBoostingClassifier.max_features}

```python
max_features = max_features
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.max_leaf_nodes` {#sklink.ensemble.RelationalGradientBoostingClassifier.max_leaf_nodes}

```python
max_leaf_nodes = max_leaf_nodes
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.max_lookup_depth` {#sklink.ensemble.RelationalGradientBoostingClassifier.max_lookup_depth}

```python
max_lookup_depth = max_lookup_depth
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.max_relationship_depth` {#sklink.ensemble.RelationalGradientBoostingClassifier.max_relationship_depth}

```python
max_relationship_depth = max_relationship_depth
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.max_search_samples` {#sklink.ensemble.RelationalGradientBoostingClassifier.max_search_samples}

```python
max_search_samples = max_search_samples
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.min_impurity_decrease` {#sklink.ensemble.RelationalGradientBoostingClassifier.min_impurity_decrease}

```python
min_impurity_decrease = min_impurity_decrease
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.min_samples_leaf` {#sklink.ensemble.RelationalGradientBoostingClassifier.min_samples_leaf}

```python
min_samples_leaf = min_samples_leaf
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.min_samples_split` {#sklink.ensemble.RelationalGradientBoostingClassifier.min_samples_split}

```python
min_samples_split = min_samples_split
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.min_weight_fraction_leaf` {#sklink.ensemble.RelationalGradientBoostingClassifier.min_weight_fraction_leaf}

```python
min_weight_fraction_leaf = min_weight_fraction_leaf
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.n_estimators` {#sklink.ensemble.RelationalGradientBoostingClassifier.n_estimators}

```python
n_estimators = n_estimators
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.n_iter_no_change` {#sklink.ensemble.RelationalGradientBoostingClassifier.n_iter_no_change}

```python
n_iter_no_change = n_iter_no_change
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.predict` {#sklink.ensemble.RelationalGradientBoostingClassifier.predict}

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

Most probable class.

**Parameters:**

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

**Returns:**

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

### `sklink.ensemble.RelationalGradientBoostingClassifier.predict_log_proba` {#sklink.ensemble.RelationalGradientBoostingClassifier.predict_log_proba}

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

Logarithm of the class probabilities.

**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)): Log probability of each class, in the order of `classes_`.

### `sklink.ensemble.RelationalGradientBoostingClassifier.predict_proba` {#sklink.ensemble.RelationalGradientBoostingClassifier.predict_proba}

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

Class probabilities.

**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)): Probability of each class, in the order of `classes_`.

### `sklink.ensemble.RelationalGradientBoostingClassifier.primitives` {#sklink.ensemble.RelationalGradientBoostingClassifier.primitives}

```python
primitives = primitives
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.random_state` {#sklink.ensemble.RelationalGradientBoostingClassifier.random_state}

```python
random_state = random_state
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.record_candidates` {#sklink.ensemble.RelationalGradientBoostingClassifier.record_candidates}

```python
record_candidates = record_candidates
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.schema_` {#sklink.ensemble.RelationalGradientBoostingClassifier.schema\_}

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

### `sklink.ensemble.RelationalGradientBoostingClassifier.staged_decision_function` {#sklink.ensemble.RelationalGradientBoostingClassifier.staged_decision_function}

```python
staged_decision_function(X: Any) -> Iterator[np.ndarray]
```

Raw scores after each iteration (see `decision_function`).

**Parameters:**

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

**Yields:**

* **score** (ndarray of shape (n_samples,) or (n_samples, n_classes)): Raw scores after each iteration.

### `sklink.ensemble.RelationalGradientBoostingClassifier.staged_predict` {#sklink.ensemble.RelationalGradientBoostingClassifier.staged_predict}

```python
staged_predict(X: Any) -> Iterator[np.ndarray]
```

Predicted classes after each iteration.

**Parameters:**

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

**Yields:**

* **y** (ndarray of shape (n_samples,)): Predicted class labels after each iteration.

### `sklink.ensemble.RelationalGradientBoostingClassifier.staged_predict_proba` {#sklink.ensemble.RelationalGradientBoostingClassifier.staged_predict_proba}

```python
staged_predict_proba(X: Any) -> Iterator[np.ndarray]
```

Class probabilities after each iteration.

**Parameters:**

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

**Yields:**

* **proba** (ndarray of shape (n_samples, n_classes)): Class probabilities after each iteration.

### `sklink.ensemble.RelationalGradientBoostingClassifier.subsample` {#sklink.ensemble.RelationalGradientBoostingClassifier.subsample}

```python
subsample = subsample
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.time` {#sklink.ensemble.RelationalGradientBoostingClassifier.time}

```python
time = time
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.tol` {#sklink.ensemble.RelationalGradientBoostingClassifier.tol}

```python
tol = tol
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.validation_fraction` {#sklink.ensemble.RelationalGradientBoostingClassifier.validation_fraction}

```python
validation_fraction = validation_fraction
```

### `sklink.ensemble.RelationalGradientBoostingClassifier.verbose` {#sklink.ensemble.RelationalGradientBoostingClassifier.verbose}

```python
verbose = verbose
```

## `sklink.ensemble.RelationalGradientBoostingRegressor` {#sklink.ensemble.RelationalGradientBoostingRegressor}

```python
RelationalGradientBoostingRegressor(database: Database | None = None, *, entity: str | None = None, key: str | int | Sequence[str | int] | None = None, time: str | int | None = None, loss: Literal['squared_error', 'absolute_error', 'huber', 'quantile'] = 'squared_error', learning_rate: float = 0.1, n_estimators: int = 100, subsample: float = 1.0, criterion: Literal['newton', 'squared_error'] = 'newton', min_samples_split: int | float = 2, min_samples_leaf: int | float = 1, min_weight_fraction_leaf: float = 0.0, max_depth: int | None = 3, min_impurity_decrease: float = 0.0, max_features: int | float | Literal['sqrt', 'log2'] | None = None, max_leaf_nodes: int | None = None, l2_regularization: float = 0.0, alpha: float = 0.9, validation_fraction: float = 0.1, n_iter_no_change: int | None = None, tol: float = 0.0001, max_relationship_depth: int = 2, max_lookup_depth: int = 1, primitives: Literal['default'] | Sequence[str] = 'default', max_conditions: int = 2, condition_penalty: float = 2.0, max_search_samples: int | None = 2000, leaf_weights: int = 0, max_bins: int = 255, max_condition_bins: int = 32, max_categories: int = 32, record_candidates: int = 0, allow_reverse_paths: bool = False, handle_unknown_entity: Literal['error', 'empty'] = 'error', random_state: int | np.random.RandomState | None = None, verbose: int = 0) -> None
```

Bases: [RegressorMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.RegressorMixin.html), BaseRelationalGradientBoosting

Gradient boosting of relational decision trees for regression.

Each iteration fits a [`RelationalDecisionTreeRegressor`](./sklink.tree#sklink.tree.RelationalDecisionTreeRegressor)
to the negative gradient of the loss and sets every leaf to the constant
that minimizes the loss over its training rows, as
[`sklearn.ensemble.GradientBoostingRegressor`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html) does; for the squared
error, `l2_regularization` shrinks the leaves as in XGBoost and
LightGBM. The trees ask questions about aggregates of related tables,
optionally under learned conditions. Candidate expressions are evaluated
and binned once for the whole fit and shared by all trees. With
`database=None` it is a standard gradient boosting regressor on the
columns of `X`.

**Guides:** [Relational gradient boosting](../tutorials/relational-gradient-boosting), [Tune gradient boosting](../guides/tune-gradient-boosting), [Case study: forecasts with intervals](../case-studies/machine-condition-intervals)

**Parameters:**

* **database** ([Database](./sklink.database#sklink.database.Database)): Related tables. `None` gives a standard boosting model 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 static.
* **loss** ((squared_error, absolute_error, huber, quantile)): Loss to optimize. `"huber"` is quadratic below the `alpha`-quantile
  of the absolute residuals of each iteration and linear above it;
  `"quantile"` predicts the `alpha`-quantile.
* **learning_rate** ([float](https://docs.python.org/3/library/functions.html#float)): Shrinkage of the contribution of each tree.
* **n\_estimators** ([int](https://docs.python.org/3/library/functions.html#int)): Number of boosting iterations.
* **subsample** ([float](https://docs.python.org/3/library/functions.html#float)): Fraction of the training rows, drawn without replacement, that each
  iteration fits its tree on (stochastic gradient boosting).
* **criterion** ((newton, squared_error)): How the trees are fitted. For the squared error both give the same
  trees, and `"newton"` allows `l2_regularization`. The absolute,
  Huber and quantile losses have no useful Hessian: their trees always
  fit the gradient, as scikit-learn's do.
* **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_depth** ([int](https://docs.python.org/3/library/functions.html#int) or None): Maximum depth of each tree.
* **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_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 (see the tree).
* **max_leaf_nodes** ([int](https://docs.python.org/3/library/functions.html#int)): Grow each tree best-first with at most this many leaves.
* **l2_regularization** ([float](https://docs.python.org/3/library/functions.html#float)): L2 penalty on the leaf values: each leaf takes `sum(w * r) /
  (sum(w) + l2)` of the residuals `r` of its samples, splits
  maximize the matching gain, and a node splits only when that gain
  is positive. `l2` counts in sample weight, as in XGBoost, LightGBM
  and [`HistGradientBoostingRegressor`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.HistGradientBoostingRegressor.html): integer
  weights count as repeated rows, and scaling all the weights by `c`
  needs `c * l2` for the same model. Only with the squared error and
  `criterion="newton"`. The Numba kernels score the penalized
  splits too (see the `tree_kernels` option of
  [`sklink.set_config`](./sklink#sklink.set_config)).
* **alpha** ([float](https://docs.python.org/3/library/functions.html#float)): Quantile of the `"quantile"` loss, and quantile of the absolute
  residuals where the `"huber"` loss turns linear. In `(0, 1)`.
* **validation_fraction** ([float](https://docs.python.org/3/library/functions.html#float)): Fraction of the rows set aside to decide early stopping; used only
  when `n_iter_no_change` is set.
* **n\_iter_no_change** ([int](https://docs.python.org/3/library/functions.html#int)): Stop when the validation loss has not improved by `tol` in this many
  iterations. `None` fits `n_estimators` iterations on all rows.
* **tol** ([float](https://docs.python.org/3/library/functions.html#float)): Minimum improvement of the validation loss for early stopping.
* **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,
  not counted by `max_relationship_depth`) from the rows a path aggregates
  to the columns its conditions read and that are aggregated without
  conditions, such as `mean(orders.order_items.products.price)` (see the
  tree).
* **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 first one, such as
  `count(orders[amount > 100.0 & type == 'express'])`; 1 fits faster.
* **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. Lower values fit faster on large data;
  `None` searches on all samples.
* **leaf_weights** ([int](https://docs.python.org/3/library/functions.html#int)): Depth, from 0 (none) to 4, of a small tree over the rows of each path
  whose leaf weights are candidates, as in getML's Relboost. Each
  boosting tree fits one such tree per path, at the first node that
  searches the path (the root, unless `max_features` leaves the path
  out there) and on a random half of the node's samples: the rows carry
  the working response of their sample, and the sum and the mean of the
  leaf weights of each sample's rows are then candidate questions at
  every node, each split paying
  `condition_penalty` like a learned condition. Such a question is a
  [`LeafSum`](./sklink.expressions#sklink.expressions.LeafSum), as
  `mean_weights(orders: +0.4 [type == 'pickup'] -0.1 [type in
  ('economy', 'express', 'standard')])`.
* **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.
* **max_categories** ([int](https://docs.python.org/3/library/functions.html#int)): Most frequent categories tried in `==` conditions. A categorical
  column with more categories among the reachable rows also gets
  conditions on sets of categories, as in
  [`RelationalDecisionTreeRegressor`](./sklink.tree#sklink.tree.RelationalDecisionTreeRegressor), ranked for
  each tree by the mean residual (negative gradient) of its iteration.
* **record_candidates** ([int](https://docs.python.org/3/library/functions.html#int)): Number of best questions each tree keeps for each split node, in
  `tree_.candidates` of its estimator, for
  [`SearchDisplay`](./sklink.plotting#sklink.plotting.SearchDisplay) (see the tree). `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 `subsample`, the sampling of `max_features`, the samples
  drawn for `max_search_samples` and the early-stopping split.
* **verbose** ([int](https://docs.python.org/3/library/functions.html#int)): Print the losses of every iteration when positive.

**Attributes:**

* **estimators\_** (ndarray of RelationalDecisionTreeRegressor of shape (n_estimators\_, 1)): Fitted trees. Their leaf values are steps before the learning rate.
* **n\_estimators\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of iterations fitted.
* **train_score\_** (ndarray of shape (n_estimators\_,)): Mean loss of the training rows of each iteration after it: the mean
  squared error, mean absolute error, mean Huber loss or mean pinball
  loss.
* **validation_score\_** (ndarray of shape (n_estimators\_,)): Mean loss of the validation rows after each iteration; only with
  `n_iter_no_change`.
* **expressions\_** (tuple of Expression): Distinct questions used by all trees.
* **feature_importances\_** (ndarray of shape (n_features_in\_,)): Impurity-based importance per column of `X`: the unnormalized
  importances of the trees, averaged and normalized to sum to one, as
  in scikit-learn's gradient boosting.
* **expression_importances\_** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Importance per canonical expression name, computed in the same way,
  in decreasing order.
* [**schema\_**](#sklink.ensemble.RelationalGradientBoostingRegressor.schema_) ([Schema](./sklink.database#sklink.database.Schema) or None): Part of the database schema the model reads.
* **visibility\_** (Visibility): Visibility rules used during fit.
* **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.

sklink.ensemble.RelationalRandomForestRegressor : Averages deep trees
grown independently on bootstrap samples.

With scikit-learn 1.9 or later the model supports scikit-learn's
experimental callbacks: the `"fit"` task has `n_estimators` subtasks
named `"iteration"`, and a true return of `on_fit_task_end` for one of
them stops the fit after that iteration.

J. H. Friedman, "Greedy function approximation: a gradient boosting
machine", *Annals of Statistics* 29(5), 2001.

**Examples:**

```pycon
>>> from sklink.datasets import make_relational_regression
>>> from sklink.ensemble import RelationalGradientBoostingRegressor
>>> db, X, y = make_relational_regression(300, output="numpy", random_state=0)
>>> model = RelationalGradientBoostingRegressor(
...     db, entity="customers", key=0, n_estimators=20, random_state=0
... ).fit(X, y)
>>> model.predict(X).shape
(300,)
```

**Functions:**

* [**apply**](#sklink.ensemble.RelationalGradientBoostingRegressor.apply): Leaf index of every sample in every tree.
* [**fit**](#sklink.ensemble.RelationalGradientBoostingRegressor.fit): Fit the boosted trees.
* [**predict**](#sklink.ensemble.RelationalGradientBoostingRegressor.predict): Predicted values.
* [**staged_predict**](#sklink.ensemble.RelationalGradientBoostingRegressor.staged_predict): Predicted values after each iteration.

### `sklink.ensemble.RelationalGradientBoostingRegressor.allow_reverse_paths` {#sklink.ensemble.RelationalGradientBoostingRegressor.allow_reverse_paths}

```python
allow_reverse_paths = allow_reverse_paths
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.alpha` {#sklink.ensemble.RelationalGradientBoostingRegressor.alpha}

```python
alpha = alpha
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.apply` {#sklink.ensemble.RelationalGradientBoostingRegressor.apply}

```python
apply(X: Any) -> npt.NDArray[np.int64]
```

Leaf index of every sample in every tree.

**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, n_estimators\_)): Leaf of each sample in each tree, as
  [`sklearn.ensemble.GradientBoostingRegressor.apply`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.apply.html) returns it.

### `sklink.ensemble.RelationalGradientBoostingRegressor.condition_penalty` {#sklink.ensemble.RelationalGradientBoostingRegressor.condition_penalty}

```python
condition_penalty = condition_penalty
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.criterion` {#sklink.ensemble.RelationalGradientBoostingRegressor.criterion}

```python
criterion = criterion
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.database` {#sklink.ensemble.RelationalGradientBoostingRegressor.database}

```python
database = database
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.entity` {#sklink.ensemble.RelationalGradientBoostingRegressor.entity}

```python
entity = entity
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.fit` {#sklink.ensemble.RelationalGradientBoostingRegressor.fit}

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

Fit the boosted trees.

**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 row of weight zero is ignored as if it were not
  in `X`; integer weights are equivalent to repeated rows.

**Returns:**

* **self** ([RelationalGradientBoostingRegressor](#sklink.ensemble.RelationalGradientBoostingRegressor)): Fitted estimator.

### `sklink.ensemble.RelationalGradientBoostingRegressor.handle_unknown_entity` {#sklink.ensemble.RelationalGradientBoostingRegressor.handle_unknown_entity}

```python
handle_unknown_entity = handle_unknown_entity
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.key` {#sklink.ensemble.RelationalGradientBoostingRegressor.key}

```python
key = key
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.l2_regularization` {#sklink.ensemble.RelationalGradientBoostingRegressor.l2_regularization}

```python
l2_regularization = l2_regularization
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.leaf_weights` {#sklink.ensemble.RelationalGradientBoostingRegressor.leaf_weights}

```python
leaf_weights = leaf_weights
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.learning_rate` {#sklink.ensemble.RelationalGradientBoostingRegressor.learning_rate}

```python
learning_rate = learning_rate
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.loss` {#sklink.ensemble.RelationalGradientBoostingRegressor.loss}

```python
loss = loss
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.max_bins` {#sklink.ensemble.RelationalGradientBoostingRegressor.max_bins}

```python
max_bins = max_bins
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.max_categories` {#sklink.ensemble.RelationalGradientBoostingRegressor.max_categories}

```python
max_categories = max_categories
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.max_condition_bins` {#sklink.ensemble.RelationalGradientBoostingRegressor.max_condition_bins}

```python
max_condition_bins = max_condition_bins
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.max_conditions` {#sklink.ensemble.RelationalGradientBoostingRegressor.max_conditions}

```python
max_conditions = max_conditions
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.max_depth` {#sklink.ensemble.RelationalGradientBoostingRegressor.max_depth}

```python
max_depth = max_depth
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.max_features` {#sklink.ensemble.RelationalGradientBoostingRegressor.max_features}

```python
max_features = max_features
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.max_leaf_nodes` {#sklink.ensemble.RelationalGradientBoostingRegressor.max_leaf_nodes}

```python
max_leaf_nodes = max_leaf_nodes
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.max_lookup_depth` {#sklink.ensemble.RelationalGradientBoostingRegressor.max_lookup_depth}

```python
max_lookup_depth = max_lookup_depth
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.max_relationship_depth` {#sklink.ensemble.RelationalGradientBoostingRegressor.max_relationship_depth}

```python
max_relationship_depth = max_relationship_depth
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.max_search_samples` {#sklink.ensemble.RelationalGradientBoostingRegressor.max_search_samples}

```python
max_search_samples = max_search_samples
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.min_impurity_decrease` {#sklink.ensemble.RelationalGradientBoostingRegressor.min_impurity_decrease}

```python
min_impurity_decrease = min_impurity_decrease
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.min_samples_leaf` {#sklink.ensemble.RelationalGradientBoostingRegressor.min_samples_leaf}

```python
min_samples_leaf = min_samples_leaf
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.min_samples_split` {#sklink.ensemble.RelationalGradientBoostingRegressor.min_samples_split}

```python
min_samples_split = min_samples_split
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.min_weight_fraction_leaf` {#sklink.ensemble.RelationalGradientBoostingRegressor.min_weight_fraction_leaf}

```python
min_weight_fraction_leaf = min_weight_fraction_leaf
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.n_estimators` {#sklink.ensemble.RelationalGradientBoostingRegressor.n_estimators}

```python
n_estimators = n_estimators
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.n_iter_no_change` {#sklink.ensemble.RelationalGradientBoostingRegressor.n_iter_no_change}

```python
n_iter_no_change = n_iter_no_change
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.predict` {#sklink.ensemble.RelationalGradientBoostingRegressor.predict}

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

Predicted values.

**Parameters:**

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

**Returns:**

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

### `sklink.ensemble.RelationalGradientBoostingRegressor.primitives` {#sklink.ensemble.RelationalGradientBoostingRegressor.primitives}

```python
primitives = primitives
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.random_state` {#sklink.ensemble.RelationalGradientBoostingRegressor.random_state}

```python
random_state = random_state
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.record_candidates` {#sklink.ensemble.RelationalGradientBoostingRegressor.record_candidates}

```python
record_candidates = record_candidates
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.schema_` {#sklink.ensemble.RelationalGradientBoostingRegressor.schema\_}

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

### `sklink.ensemble.RelationalGradientBoostingRegressor.staged_predict` {#sklink.ensemble.RelationalGradientBoostingRegressor.staged_predict}

```python
staged_predict(X: Any) -> Iterator[np.ndarray]
```

Predicted values after each iteration.

**Parameters:**

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

**Yields:**

* **y** (ndarray of shape (n_samples,)): Predicted values after each iteration.

### `sklink.ensemble.RelationalGradientBoostingRegressor.subsample` {#sklink.ensemble.RelationalGradientBoostingRegressor.subsample}

```python
subsample = subsample
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.time` {#sklink.ensemble.RelationalGradientBoostingRegressor.time}

```python
time = time
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.tol` {#sklink.ensemble.RelationalGradientBoostingRegressor.tol}

```python
tol = tol
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.validation_fraction` {#sklink.ensemble.RelationalGradientBoostingRegressor.validation_fraction}

```python
validation_fraction = validation_fraction
```

### `sklink.ensemble.RelationalGradientBoostingRegressor.verbose` {#sklink.ensemble.RelationalGradientBoostingRegressor.verbose}

```python
verbose = verbose
```

## `sklink.ensemble.RelationalIsolationForest` {#sklink.ensemble.RelationalIsolationForest}

```python
RelationalIsolationForest(database: Database | None = None, *, entity: str | None = None, key: str | int | Sequence[str | int] | None = None, time: str | int | None = None, n_estimators: int = 100, max_samples: Literal['auto'] | int | float = 'auto', contamination: Literal['auto'] | float = 'auto', max_features: int | float = 1.0, bootstrap: bool = False, n_jobs: int | None = None, max_relationship_depth: int = 2, max_lookup_depth: int = 1, primitives: Literal['default'] | Sequence[str] = 'default', conditional: bool = False, max_categories: int = 10, windows: Sequence[str | dt.timedelta | np.timedelta64] | None = None, include: Sequence[str] | None = None, exclude: Sequence[str] | None = None, allow_reverse_paths: bool = False, handle_unknown_entity: Literal['error', 'empty'] = 'error', random_state: int | np.random.RandomState | None = None) -> None
```

Bases: [OutlierMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.OutlierMixin.html), VersionedStateMixin, [BaseEstimator](https://scikit-learn.org/stable/modules/generated/sklearn.base.BaseEstimator.html)

Isolation forest that finds unusual entities from their related rows.

Each sample (a row of `X`) is described by the relational features of
[`RelationalFeaturizer`](./sklink.feature_extraction#sklink.feature_extraction.RelationalFeaturizer), such as
`count(orders)`, `max(orders.amount)` or
`proportion(orders[type == 'express'])`, and by the other columns of
`X`. Categorical features become one indicator per category and
missing values take the training mean; then
[`sklearn.ensemble.IsolationForest`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html) isolates the samples with
random splits. A sample that few splits isolate, such as a customer with
many more orders, or much larger ones, than the others, is an outlier.
With `database=None` it is an isolation forest on the columns of `X`.

**Guides:** [Find unusual entities](../tutorials/anomaly-detection), [Case study: segments and anomalies](../case-studies/segment-and-flag-accounts)

**Parameters:**

* **database** ([Database](./sklink.database#sklink.database.Database)): Related tables. `None` uses the columns of `X` alone.
* **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 static.
  With a cutoff, a sample is described only by rows before it.
* **n\_estimators** ([int](https://docs.python.org/3/library/functions.html#int)): Number of isolation trees.
* **max_samples** ((auto, [int](https://docs.python.org/3/library/functions.html#int) or [float](https://docs.python.org/3/library/functions.html#float))): Samples drawn to grow each tree: `"auto"` is `min(256, n_samples)`,
  an int that many and a float that fraction (see
  [`sklearn.ensemble.IsolationForest`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html)).
* **contamination** (auto or [float](https://docs.python.org/3/library/functions.html#float)): Expected share of outliers, which sets the threshold of `predict`.
  `"auto"` uses the threshold of the original paper.
* **max_features** ([int](https://docs.python.org/3/library/functions.html#int) or [float](https://docs.python.org/3/library/functions.html#float)): Features drawn to grow each tree, an int or a fraction of the
  standardized features.
* **bootstrap** ([bool](https://docs.python.org/3/library/functions.html#bool)): Draw the samples of each tree with replacement.
* **n\_jobs** ([int](https://docs.python.org/3/library/functions.html#int)): Trees grown in parallel (see [`sklearn.ensemble.IsolationForest`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html)).
* **max_relationship_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum number of relationships followed from the entity table.
* **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,
  not counted by `max_relationship_depth`) from the rows of a path to the
  columns that its category conditions read and that are aggregated like the
  columns of the path's last table, such as
  `mean(orders.order_items.products.price)` (see the featurizer).
* **primitives** ("default" or list of str): Aggregations to apply. `"default"` picks them from each column's type.
* **conditional** ([bool](https://docs.python.org/3/library/functions.html#bool)): Also aggregate numeric columns over the rows of each frequent
  category, as [`RelationalFeaturizer`](./sklink.feature_extraction#sklink.feature_extraction.RelationalFeaturizer)
  does by default. Off by default here: these aggregates add many
  columns correlated with the unconditioned ones, and the trees, which
  split on features drawn at random, then isolate samples mostly along
  those few correlated directions.
* **max_categories** ([int](https://docs.python.org/3/library/functions.html#int)): Number of most frequent categories per categorical column that get their
  own `count` and `proportion` features.
* **windows** (list of str, timedelta or timedelta64): Temporal mode only: also aggregate over these windows before the cutoff.
* **include** (list of str): Glob patterns over canonical names, table names or relationship names
  that select the features.
* **exclude** (list of str): Glob patterns over canonical names, table names or relationship names
  that select the features.
* **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 of `X` missing from the entity table.
* **random_state** (([int](https://docs.python.org/3/library/functions.html#int), RandomState or None)): Controls the samples and splits of every tree.

**Attributes:**

* **isolation_forest\_** ([IsolationForest](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html)): Fitted forest on the embedding, whose columns are named by
  `embedding_feature_names_`.
* **offset\_** ([float](https://docs.python.org/3/library/functions.html#float)): Offset that turns `score_samples` into `decision_function`.
* **featurizer\_** ([RelationalFeaturizer](./sklink.feature_extraction#sklink.feature_extraction.RelationalFeaturizer)): Fitted featurizer that describes the samples.
* **embedding_feature_names\_** (ndarray of str): Names of the columns the forest splits: a featurizer column, or
  `"name == label"` for the indicator of a category.
* **expressions\_** (tuple of Expression): Expressions of the featurizer columns.
* **schema\_** ([Schema](./sklink.database#sklink.database.Schema) or None): Part of the database schema the model reads.
* **visibility\_** (Visibility): Visibility rules used during fit.
* **n\_features_in\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of columns of `X`.
* **feature_names_in\_** (ndarray of str): Column names of `X`, when it has them.

sklink.cluster.RelationalKMeans : Groups of similar entities, on the same
features.

The forest is invariant to the scale of each feature, so the
standardization of the features does not change it; it only places
missing values at the training mean. A table with many columns gives
the trees more features to split on: narrow them with `include` or
`exclude`.

F. T. Liu, K. M. Ting and Z.-H. Zhou, "Isolation forest", *IEEE
International Conference on Data Mining*, 2008.

**Examples:**

```pycon
>>> from sklink.datasets import load_shop
>>> from sklink.ensemble import RelationalIsolationForest
>>> shop = load_shop()
>>> model = RelationalIsolationForest(
...     shop.database, entity="customers", key=0, random_state=0
... ).fit(shop.X)
>>> model.predict(shop.X).shape
(24,)
```

**Functions:**

* [**decision_function**](#sklink.ensemble.RelationalIsolationForest.decision_function): Score of every row of `X` shifted by `offset_`: negative for outliers.
* [**fit**](#sklink.ensemble.RelationalIsolationForest.fit): Grow the isolation trees.
* [**predict**](#sklink.ensemble.RelationalIsolationForest.predict): Whether every row of `X` is an inlier (1) or an outlier (-1).
* [**score_samples**](#sklink.ensemble.RelationalIsolationForest.score_samples): Anomaly score of every row of `X`: the lower, the more abnormal.

### `sklink.ensemble.RelationalIsolationForest.allow_reverse_paths` {#sklink.ensemble.RelationalIsolationForest.allow_reverse_paths}

```python
allow_reverse_paths = allow_reverse_paths
```

### `sklink.ensemble.RelationalIsolationForest.bootstrap` {#sklink.ensemble.RelationalIsolationForest.bootstrap}

```python
bootstrap = bootstrap
```

### `sklink.ensemble.RelationalIsolationForest.conditional` {#sklink.ensemble.RelationalIsolationForest.conditional}

```python
conditional = conditional
```

### `sklink.ensemble.RelationalIsolationForest.contamination` {#sklink.ensemble.RelationalIsolationForest.contamination}

```python
contamination = contamination
```

### `sklink.ensemble.RelationalIsolationForest.database` {#sklink.ensemble.RelationalIsolationForest.database}

```python
database = database
```

### `sklink.ensemble.RelationalIsolationForest.decision_function` {#sklink.ensemble.RelationalIsolationForest.decision_function}

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

Score of every row of `X` shifted by `offset_`: negative for outliers.

**Parameters:**

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

**Returns:**

* **scores** (ndarray of shape (n_samples,)): `score_samples(X) - offset_`.

### `sklink.ensemble.RelationalIsolationForest.entity` {#sklink.ensemble.RelationalIsolationForest.entity}

```python
entity = entity
```

### `sklink.ensemble.RelationalIsolationForest.exclude` {#sklink.ensemble.RelationalIsolationForest.exclude}

```python
exclude = exclude
```

### `sklink.ensemble.RelationalIsolationForest.fit` {#sklink.ensemble.RelationalIsolationForest.fit}

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

Grow the isolation trees.

**Parameters:**

* **X** (DataFrame or array-like of shape (n_samples, n_columns)): Population table: entity key, optional cutoff and sample features.
* **y** (None): Ignored.
* **sample_weight** (array-like of shape (n_samples,)): Weight of every row in the standardization and, as in
  [`sklearn.ensemble.IsolationForest`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html), the probability that a
  tree draws the row. Without `bootstrap`, a tree that draws every
  row (such as with `max_samples="auto"` and at most 256 rows of
  positive weight) ignores the weights, and `contamination`
  counts rows, not weights. A row of weight zero learns nothing, as if it were
  not in `X`.

**Returns:**

* **self** ([RelationalIsolationForest](#sklink.ensemble.RelationalIsolationForest)): Fitted estimator.

### `sklink.ensemble.RelationalIsolationForest.handle_unknown_entity` {#sklink.ensemble.RelationalIsolationForest.handle_unknown_entity}

```python
handle_unknown_entity = handle_unknown_entity
```

### `sklink.ensemble.RelationalIsolationForest.include` {#sklink.ensemble.RelationalIsolationForest.include}

```python
include = include
```

### `sklink.ensemble.RelationalIsolationForest.key` {#sklink.ensemble.RelationalIsolationForest.key}

```python
key = key
```

### `sklink.ensemble.RelationalIsolationForest.max_categories` {#sklink.ensemble.RelationalIsolationForest.max_categories}

```python
max_categories = max_categories
```

### `sklink.ensemble.RelationalIsolationForest.max_features` {#sklink.ensemble.RelationalIsolationForest.max_features}

```python
max_features = max_features
```

### `sklink.ensemble.RelationalIsolationForest.max_lookup_depth` {#sklink.ensemble.RelationalIsolationForest.max_lookup_depth}

```python
max_lookup_depth = max_lookup_depth
```

### `sklink.ensemble.RelationalIsolationForest.max_relationship_depth` {#sklink.ensemble.RelationalIsolationForest.max_relationship_depth}

```python
max_relationship_depth = max_relationship_depth
```

### `sklink.ensemble.RelationalIsolationForest.max_samples` {#sklink.ensemble.RelationalIsolationForest.max_samples}

```python
max_samples = max_samples
```

### `sklink.ensemble.RelationalIsolationForest.n_estimators` {#sklink.ensemble.RelationalIsolationForest.n_estimators}

```python
n_estimators = n_estimators
```

### `sklink.ensemble.RelationalIsolationForest.n_jobs` {#sklink.ensemble.RelationalIsolationForest.n_jobs}

```python
n_jobs = n_jobs
```

### `sklink.ensemble.RelationalIsolationForest.predict` {#sklink.ensemble.RelationalIsolationForest.predict}

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

Whether every row of `X` is an inlier (1) or an outlier (-1).

**Parameters:**

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

**Returns:**

* **labels** (ndarray of shape (n_samples,)): `-1` where `decision_function` is negative, `1` elsewhere.

### `sklink.ensemble.RelationalIsolationForest.primitives` {#sklink.ensemble.RelationalIsolationForest.primitives}

```python
primitives = primitives
```

### `sklink.ensemble.RelationalIsolationForest.random_state` {#sklink.ensemble.RelationalIsolationForest.random_state}

```python
random_state = random_state
```

### `sklink.ensemble.RelationalIsolationForest.score_samples` {#sklink.ensemble.RelationalIsolationForest.score_samples}

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

Anomaly score of every row of `X`: the lower, the more abnormal.

**Parameters:**

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

**Returns:**

* **scores** (ndarray of shape (n_samples,)): Opposite of the anomaly score of the original paper.

### `sklink.ensemble.RelationalIsolationForest.time` {#sklink.ensemble.RelationalIsolationForest.time}

```python
time = time
```

### `sklink.ensemble.RelationalIsolationForest.windows` {#sklink.ensemble.RelationalIsolationForest.windows}

```python
windows = windows
```

## `sklink.ensemble.RelationalRandomForestClassifier` {#sklink.ensemble.RelationalRandomForestClassifier}

```python
RelationalRandomForestClassifier(database: Database | None = None, *, entity: str | None = None, key: str | int | Sequence[str | int] | None = None, time: str | int | None = None, n_estimators: int = 100, 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 = 'sqrt', max_leaf_nodes: int | None = None, min_impurity_decrease: float = 0.0, bootstrap: bool = True, max_samples: int | float | None = None, oob_score: bool | Callable[..., float] = False, class_weight: dict[Any, float] | Literal['balanced', 'balanced_subsample'] | 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 = 0, allow_reverse_paths: bool = False, handle_unknown_entity: Literal['error', 'empty'] = 'error', n_jobs: int | None = None, random_state: int | np.random.RandomState | None = None, verbose: int = 0) -> None
```

Bases: [ClassifierMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.ClassifierMixin.html), BaseRelationalForest

Random forest of relational decision tree classifiers.

Each tree is a [`RelationalDecisionTreeClassifier`](./sklink.tree#sklink.tree.RelationalDecisionTreeClassifier)
grown on a bootstrap sample of the rows of `X`; the forest averages
their class probabilities. Candidate expressions are evaluated and binned
once for the whole forest and shared by all trees. With `database=None`
it is a standard random forest on the columns of `X`.

**Guides:** [Relational random forests](../tutorials/relational-random-forests), [Tune trees and forests](../guides/tune-trees-and-forests)

**Parameters:**

* **database** ([Database](./sklink.database#sklink.database.Database)): Related tables. `None` gives a standard forest 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 static.
* **n\_estimators** ([int](https://docs.python.org/3/library/functions.html#int)): Number of trees.
* **criterion** ((gini, entropy, log_loss)): Impurity measure.
* **max_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum depth of each 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 (see the tree).
* **max_leaf_nodes** ([int](https://docs.python.org/3/library/functions.html#int)): Grow each tree 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.
* **bootstrap** ([bool](https://docs.python.org/3/library/functions.html#bool)): Draw a bootstrap sample of the rows of `X` for each tree. Rows are
  drawn with probability proportional to `sample_weight` (times the
  class weights), and each tree weighs its rows by how often they were
  drawn, as in scikit-learn 1.9 whatever version is installed. With
  `False` every tree sees every row with its weight.
* **max_samples** ([int](https://docs.python.org/3/library/functions.html#int) or [float](https://docs.python.org/3/library/functions.html#float)): Size of each bootstrap sample: all rows when `None`, that many draws
  for an int (it may exceed the number of rows), and that fraction of the
  number of rows, or of the total `sample_weight` when it is given,
  for a float.
* **oob_score** ([bool](https://docs.python.org/3/library/functions.html#bool) or [callable](https://docs.python.org/3/library/functions.html#callable)): Score the forest on the rows each tree did not draw. A callable is
  called as `score(y_true, y_pred)`.
* **class_weight** (([dict](https://docs.python.org/3/library/stdtypes.html#dict), balanced, balanced_subsample or None)): Weights of the classes; `"balanced_subsample"` recomputes them for
  each bootstrap sample.
* **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 column with more categories also gets
  conditions on sets of categories ranked by the mean target, as in
  [`RelationalDecisionTreeClassifier`](./sklink.tree#sklink.tree.RelationalDecisionTreeClassifier). Each tree
  ranks them on its own bootstrap sample, so that its out-of-bag
  samples take no part in the ranking.
* **record_candidates** ([int](https://docs.python.org/3/library/functions.html#int)): Number of best questions each tree keeps for each split node, in
  `tree_.candidates` of its estimator (see the tree). `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.
* **n\_jobs** ([int](https://docs.python.org/3/library/functions.html#int)): Number of trees grown in parallel, in worker processes unless another
  joblib backend is configured. Each task grows a group of up to 16
  trees side by side, which scores their nodes in batches. Results do
  not depend on it.
* **random_state** (([int](https://docs.python.org/3/library/functions.html#int), RandomState or None)): Controls bootstrapping, the sampling of `max_features` and the
  samples drawn for `max_search_samples`.
* **verbose** ([int](https://docs.python.org/3/library/functions.html#int)): Verbosity of the parallel loop.

**Attributes:**

* **estimators\_** (list of RelationalDecisionTreeClassifier): Fitted trees: `n_estimators` of them, unless a callback stopped
  the fit (see Notes).
* [**estimators_samples\_**](#sklink.ensemble.RelationalRandomForestClassifier.estimators_samples_) (list of ndarray): Indices of the rows of `X` drawn for each tree, with repetitions and
  in draw order, as in scikit-learn. Drawn again from the seed of each
  tree at every access, so the forest does not store them.
* **classes\_** (ndarray of shape (n_classes,)): Class labels.
* **n\_classes\_** ([int](https://docs.python.org/3/library/functions.html#int)): Number of classes.
* **expressions\_** (tuple of Expression): Distinct questions used by all trees.
* **feature_importances\_** (ndarray of shape (n_features_in\_,)): Mean impurity-based importance per column of `X`.
* **expression_importances\_** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Importance per canonical expression name, averaged over the trees and
  normalized to sum to one, in decreasing order.
* **oob_score\_** ([float](https://docs.python.org/3/library/functions.html#float)): Out-of-bag accuracy (or the given score); only with `oob_score`.
* **oob_decision_function\_** (ndarray of shape (n_samples, n_classes)): Out-of-bag class probabilities; only with `oob_score`.
* [**schema\_**](#sklink.ensemble.RelationalRandomForestClassifier.schema_) ([Schema](./sklink.database#sklink.database.Schema) or None): Part of the database schema the model reads.
* **visibility\_** (Visibility): Visibility rules used during fit.
* **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.

sklink.ensemble.RelationalRandomForestRegressor : The same forest for a
numeric target.
sklink.tree.RelationalDecisionTreeClassifier : The tree grown on each
bootstrap sample.
sklink.ensemble.RelationalGradientBoostingClassifier : Shallow trees fitted
in sequence, each to the errors of the previous ones.

With scikit-learn 1.9 or later the forest 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
`n_estimators` subtasks named `"tree"`, one per tree in the order of
`estimators_`: subtask `i` is `estimators_[i]`. They begin and end in
the main process as each tree comes back from the workers, whatever
`n_jobs`. The workers get no callback, so the trees report no node
subtasks. As scikit-learn specifies, a true return of `on_fit_task_end`
asks to stop the iterations: for a tree, no further tree is grown (those
already running are cancelled, and the trees of the stopping tree's group
are discarded) and the forest is fitted with the trees reported so far,
which are those of the full forest. `estimators_` and
`estimators_samples_` then have fewer than `n_estimators` entries,
which the parameter keeps. The `"fit"` task gets `X`, `y` and, when
given, `metadata={"sample_weight": ...}`, and its end the fitted forest.
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.ensemble import RelationalRandomForestClassifier
>>> db, X, y = make_relational_classification(
...     300, signal="conditional", output="numpy", random_state=0
... )
>>> forest = RelationalRandomForestClassifier(
...     db, entity="customers", key=0, n_estimators=10,
...     max_conditions=2, random_state=0,
... ).fit(X, y)
>>> forest.predict_proba(X).shape
(300, 2)
```

**Functions:**

* [**apply**](#sklink.ensemble.RelationalRandomForestClassifier.apply): Leaf index of every sample in every tree.
* [**fit**](#sklink.ensemble.RelationalRandomForestClassifier.fit): Grow the trees.
* [**predict**](#sklink.ensemble.RelationalRandomForestClassifier.predict): Class with the highest mean probability.
* [**predict_log_proba**](#sklink.ensemble.RelationalRandomForestClassifier.predict_log_proba): Logarithm of `predict_proba`.
* [**predict_proba**](#sklink.ensemble.RelationalRandomForestClassifier.predict_proba): Mean class probabilities of the trees.

### `sklink.ensemble.RelationalRandomForestClassifier.allow_reverse_paths` {#sklink.ensemble.RelationalRandomForestClassifier.allow_reverse_paths}

```python
allow_reverse_paths = allow_reverse_paths
```

### `sklink.ensemble.RelationalRandomForestClassifier.apply` {#sklink.ensemble.RelationalRandomForestClassifier.apply}

```python
apply(X: Any) -> npt.NDArray[np.int64]
```

Leaf index of every sample in every tree.

**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, n_estimators)): Leaf of each sample in each tree.

### `sklink.ensemble.RelationalRandomForestClassifier.bootstrap` {#sklink.ensemble.RelationalRandomForestClassifier.bootstrap}

```python
bootstrap = bootstrap
```

### `sklink.ensemble.RelationalRandomForestClassifier.class_weight` {#sklink.ensemble.RelationalRandomForestClassifier.class_weight}

```python
class_weight = class_weight
```

### `sklink.ensemble.RelationalRandomForestClassifier.condition_penalty` {#sklink.ensemble.RelationalRandomForestClassifier.condition_penalty}

```python
condition_penalty = condition_penalty
```

### `sklink.ensemble.RelationalRandomForestClassifier.criterion` {#sklink.ensemble.RelationalRandomForestClassifier.criterion}

```python
criterion = criterion
```

### `sklink.ensemble.RelationalRandomForestClassifier.database` {#sklink.ensemble.RelationalRandomForestClassifier.database}

```python
database = database
```

### `sklink.ensemble.RelationalRandomForestClassifier.entity` {#sklink.ensemble.RelationalRandomForestClassifier.entity}

```python
entity = entity
```

### `sklink.ensemble.RelationalRandomForestClassifier.estimators_samples_` {#sklink.ensemble.RelationalRandomForestClassifier.estimators_samples\_}

```python
estimators_samples_: list[np.ndarray]
```

Rows of `X` drawn for each tree, with repetitions, in draw order.

Drawn again from the seed of each tree at every access, as in
scikit-learn, so that a fitted or saved forest does not hold one
index per training row and tree.

### `sklink.ensemble.RelationalRandomForestClassifier.fit` {#sklink.ensemble.RelationalRandomForestClassifier.fit}

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

Grow the trees.

With scikit-learn 1.9 or later, callbacks set with `set_callbacks`
follow the fit: see `RelationalRandomForestClassifier`.

**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. With `bootstrap=True` they set how often each
  row is drawn; integer weights then match repeating rows in
  distribution, not tree by tree. The bins and condition cuts shared
  by all trees are learned once from these weights, not from any
  bootstrap sample, and a row of weight zero is ignored as if it were
  not in `X`.

**Returns:**

* **self** ([RelationalRandomForestClassifier](#sklink.ensemble.RelationalRandomForestClassifier)): Fitted estimator.

### `sklink.ensemble.RelationalRandomForestClassifier.handle_unknown_entity` {#sklink.ensemble.RelationalRandomForestClassifier.handle_unknown_entity}

```python
handle_unknown_entity = handle_unknown_entity
```

### `sklink.ensemble.RelationalRandomForestClassifier.key` {#sklink.ensemble.RelationalRandomForestClassifier.key}

```python
key = key
```

### `sklink.ensemble.RelationalRandomForestClassifier.max_bins` {#sklink.ensemble.RelationalRandomForestClassifier.max_bins}

```python
max_bins = max_bins
```

### `sklink.ensemble.RelationalRandomForestClassifier.max_categories` {#sklink.ensemble.RelationalRandomForestClassifier.max_categories}

```python
max_categories = max_categories
```

### `sklink.ensemble.RelationalRandomForestClassifier.max_condition_bins` {#sklink.ensemble.RelationalRandomForestClassifier.max_condition_bins}

```python
max_condition_bins = max_condition_bins
```

### `sklink.ensemble.RelationalRandomForestClassifier.max_conditions` {#sklink.ensemble.RelationalRandomForestClassifier.max_conditions}

```python
max_conditions = max_conditions
```

### `sklink.ensemble.RelationalRandomForestClassifier.max_depth` {#sklink.ensemble.RelationalRandomForestClassifier.max_depth}

```python
max_depth = max_depth
```

### `sklink.ensemble.RelationalRandomForestClassifier.max_features` {#sklink.ensemble.RelationalRandomForestClassifier.max_features}

```python
max_features = max_features
```

### `sklink.ensemble.RelationalRandomForestClassifier.max_leaf_nodes` {#sklink.ensemble.RelationalRandomForestClassifier.max_leaf_nodes}

```python
max_leaf_nodes = max_leaf_nodes
```

### `sklink.ensemble.RelationalRandomForestClassifier.max_lookup_depth` {#sklink.ensemble.RelationalRandomForestClassifier.max_lookup_depth}

```python
max_lookup_depth = max_lookup_depth
```

### `sklink.ensemble.RelationalRandomForestClassifier.max_relationship_depth` {#sklink.ensemble.RelationalRandomForestClassifier.max_relationship_depth}

```python
max_relationship_depth = max_relationship_depth
```

### `sklink.ensemble.RelationalRandomForestClassifier.max_samples` {#sklink.ensemble.RelationalRandomForestClassifier.max_samples}

```python
max_samples = max_samples
```

### `sklink.ensemble.RelationalRandomForestClassifier.max_search_samples` {#sklink.ensemble.RelationalRandomForestClassifier.max_search_samples}

```python
max_search_samples = max_search_samples
```

### `sklink.ensemble.RelationalRandomForestClassifier.min_impurity_decrease` {#sklink.ensemble.RelationalRandomForestClassifier.min_impurity_decrease}

```python
min_impurity_decrease = min_impurity_decrease
```

### `sklink.ensemble.RelationalRandomForestClassifier.min_samples_leaf` {#sklink.ensemble.RelationalRandomForestClassifier.min_samples_leaf}

```python
min_samples_leaf = min_samples_leaf
```

### `sklink.ensemble.RelationalRandomForestClassifier.min_samples_split` {#sklink.ensemble.RelationalRandomForestClassifier.min_samples_split}

```python
min_samples_split = min_samples_split
```

### `sklink.ensemble.RelationalRandomForestClassifier.min_weight_fraction_leaf` {#sklink.ensemble.RelationalRandomForestClassifier.min_weight_fraction_leaf}

```python
min_weight_fraction_leaf = min_weight_fraction_leaf
```

### `sklink.ensemble.RelationalRandomForestClassifier.n_estimators` {#sklink.ensemble.RelationalRandomForestClassifier.n_estimators}

```python
n_estimators = n_estimators
```

### `sklink.ensemble.RelationalRandomForestClassifier.n_jobs` {#sklink.ensemble.RelationalRandomForestClassifier.n_jobs}

```python
n_jobs = n_jobs
```

### `sklink.ensemble.RelationalRandomForestClassifier.oob_score` {#sklink.ensemble.RelationalRandomForestClassifier.oob_score}

```python
oob_score = oob_score
```

### `sklink.ensemble.RelationalRandomForestClassifier.predict` {#sklink.ensemble.RelationalRandomForestClassifier.predict}

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

Class with the highest mean probability.

**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.ensemble.RelationalRandomForestClassifier.predict_log_proba` {#sklink.ensemble.RelationalRandomForestClassifier.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.ensemble.RelationalRandomForestClassifier.predict_proba` {#sklink.ensemble.RelationalRandomForestClassifier.predict_proba}

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

Mean class probabilities of the trees.

**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.ensemble.RelationalRandomForestClassifier.primitives` {#sklink.ensemble.RelationalRandomForestClassifier.primitives}

```python
primitives = primitives
```

### `sklink.ensemble.RelationalRandomForestClassifier.random_state` {#sklink.ensemble.RelationalRandomForestClassifier.random_state}

```python
random_state = random_state
```

### `sklink.ensemble.RelationalRandomForestClassifier.record_candidates` {#sklink.ensemble.RelationalRandomForestClassifier.record_candidates}

```python
record_candidates = record_candidates
```

### `sklink.ensemble.RelationalRandomForestClassifier.schema_` {#sklink.ensemble.RelationalRandomForestClassifier.schema\_}

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

### `sklink.ensemble.RelationalRandomForestClassifier.time` {#sklink.ensemble.RelationalRandomForestClassifier.time}

```python
time = time
```

### `sklink.ensemble.RelationalRandomForestClassifier.verbose` {#sklink.ensemble.RelationalRandomForestClassifier.verbose}

```python
verbose = verbose
```

## `sklink.ensemble.RelationalRandomForestRegressor` {#sklink.ensemble.RelationalRandomForestRegressor}

```python
RelationalRandomForestRegressor(database: Database | None = None, *, entity: str | None = None, key: str | int | Sequence[str | int] | None = None, time: str | int | None = None, n_estimators: int = 100, 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 = 1.0, max_leaf_nodes: int | None = None, min_impurity_decrease: float = 0.0, bootstrap: bool = True, max_samples: int | float | None = None, oob_score: bool | Callable[..., float] = False, 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 = 0, allow_reverse_paths: bool = False, handle_unknown_entity: Literal['error', 'empty'] = 'error', n_jobs: int | None = None, random_state: int | np.random.RandomState | None = None, verbose: int = 0) -> None
```

Bases: [RegressorMixin](https://scikit-learn.org/stable/modules/generated/sklearn.base.RegressorMixin.html), BaseRelationalForest

Random forest of relational decision tree regressors.

Same parameters as `RelationalRandomForestClassifier` without
`class_weight`; `criterion` is `"squared_error"` and `max_features`
defaults to `1.0`, as in scikit-learn.

**Guides:** [Relational random forests](../tutorials/relational-random-forests), [Tune trees and forests](../guides/tune-trees-and-forests)

**Parameters:**

* **database** ([Database](./sklink.database#sklink.database.Database)): Related tables. `None` gives a standard forest 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 static.
* **n\_estimators** ([int](https://docs.python.org/3/library/functions.html#int)): Number of trees.
* **criterion** (squared_error): Impurity measure.
* **max_depth** ([int](https://docs.python.org/3/library/functions.html#int)): Maximum depth of each 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 each tree 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.
* **bootstrap** ([bool](https://docs.python.org/3/library/functions.html#bool)): Draw a bootstrap sample of the rows of `X` for each tree. Rows are
  drawn with probability proportional to `sample_weight` (times the
  class weights), and each tree weighs its rows by how often they were
  drawn, as in scikit-learn 1.9 whatever version is installed. With
  `False` every tree sees every row with its weight.
* **max_samples** ([int](https://docs.python.org/3/library/functions.html#int) or [float](https://docs.python.org/3/library/functions.html#float)): Size of each bootstrap sample: all rows when `None`, that many draws
  for an int (it may exceed the number of rows), and that fraction of the
  number of rows, or of the total `sample_weight` when it is given,
  for a float.
* **oob_score** ([bool](https://docs.python.org/3/library/functions.html#bool) or [callable](https://docs.python.org/3/library/functions.html#callable)): Score the forest (R², or the given score) on the rows each tree did
  not draw.
* **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 column with more categories also gets
  conditions on sets of categories ranked by the mean target, as in
  [`RelationalDecisionTreeClassifier`](./sklink.tree#sklink.tree.RelationalDecisionTreeClassifier). Each tree
  ranks them on its own bootstrap sample, so that its out-of-bag
  samples take no part in the ranking.
* **record_candidates** ([int](https://docs.python.org/3/library/functions.html#int)): Number of best questions each tree keeps for each split node, in
  `tree_.candidates` of its estimator (see the tree). `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.
* **n\_jobs** ([int](https://docs.python.org/3/library/functions.html#int)): Number of trees grown in parallel, in worker processes unless another
  joblib backend is configured. Each task grows a group of up to 16
  trees side by side, which scores their nodes in batches. Results do
  not depend on it.
* **random_state** (([int](https://docs.python.org/3/library/functions.html#int), RandomState or None)): Controls bootstrapping, the sampling of `max_features` and the
  samples drawn for `max_search_samples`.
* **verbose** ([int](https://docs.python.org/3/library/functions.html#int)): Verbosity of the parallel loop.

**Attributes:**

* **estimators\_** (list of RelationalDecisionTreeRegressor): Fitted trees: `n_estimators` of them, unless a callback stopped
  the fit (see Notes).
* [**estimators_samples\_**](#sklink.ensemble.RelationalRandomForestRegressor.estimators_samples_) (list of ndarray): Indices of the rows of `X` drawn for each tree, with repetitions and
  in draw order, as in scikit-learn. Drawn again from the seed of each
  tree at every access, so the forest does not store them.
* **expressions\_** (tuple of Expression): Distinct questions used by all trees.
* **feature_importances\_** (ndarray of shape (n_features_in\_,)): Mean impurity-based importance per column of `X`.
* **expression_importances\_** ([dict](https://docs.python.org/3/library/stdtypes.html#dict)): Importance per canonical expression name, averaged over the trees and
  normalized to sum to one, in decreasing order.
* **oob_score\_** ([float](https://docs.python.org/3/library/functions.html#float)): Out-of-bag R² (or the given score); only with `oob_score`.
* **oob_prediction\_** (ndarray of shape (n_samples,)): Out-of-bag predictions; only with `oob_score`.
* [**schema\_**](#sklink.ensemble.RelationalRandomForestRegressor.schema_) ([Schema](./sklink.database#sklink.database.Schema) or None): Part of the database schema the model reads.
* **visibility\_** (Visibility): Visibility rules used during fit.
* **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.

sklink.ensemble.RelationalRandomForestClassifier : The same forest for
class labels.
sklink.tree.RelationalDecisionTreeRegressor : The tree grown on each
bootstrap sample.
sklink.ensemble.RelationalGradientBoostingRegressor : Shallow trees fitted
in sequence, each to the errors of the previous ones.

With scikit-learn 1.9 or later, `set_callbacks` follows the fit tree by
tree, as described for `RelationalRandomForestClassifier`.

**Examples:**

```pycon
>>> from sklink.datasets import make_relational_regression
>>> from sklink.ensemble import RelationalRandomForestRegressor
>>> db, X, y = make_relational_regression(300, output="numpy", random_state=0)
>>> forest = RelationalRandomForestRegressor(
...     db, entity="customers", key=0, n_estimators=10, random_state=0
... ).fit(X, y)
>>> forest.predict(X).shape
(300,)
```

**Functions:**

* [**apply**](#sklink.ensemble.RelationalRandomForestRegressor.apply): Leaf index of every sample in every tree.
* [**fit**](#sklink.ensemble.RelationalRandomForestRegressor.fit): Grow the trees.
* [**predict**](#sklink.ensemble.RelationalRandomForestRegressor.predict): Mean prediction of the trees.

### `sklink.ensemble.RelationalRandomForestRegressor.allow_reverse_paths` {#sklink.ensemble.RelationalRandomForestRegressor.allow_reverse_paths}

```python
allow_reverse_paths = allow_reverse_paths
```

### `sklink.ensemble.RelationalRandomForestRegressor.apply` {#sklink.ensemble.RelationalRandomForestRegressor.apply}

```python
apply(X: Any) -> npt.NDArray[np.int64]
```

Leaf index of every sample in every tree.

**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, n_estimators)): Leaf of each sample in each tree.

### `sklink.ensemble.RelationalRandomForestRegressor.bootstrap` {#sklink.ensemble.RelationalRandomForestRegressor.bootstrap}

```python
bootstrap = bootstrap
```

### `sklink.ensemble.RelationalRandomForestRegressor.condition_penalty` {#sklink.ensemble.RelationalRandomForestRegressor.condition_penalty}

```python
condition_penalty = condition_penalty
```

### `sklink.ensemble.RelationalRandomForestRegressor.criterion` {#sklink.ensemble.RelationalRandomForestRegressor.criterion}

```python
criterion = criterion
```

### `sklink.ensemble.RelationalRandomForestRegressor.database` {#sklink.ensemble.RelationalRandomForestRegressor.database}

```python
database = database
```

### `sklink.ensemble.RelationalRandomForestRegressor.entity` {#sklink.ensemble.RelationalRandomForestRegressor.entity}

```python
entity = entity
```

### `sklink.ensemble.RelationalRandomForestRegressor.estimators_samples_` {#sklink.ensemble.RelationalRandomForestRegressor.estimators_samples\_}

```python
estimators_samples_: list[np.ndarray]
```

Rows of `X` drawn for each tree, with repetitions, in draw order.

Drawn again from the seed of each tree at every access, as in
scikit-learn, so that a fitted or saved forest does not hold one
index per training row and tree.

### `sklink.ensemble.RelationalRandomForestRegressor.fit` {#sklink.ensemble.RelationalRandomForestRegressor.fit}

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

Grow the trees.

With scikit-learn 1.9 or later, callbacks set with `set_callbacks`
follow the fit: see `RelationalRandomForestClassifier`.

**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. With `bootstrap=True` they set how often each
  row is drawn; integer weights then match repeating rows in
  distribution, not tree by tree. The bins and condition cuts shared
  by all trees are learned once from these weights, not from any
  bootstrap sample, and a row of weight zero is ignored as if it were
  not in `X`.

**Returns:**

* **self** ([RelationalRandomForestRegressor](#sklink.ensemble.RelationalRandomForestRegressor)): Fitted estimator.

### `sklink.ensemble.RelationalRandomForestRegressor.handle_unknown_entity` {#sklink.ensemble.RelationalRandomForestRegressor.handle_unknown_entity}

```python
handle_unknown_entity = handle_unknown_entity
```

### `sklink.ensemble.RelationalRandomForestRegressor.key` {#sklink.ensemble.RelationalRandomForestRegressor.key}

```python
key = key
```

### `sklink.ensemble.RelationalRandomForestRegressor.max_bins` {#sklink.ensemble.RelationalRandomForestRegressor.max_bins}

```python
max_bins = max_bins
```

### `sklink.ensemble.RelationalRandomForestRegressor.max_categories` {#sklink.ensemble.RelationalRandomForestRegressor.max_categories}

```python
max_categories = max_categories
```

### `sklink.ensemble.RelationalRandomForestRegressor.max_condition_bins` {#sklink.ensemble.RelationalRandomForestRegressor.max_condition_bins}

```python
max_condition_bins = max_condition_bins
```

### `sklink.ensemble.RelationalRandomForestRegressor.max_conditions` {#sklink.ensemble.RelationalRandomForestRegressor.max_conditions}

```python
max_conditions = max_conditions
```

### `sklink.ensemble.RelationalRandomForestRegressor.max_depth` {#sklink.ensemble.RelationalRandomForestRegressor.max_depth}

```python
max_depth = max_depth
```

### `sklink.ensemble.RelationalRandomForestRegressor.max_features` {#sklink.ensemble.RelationalRandomForestRegressor.max_features}

```python
max_features = max_features
```

### `sklink.ensemble.RelationalRandomForestRegressor.max_leaf_nodes` {#sklink.ensemble.RelationalRandomForestRegressor.max_leaf_nodes}

```python
max_leaf_nodes = max_leaf_nodes
```

### `sklink.ensemble.RelationalRandomForestRegressor.max_lookup_depth` {#sklink.ensemble.RelationalRandomForestRegressor.max_lookup_depth}

```python
max_lookup_depth = max_lookup_depth
```

### `sklink.ensemble.RelationalRandomForestRegressor.max_relationship_depth` {#sklink.ensemble.RelationalRandomForestRegressor.max_relationship_depth}

```python
max_relationship_depth = max_relationship_depth
```

### `sklink.ensemble.RelationalRandomForestRegressor.max_samples` {#sklink.ensemble.RelationalRandomForestRegressor.max_samples}

```python
max_samples = max_samples
```

### `sklink.ensemble.RelationalRandomForestRegressor.max_search_samples` {#sklink.ensemble.RelationalRandomForestRegressor.max_search_samples}

```python
max_search_samples = max_search_samples
```

### `sklink.ensemble.RelationalRandomForestRegressor.min_impurity_decrease` {#sklink.ensemble.RelationalRandomForestRegressor.min_impurity_decrease}

```python
min_impurity_decrease = min_impurity_decrease
```

### `sklink.ensemble.RelationalRandomForestRegressor.min_samples_leaf` {#sklink.ensemble.RelationalRandomForestRegressor.min_samples_leaf}

```python
min_samples_leaf = min_samples_leaf
```

### `sklink.ensemble.RelationalRandomForestRegressor.min_samples_split` {#sklink.ensemble.RelationalRandomForestRegressor.min_samples_split}

```python
min_samples_split = min_samples_split
```

### `sklink.ensemble.RelationalRandomForestRegressor.min_weight_fraction_leaf` {#sklink.ensemble.RelationalRandomForestRegressor.min_weight_fraction_leaf}

```python
min_weight_fraction_leaf = min_weight_fraction_leaf
```

### `sklink.ensemble.RelationalRandomForestRegressor.n_estimators` {#sklink.ensemble.RelationalRandomForestRegressor.n_estimators}

```python
n_estimators = n_estimators
```

### `sklink.ensemble.RelationalRandomForestRegressor.n_jobs` {#sklink.ensemble.RelationalRandomForestRegressor.n_jobs}

```python
n_jobs = n_jobs
```

### `sklink.ensemble.RelationalRandomForestRegressor.oob_score` {#sklink.ensemble.RelationalRandomForestRegressor.oob_score}

```python
oob_score = oob_score
```

### `sklink.ensemble.RelationalRandomForestRegressor.predict` {#sklink.ensemble.RelationalRandomForestRegressor.predict}

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

Mean prediction of the trees.

**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.ensemble.RelationalRandomForestRegressor.primitives` {#sklink.ensemble.RelationalRandomForestRegressor.primitives}

```python
primitives = primitives
```

### `sklink.ensemble.RelationalRandomForestRegressor.random_state` {#sklink.ensemble.RelationalRandomForestRegressor.random_state}

```python
random_state = random_state
```

### `sklink.ensemble.RelationalRandomForestRegressor.record_candidates` {#sklink.ensemble.RelationalRandomForestRegressor.record_candidates}

```python
record_candidates = record_candidates
```

### `sklink.ensemble.RelationalRandomForestRegressor.schema_` {#sklink.ensemble.RelationalRandomForestRegressor.schema\_}

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

### `sklink.ensemble.RelationalRandomForestRegressor.time` {#sklink.ensemble.RelationalRandomForestRegressor.time}

```python
time = time
```

### `sklink.ensemble.RelationalRandomForestRegressor.verbose` {#sklink.ensemble.RelationalRandomForestRegressor.verbose}

```python
verbose = verbose
```

:::
