sklink.ensemble
Ensembles of relational models: forests, gradient boosting, isolation forests.
Classes:
- RelationalGradientBoostingClassifier: Gradient boosting of relational decision trees for classification.
- RelationalGradientBoostingRegressor: Gradient boosting of relational decision trees for regression.
- RelationalIsolationForest: Isolation forest that finds unusual entities from their related rows.
- RelationalRandomForestClassifier: Random forest of relational decision tree classifiers.
- RelationalRandomForestRegressor: Random forest of relational decision tree regressors.
sklink.ensemble.RelationalGradientBoostingClassifier
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) -> NoneBases: ClassifierMixin, BaseRelationalGradientBoosting
Gradient boosting of relational decision trees for classification.
Each iteration fits a 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 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, Tune gradient boosting, Case study: churn end to end
Parameters:
- database (
Database): Related tables.Nonegives a standard boosting model onX. - entity (
str): Table whose rows are the samples; required with a database. - key (
(str, int or sequence)): Column(s) ofXholding the entity key. - time (
str or int): Column ofXwith the cutoff of each sample;Noneis static. - loss (
log_loss): Loss to optimize: the binomial or multinomial log loss. - learning_rate (
float): Shrinkage of the contribution of each tree. - n_estimators (
int): Number of boosting iterations. - subsample (
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 gainG_L**2 / (H_L + l2) + G_R**2 / (H_R + l2)of the sums of gradientsGand HessiansHof the samples in each child, and sets every leaf toG / (H + l2), as XGBoost and LightGBM do (the Hessians then weigh the samples inmin_weight_fraction_leafandmin_impurity_decrease)."squared_error"splits on the squared error of the gradient and sets every leaf to a Newton step afterwards, assklearn.ensemble.GradientBoostingClassifierdoes withcriterion="squared_error". - min_samples_split (
int or float): Minimum number of samples to split a node. - min_samples_leaf (
int or float): Minimum number of samples in each leaf. - min_weight_fraction_leaf (
float): Minimum fraction of the total sample weight in each leaf. - max_depth (
int or None): Maximum depth of each tree. - min_impurity_decrease (
float): A node is split only if the weighted impurity decrease reaches this. - max_features (
(int, float, {sqrt, log2} or None)): Number of candidate groups tried at each node (see the tree). - max_leaf_nodes (
int): Grow each tree best-first with at most this many leaves. - l2_regularization (
float): L2 penaltyl2on the leaf values of the Newton trees (seecriterion), added to the sum of sample weights times Hessians of each node, as in XGBoost, LightGBM andHistGradientBoostingClassifier: integer weights count as repeated rows, and scaling all the weights bycneedsc * l2for 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 withcriterion="newton". The Numba kernels score the penalized splits too (see thetree_kernelsoption ofsklink.set_config). - validation_fraction (
float): Fraction of the rows set aside to decide early stopping; used only whenn_iter_no_changeis set. The split is stratified by class. - n_iter_no_change (
int): Stop when the validation loss has not improved bytolin this many iterations.Nonefitsn_estimatorsiterations on all rows. - tol (
float): Minimum improvement of the validation loss for early stopping. - max_relationship_depth (
int): Maximum number of relationship hops of a path. - max_lookup_depth (
int): Maximum number of lookups (many-to-one steps after the last table of a path, not counted bymax_relationship_depth) from the rows a path aggregates to the columns its conditions read and that are aggregated without conditions, such asmean(orders.order_items.products.price)(see the tree). - primitives (
"default" or sequence of str): Primitives of the unconditioned aggregates. - max_conditions (
int): Conditions learned inside an aggregate: 0, 1 or 2. With 2, the second condition is searched for the best first one, such ascount(orders[amount > 100.0 & type == 'express']); 1 fits faster. - condition_penalty (
float): Gain each learned condition must pay before it is chosen: this value times the gain one condition makes by chance at the node (the node impurity for the Gini index and the squared error, a constant for the entropy, times the mean sample weight per row) and the log of the number of conditions its path offers. The best of many conditions gains by chance alone, so this Bonferroni-style correction keeps conditions that only fit noise out of small nodes; a question whose conditions do not pay for themselves is not asked. Improvements and importances stay the impurity decrease itself. Higher values prefer aggregates without conditions on small or noisy data;0disables it. - max_search_samples (
int or None): Samples on which a node searches its aggregates with learned conditions. A node with more samples searches them on this many, drawn at random once per tree, with the leaf limits scaled to that share, then scores the best few on all its samples, so that the condition search costs the same at any size of the data. Withrecord_candidates, such a node records only those few among the questions with learned conditions. Lower values fit faster on large data;Nonesearches on all samples. - leaf_weights (
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, unlessmax_featuresleaves 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 payingcondition_penaltylike a learned condition. Such a question is aLeafSum, asmean_weights(orders: +0.4 [type == 'pickup'] -0.1 [type in ('economy', 'express', 'standard')]). - max_bins (
int): Thresholds per base feature. - max_condition_bins (
int): Candidate cuts per numeric condition column before refinement. - max_categories (
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 inRelationalDecisionTreeRegressor, ranked for each tree by the mean residual (negative gradient) of its iteration. - record_candidates (
int): Number of best questions each tree keeps for each split node, intree_.candidatesof its estimator, forSearchDisplay(see the tree).0keeps none. - allow_reverse_paths (
bool): Allow paths that read rows of other entities through shared tables. - handle_unknown_entity (
(error, empty)): What to do with keys that are not in the entity table. - random_state (
(int, RandomState or None)): Controlssubsample, the sampling ofmax_features, the samples drawn formax_search_samplesand the early-stopping split. - verbose (
int): Print the losses of every iteration when positive.
Attributes:
- estimators_ (
ndarray of RelationalDecisionTreeRegressor of shape (n_estimators_, K)): Fitted trees,K = 1for two classes and the number of classes otherwise. Their leaf values are raw (log-odds) steps, before the learning rate. - n_estimators_ (
int): Number of iterations fitted:n_estimatorsunless early stopping or a callback ended the fit sooner. - classes_ (
ndarray of shape (n_classes,)): Class labels. - n_classes_ (
int): Number of classes. - train_score_ (
ndarray of shape (n_estimators_,)): Mean log loss of the training rows of each iteration (the rows drawn bysubsample) after that iteration. - validation_score_ (
ndarray of shape (n_estimators_,)): Mean log loss of the validation rows after each iteration; only withn_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 ofX: the unnormalized importances of the trees, averaged and normalized to sum to one, as in scikit-learn's gradient boosting. - expression_importances_ (
dict): Importance per canonical expression name, computed in the same way, in decreasing order. - schema_ (
Schema or None): Part of the database schema the model reads. - visibility_ (
Visibility): Visibility rules used during fit. - n_features_in_ (
int): Number of columns ofX. - feature_names_in_ (
ndarray of shape (n_features_in_,)): Column names ofXwhen it has them.
See Also
sklink.ensemble.RelationalRandomForestClassifier : Averages deep trees grown independently on bootstrap samples.
Notes
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.
References
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:
>>> 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: Leaf index of every sample in every tree.
- decision_function: Raw scores: log-odds of the second class, or one score per class.
- fit: Fit the boosted trees.
- predict: Most probable class.
- predict_log_proba: Logarithm of the class probabilities.
- predict_proba: Class probabilities.
- staged_decision_function: Raw scores after each iteration (see
decision_function). - staged_predict: Predicted classes after each iteration.
- staged_predict_proba: Class probabilities after each iteration.
sklink.ensemble.RelationalGradientBoostingClassifier.allow_reverse_paths
allow_reverse_paths = allow_reverse_pathssklink.ensemble.RelationalGradientBoostingClassifier.alpha
alpha = alphasklink.ensemble.RelationalGradientBoostingClassifier.apply
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 infit.
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
condition_penalty = condition_penaltysklink.ensemble.RelationalGradientBoostingClassifier.criterion
criterion = criterionsklink.ensemble.RelationalGradientBoostingClassifier.database
database = databasesklink.ensemble.RelationalGradientBoostingClassifier.decision_function
decision_function(X: Any) -> np.ndarrayRaw 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 infit.
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
entity = entitysklink.ensemble.RelationalGradientBoostingClassifier.fit
fit(X: Any, y: Any, sample_weight: Any = None) -> SelfFit 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 inX; integer weights are equivalent to repeated rows.
Returns:
- self (
RelationalGradientBoostingClassifier): Fitted estimator.
sklink.ensemble.RelationalGradientBoostingClassifier.handle_unknown_entity
handle_unknown_entity = handle_unknown_entitysklink.ensemble.RelationalGradientBoostingClassifier.key
key = keysklink.ensemble.RelationalGradientBoostingClassifier.l2_regularization
l2_regularization = l2_regularizationsklink.ensemble.RelationalGradientBoostingClassifier.leaf_weights
leaf_weights = leaf_weightssklink.ensemble.RelationalGradientBoostingClassifier.learning_rate
learning_rate = learning_ratesklink.ensemble.RelationalGradientBoostingClassifier.loss
loss = losssklink.ensemble.RelationalGradientBoostingClassifier.max_bins
max_bins = max_binssklink.ensemble.RelationalGradientBoostingClassifier.max_categories
max_categories = max_categoriessklink.ensemble.RelationalGradientBoostingClassifier.max_condition_bins
max_condition_bins = max_condition_binssklink.ensemble.RelationalGradientBoostingClassifier.max_conditions
max_conditions = max_conditionssklink.ensemble.RelationalGradientBoostingClassifier.max_depth
max_depth = max_depthsklink.ensemble.RelationalGradientBoostingClassifier.max_features
max_features = max_featuressklink.ensemble.RelationalGradientBoostingClassifier.max_leaf_nodes
max_leaf_nodes = max_leaf_nodessklink.ensemble.RelationalGradientBoostingClassifier.max_lookup_depth
max_lookup_depth = max_lookup_depthsklink.ensemble.RelationalGradientBoostingClassifier.max_relationship_depth
max_relationship_depth = max_relationship_depthsklink.ensemble.RelationalGradientBoostingClassifier.max_search_samples
max_search_samples = max_search_samplessklink.ensemble.RelationalGradientBoostingClassifier.min_impurity_decrease
min_impurity_decrease = min_impurity_decreasesklink.ensemble.RelationalGradientBoostingClassifier.min_samples_leaf
min_samples_leaf = min_samples_leafsklink.ensemble.RelationalGradientBoostingClassifier.min_samples_split
min_samples_split = min_samples_splitsklink.ensemble.RelationalGradientBoostingClassifier.min_weight_fraction_leaf
min_weight_fraction_leaf = min_weight_fraction_leafsklink.ensemble.RelationalGradientBoostingClassifier.n_estimators
n_estimators = n_estimatorssklink.ensemble.RelationalGradientBoostingClassifier.n_iter_no_change
n_iter_no_change = n_iter_no_changesklink.ensemble.RelationalGradientBoostingClassifier.predict
predict(X: Any) -> np.ndarrayMost probable class.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- y (
ndarray of shape (n_samples,)): Predicted class labels.
sklink.ensemble.RelationalGradientBoostingClassifier.predict_log_proba
predict_log_proba(X: Any) -> np.ndarrayLogarithm of the class probabilities.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- log_proba (
ndarray of shape (n_samples, n_classes)): Log probability of each class, in the order ofclasses_.
sklink.ensemble.RelationalGradientBoostingClassifier.predict_proba
predict_proba(X: Any) -> np.ndarrayClass probabilities.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- proba (
ndarray of shape (n_samples, n_classes)): Probability of each class, in the order ofclasses_.
sklink.ensemble.RelationalGradientBoostingClassifier.primitives
primitives = primitivessklink.ensemble.RelationalGradientBoostingClassifier.random_state
random_state = random_statesklink.ensemble.RelationalGradientBoostingClassifier.record_candidates
record_candidates = record_candidatessklink.ensemble.RelationalGradientBoostingClassifier.schema_
schema_: Schema | Nonesklink.ensemble.RelationalGradientBoostingClassifier.staged_decision_function
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 infit.
Yields:
- score (
ndarray of shape (n_samples,) or (n_samples, n_classes)): Raw scores after each iteration.
sklink.ensemble.RelationalGradientBoostingClassifier.staged_predict
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 infit.
Yields:
- y (
ndarray of shape (n_samples,)): Predicted class labels after each iteration.
sklink.ensemble.RelationalGradientBoostingClassifier.staged_predict_proba
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 infit.
Yields:
- proba (
ndarray of shape (n_samples, n_classes)): Class probabilities after each iteration.
sklink.ensemble.RelationalGradientBoostingClassifier.subsample
subsample = subsamplesklink.ensemble.RelationalGradientBoostingClassifier.time
time = timesklink.ensemble.RelationalGradientBoostingClassifier.tol
tol = tolsklink.ensemble.RelationalGradientBoostingClassifier.validation_fraction
validation_fraction = validation_fractionsklink.ensemble.RelationalGradientBoostingClassifier.verbose
verbose = verbosesklink.ensemble.RelationalGradientBoostingRegressor
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) -> NoneBases: RegressorMixin, BaseRelationalGradientBoosting
Gradient boosting of relational decision trees for regression.
Each iteration fits a 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 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, Tune gradient boosting, Case study: forecasts with intervals
Parameters:
- database (
Database): Related tables.Nonegives a standard boosting model onX. - entity (
str): Table whose rows are the samples; required with a database. - key (
(str, int or sequence)): Column(s) ofXholding the entity key. - time (
str or int): Column ofXwith the cutoff of each sample;Noneis static. - loss (
(squared_error, absolute_error, huber, quantile)): Loss to optimize."huber"is quadratic below thealpha-quantile of the absolute residuals of each iteration and linear above it;"quantile"predicts thealpha-quantile. - learning_rate (
float): Shrinkage of the contribution of each tree. - n_estimators (
int): Number of boosting iterations. - subsample (
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"allowsl2_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 or float): Minimum number of samples to split a node. - min_samples_leaf (
int or float): Minimum number of samples in each leaf. - min_weight_fraction_leaf (
float): Minimum fraction of the total sample weight in each leaf. - max_depth (
int or None): Maximum depth of each tree. - min_impurity_decrease (
float): A node is split only if the weighted impurity decrease reaches this. - max_features (
(int, float, {sqrt, log2} or None)): Number of candidate groups tried at each node (see the tree). - max_leaf_nodes (
int): Grow each tree best-first with at most this many leaves. - l2_regularization (
float): L2 penalty on the leaf values: each leaf takessum(w * r) / (sum(w) + l2)of the residualsrof its samples, splits maximize the matching gain, and a node splits only when that gain is positive.l2counts in sample weight, as in XGBoost, LightGBM andHistGradientBoostingRegressor: integer weights count as repeated rows, and scaling all the weights bycneedsc * l2for the same model. Only with the squared error andcriterion="newton". The Numba kernels score the penalized splits too (see thetree_kernelsoption ofsklink.set_config). - alpha (
float): Quantile of the"quantile"loss, and quantile of the absolute residuals where the"huber"loss turns linear. In(0, 1). - validation_fraction (
float): Fraction of the rows set aside to decide early stopping; used only whenn_iter_no_changeis set. - n_iter_no_change (
int): Stop when the validation loss has not improved bytolin this many iterations.Nonefitsn_estimatorsiterations on all rows. - tol (
float): Minimum improvement of the validation loss for early stopping. - max_relationship_depth (
int): Maximum number of relationship hops of a path. - max_lookup_depth (
int): Maximum number of lookups (many-to-one steps after the last table of a path, not counted bymax_relationship_depth) from the rows a path aggregates to the columns its conditions read and that are aggregated without conditions, such asmean(orders.order_items.products.price)(see the tree). - primitives (
"default" or sequence of str): Primitives of the unconditioned aggregates. - max_conditions (
int): Conditions learned inside an aggregate: 0, 1 or 2. With 2, the second condition is searched for the best first one, such ascount(orders[amount > 100.0 & type == 'express']); 1 fits faster. - condition_penalty (
float): Gain each learned condition must pay before it is chosen: this value times the gain one condition makes by chance at the node (the node impurity for the Gini index and the squared error, a constant for the entropy, times the mean sample weight per row) and the log of the number of conditions its path offers. The best of many conditions gains by chance alone, so this Bonferroni-style correction keeps conditions that only fit noise out of small nodes; a question whose conditions do not pay for themselves is not asked. Improvements and importances stay the impurity decrease itself. Higher values prefer aggregates without conditions on small or noisy data;0disables it. - max_search_samples (
int or None): Samples on which a node searches its aggregates with learned conditions. A node with more samples searches them on this many, drawn at random once per tree, with the leaf limits scaled to that share, then scores the best few on all its samples, so that the condition search costs the same at any size of the data. Withrecord_candidates, such a node records only those few among the questions with learned conditions. Lower values fit faster on large data;Nonesearches on all samples. - leaf_weights (
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, unlessmax_featuresleaves 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 payingcondition_penaltylike a learned condition. Such a question is aLeafSum, asmean_weights(orders: +0.4 [type == 'pickup'] -0.1 [type in ('economy', 'express', 'standard')]). - max_bins (
int): Thresholds per base feature. - max_condition_bins (
int): Candidate cuts per numeric condition column before refinement. - max_categories (
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 inRelationalDecisionTreeRegressor, ranked for each tree by the mean residual (negative gradient) of its iteration. - record_candidates (
int): Number of best questions each tree keeps for each split node, intree_.candidatesof its estimator, forSearchDisplay(see the tree).0keeps none. - allow_reverse_paths (
bool): Allow paths that read rows of other entities through shared tables. - handle_unknown_entity (
(error, empty)): What to do with keys that are not in the entity table. - random_state (
(int, RandomState or None)): Controlssubsample, the sampling ofmax_features, the samples drawn formax_search_samplesand the early-stopping split. - verbose (
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): 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 withn_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 ofX: the unnormalized importances of the trees, averaged and normalized to sum to one, as in scikit-learn's gradient boosting. - expression_importances_ (
dict): Importance per canonical expression name, computed in the same way, in decreasing order. - schema_ (
Schema or None): Part of the database schema the model reads. - visibility_ (
Visibility): Visibility rules used during fit. - n_features_in_ (
int): Number of columns ofX. - feature_names_in_ (
ndarray of shape (n_features_in_,)): Column names ofXwhen it has them.
See Also
sklink.ensemble.RelationalRandomForestRegressor : Averages deep trees grown independently on bootstrap samples.
Notes
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.
References
J. H. Friedman, "Greedy function approximation: a gradient boosting machine", Annals of Statistics 29(5), 2001.
Examples:
>>> 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: Leaf index of every sample in every tree.
- fit: Fit the boosted trees.
- predict: Predicted values.
- staged_predict: Predicted values after each iteration.
sklink.ensemble.RelationalGradientBoostingRegressor.allow_reverse_paths
allow_reverse_paths = allow_reverse_pathssklink.ensemble.RelationalGradientBoostingRegressor.alpha
alpha = alphasklink.ensemble.RelationalGradientBoostingRegressor.apply
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 infit.
Returns:
- X_leaves (
ndarray of shape (n_samples, n_estimators_)): Leaf of each sample in each tree, assklearn.ensemble.GradientBoostingRegressor.applyreturns it.
sklink.ensemble.RelationalGradientBoostingRegressor.condition_penalty
condition_penalty = condition_penaltysklink.ensemble.RelationalGradientBoostingRegressor.criterion
criterion = criterionsklink.ensemble.RelationalGradientBoostingRegressor.database
database = databasesklink.ensemble.RelationalGradientBoostingRegressor.entity
entity = entitysklink.ensemble.RelationalGradientBoostingRegressor.fit
fit(X: Any, y: Any, sample_weight: Any = None) -> SelfFit 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 inX; integer weights are equivalent to repeated rows.
Returns:
- self (
RelationalGradientBoostingRegressor): Fitted estimator.
sklink.ensemble.RelationalGradientBoostingRegressor.handle_unknown_entity
handle_unknown_entity = handle_unknown_entitysklink.ensemble.RelationalGradientBoostingRegressor.key
key = keysklink.ensemble.RelationalGradientBoostingRegressor.l2_regularization
l2_regularization = l2_regularizationsklink.ensemble.RelationalGradientBoostingRegressor.leaf_weights
leaf_weights = leaf_weightssklink.ensemble.RelationalGradientBoostingRegressor.learning_rate
learning_rate = learning_ratesklink.ensemble.RelationalGradientBoostingRegressor.loss
loss = losssklink.ensemble.RelationalGradientBoostingRegressor.max_bins
max_bins = max_binssklink.ensemble.RelationalGradientBoostingRegressor.max_categories
max_categories = max_categoriessklink.ensemble.RelationalGradientBoostingRegressor.max_condition_bins
max_condition_bins = max_condition_binssklink.ensemble.RelationalGradientBoostingRegressor.max_conditions
max_conditions = max_conditionssklink.ensemble.RelationalGradientBoostingRegressor.max_depth
max_depth = max_depthsklink.ensemble.RelationalGradientBoostingRegressor.max_features
max_features = max_featuressklink.ensemble.RelationalGradientBoostingRegressor.max_leaf_nodes
max_leaf_nodes = max_leaf_nodessklink.ensemble.RelationalGradientBoostingRegressor.max_lookup_depth
max_lookup_depth = max_lookup_depthsklink.ensemble.RelationalGradientBoostingRegressor.max_relationship_depth
max_relationship_depth = max_relationship_depthsklink.ensemble.RelationalGradientBoostingRegressor.max_search_samples
max_search_samples = max_search_samplessklink.ensemble.RelationalGradientBoostingRegressor.min_impurity_decrease
min_impurity_decrease = min_impurity_decreasesklink.ensemble.RelationalGradientBoostingRegressor.min_samples_leaf
min_samples_leaf = min_samples_leafsklink.ensemble.RelationalGradientBoostingRegressor.min_samples_split
min_samples_split = min_samples_splitsklink.ensemble.RelationalGradientBoostingRegressor.min_weight_fraction_leaf
min_weight_fraction_leaf = min_weight_fraction_leafsklink.ensemble.RelationalGradientBoostingRegressor.n_estimators
n_estimators = n_estimatorssklink.ensemble.RelationalGradientBoostingRegressor.n_iter_no_change
n_iter_no_change = n_iter_no_changesklink.ensemble.RelationalGradientBoostingRegressor.predict
predict(X: Any) -> np.ndarrayPredicted values.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- y (
ndarray of shape (n_samples,)): Predicted values.
sklink.ensemble.RelationalGradientBoostingRegressor.primitives
primitives = primitivessklink.ensemble.RelationalGradientBoostingRegressor.random_state
random_state = random_statesklink.ensemble.RelationalGradientBoostingRegressor.record_candidates
record_candidates = record_candidatessklink.ensemble.RelationalGradientBoostingRegressor.schema_
schema_: Schema | Nonesklink.ensemble.RelationalGradientBoostingRegressor.staged_predict
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 infit.
Yields:
- y (
ndarray of shape (n_samples,)): Predicted values after each iteration.
sklink.ensemble.RelationalGradientBoostingRegressor.subsample
subsample = subsamplesklink.ensemble.RelationalGradientBoostingRegressor.time
time = timesklink.ensemble.RelationalGradientBoostingRegressor.tol
tol = tolsklink.ensemble.RelationalGradientBoostingRegressor.validation_fraction
validation_fraction = validation_fractionsklink.ensemble.RelationalGradientBoostingRegressor.verbose
verbose = verbosesklink.ensemble.RelationalIsolationForest
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) -> NoneBases: OutlierMixin, VersionedStateMixin, BaseEstimator
Isolation forest that finds unusual entities from their related rows.
Each sample (a row of X) is described by the relational features of 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 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, Case study: segments and anomalies
Parameters:
- database (
Database): Related tables.Noneuses the columns ofXalone. - entity (
str): Table whose rows are the samples; required with a database. - key (
(str, int or sequence)): Column(s) ofXholding the entity key. - time (
str or int): Column ofXwith the cutoff of each sample;Noneis static. With a cutoff, a sample is described only by rows before it. - n_estimators (
int): Number of isolation trees. - max_samples (
(auto, int or float)): Samples drawn to grow each tree:"auto"ismin(256, n_samples), an int that many and a float that fraction (seesklearn.ensemble.IsolationForest). - contamination (
auto or float): Expected share of outliers, which sets the threshold ofpredict."auto"uses the threshold of the original paper. - max_features (
int or float): Features drawn to grow each tree, an int or a fraction of the standardized features. - bootstrap (
bool): Draw the samples of each tree with replacement. - n_jobs (
int): Trees grown in parallel (seesklearn.ensemble.IsolationForest). - max_relationship_depth (
int): Maximum number of relationships followed from the entity table. - max_lookup_depth (
int): Maximum number of lookups (many-to-one steps after the last table of a path, not counted bymax_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 asmean(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): Also aggregate numeric columns over the rows of each frequent category, asRelationalFeaturizerdoes 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): Number of most frequent categories per categorical column that get their owncountandproportionfeatures. - 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): Allow paths that read rows of other entities through shared tables. - handle_unknown_entity (
(error, empty)): What to do with keys ofXmissing from the entity table. - random_state (
(int, RandomState or None)): Controls the samples and splits of every tree.
Attributes:
- isolation_forest_ (
IsolationForest): Fitted forest on the embedding, whose columns are named byembedding_feature_names_. - offset_ (
float): Offset that turnsscore_samplesintodecision_function. - featurizer_ (
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 or None): Part of the database schema the model reads. - visibility_ (
Visibility): Visibility rules used during fit. - n_features_in_ (
int): Number of columns ofX. - feature_names_in_ (
ndarray of str): Column names ofX, when it has them.
See Also
sklink.cluster.RelationalKMeans : Groups of similar entities, on the same features.
Notes
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.
References
F. T. Liu, K. M. Ting and Z.-H. Zhou, "Isolation forest", IEEE International Conference on Data Mining, 2008.
Examples:
>>> 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: Score of every row of
Xshifted byoffset_: negative for outliers. - fit: Grow the isolation trees.
- predict: Whether every row of
Xis an inlier (1) or an outlier (-1). - score_samples: Anomaly score of every row of
X: the lower, the more abnormal.
sklink.ensemble.RelationalIsolationForest.allow_reverse_paths
allow_reverse_paths = allow_reverse_pathssklink.ensemble.RelationalIsolationForest.bootstrap
bootstrap = bootstrapsklink.ensemble.RelationalIsolationForest.conditional
conditional = conditionalsklink.ensemble.RelationalIsolationForest.contamination
contamination = contaminationsklink.ensemble.RelationalIsolationForest.database
database = databasesklink.ensemble.RelationalIsolationForest.decision_function
decision_function(X: Any) -> np.ndarrayScore 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 infit.
Returns:
- scores (
ndarray of shape (n_samples,)):score_samples(X) - offset_.
sklink.ensemble.RelationalIsolationForest.entity
entity = entitysklink.ensemble.RelationalIsolationForest.exclude
exclude = excludesklink.ensemble.RelationalIsolationForest.fit
fit(X: Any, y: Any = None, sample_weight: Any = None) -> SelfGrow 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 insklearn.ensemble.IsolationForest, the probability that a tree draws the row. Withoutbootstrap, a tree that draws every row (such as withmax_samples="auto"and at most 256 rows of positive weight) ignores the weights, andcontaminationcounts rows, not weights. A row of weight zero learns nothing, as if it were not inX.
Returns:
- self (
RelationalIsolationForest): Fitted estimator.
sklink.ensemble.RelationalIsolationForest.handle_unknown_entity
handle_unknown_entity = handle_unknown_entitysklink.ensemble.RelationalIsolationForest.include
include = includesklink.ensemble.RelationalIsolationForest.key
key = keysklink.ensemble.RelationalIsolationForest.max_categories
max_categories = max_categoriessklink.ensemble.RelationalIsolationForest.max_features
max_features = max_featuressklink.ensemble.RelationalIsolationForest.max_lookup_depth
max_lookup_depth = max_lookup_depthsklink.ensemble.RelationalIsolationForest.max_relationship_depth
max_relationship_depth = max_relationship_depthsklink.ensemble.RelationalIsolationForest.max_samples
max_samples = max_samplessklink.ensemble.RelationalIsolationForest.n_estimators
n_estimators = n_estimatorssklink.ensemble.RelationalIsolationForest.n_jobs
n_jobs = n_jobssklink.ensemble.RelationalIsolationForest.predict
predict(X: Any) -> np.ndarrayWhether 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 infit.
Returns:
- labels (
ndarray of shape (n_samples,)):-1wheredecision_functionis negative,1elsewhere.
sklink.ensemble.RelationalIsolationForest.primitives
primitives = primitivessklink.ensemble.RelationalIsolationForest.random_state
random_state = random_statesklink.ensemble.RelationalIsolationForest.score_samples
score_samples(X: Any) -> np.ndarrayAnomaly 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 infit.
Returns:
- scores (
ndarray of shape (n_samples,)): Opposite of the anomaly score of the original paper.
sklink.ensemble.RelationalIsolationForest.time
time = timesklink.ensemble.RelationalIsolationForest.windows
windows = windowssklink.ensemble.RelationalRandomForestClassifier
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) -> NoneBases: ClassifierMixin, BaseRelationalForest
Random forest of relational decision tree classifiers.
Each tree is a 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, Tune trees and forests
Parameters:
- database (
Database): Related tables.Nonegives a standard forest onX. - entity (
str): Table whose rows are the samples; required with a database. - key (
(str, int or sequence)): Column(s) ofXholding the entity key. - time (
str or int): Column ofXwith the cutoff of each sample;Noneis static. - n_estimators (
int): Number of trees. - criterion (
(gini, entropy, log_loss)): Impurity measure. - max_depth (
int): Maximum depth of each tree. - min_samples_split (
int or float): Minimum number of samples to split a node. - min_samples_leaf (
int or float): Minimum number of samples in each leaf. - min_weight_fraction_leaf (
float): Minimum fraction of the total sample weight in each leaf. - max_features (
(int, float, {sqrt, log2} or None)): Number of candidate groups tried at each node (see the tree). - max_leaf_nodes (
int): Grow each tree best-first with at most this many leaves. - min_impurity_decrease (
float): A node is split only if the weighted impurity decrease reaches this. - bootstrap (
bool): Draw a bootstrap sample of the rows ofXfor each tree. Rows are drawn with probability proportional tosample_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. WithFalseevery tree sees every row with its weight. - max_samples (
int or float): Size of each bootstrap sample: all rows whenNone, that many draws for an int (it may exceed the number of rows), and that fraction of the number of rows, or of the totalsample_weightwhen it is given, for a float. - oob_score (
bool or callable): Score the forest on the rows each tree did not draw. A callable is called asscore(y_true, y_pred). - class_weight (
(dict, balanced, balanced_subsample or None)): Weights of the classes;"balanced_subsample"recomputes them for each bootstrap sample. - max_relationship_depth (
int): Maximum number of relationship hops of a path. - max_lookup_depth (
int): Maximum number of lookups (many-to-one steps after the last table of a path) from the rows a path aggregates to the columns its conditions read, such asproportion(orders.order_items[products.category == 'toys']). These lookups start wheremax_relationship_depthstops and do not count as hops of it. The columns of the looked-up tables are also aggregated without conditions, such asmean(orders.order_items.products.price).0keeps conditions and aggregates on the last table of the path. A numeric column of a looked-up table getsmax(2, max_condition_bins // 4)candidate cuts. - primitives (
"default" or sequence of str): Primitives of the unconditioned aggregates. - max_conditions (
int): Conditions learned inside an aggregate: 0, 1 or 2. With 2, the second condition is searched for the best few first ones, such ascount(orders[amount > 100.0 & type == 'express']); 1 fits about twice as fast. - condition_penalty (
float): Gain each learned condition must pay before it is chosen: this value times the gain one condition makes by chance at the node (the node impurity for the Gini index and the squared error, a constant for the entropy, times the mean sample weight per row) and the log of the number of conditions its path offers. The best of many conditions gains by chance alone, so this Bonferroni-style correction keeps conditions that only fit noise out of small nodes; a question whose conditions do not pay for themselves is not asked. Improvements and importances stay the impurity decrease itself. Higher values prefer aggregates without conditions on small or noisy data;0disables it. - max_search_samples (
int or None): Samples on which a node searches its aggregates with learned conditions. A node with more samples searches them on this many, drawn at random once per tree, with the leaf limits scaled to that share, then scores the best few on all its samples, so that the condition search costs the same at any size of the data. Withrecord_candidates, such a node records only those few among the questions with learned conditions.Nonesearches on all samples. - max_bins (
int): Thresholds per base feature. - max_condition_bins (
int): Candidate cuts per numeric condition column before refinement; a quarter of it, at least 2, for a column of a looked-up table (seemax_lookup_depth). - max_categories (
int): Most frequent categories tried in==conditions. In regression and binary classification, a column with more categories also gets conditions on sets of categories ranked by the mean target, as inRelationalDecisionTreeClassifier. 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): Number of best questions each tree keeps for each split node, intree_.candidatesof its estimator (see the tree).0keeps none. - allow_reverse_paths (
bool): Allow paths that read rows of other entities through shared tables. - handle_unknown_entity (
(error, empty)): What to do with keys that are not in the entity table. - n_jobs (
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, RandomState or None)): Controls bootstrapping, the sampling ofmax_featuresand the samples drawn formax_search_samples. - verbose (
int): Verbosity of the parallel loop.
Attributes:
- estimators_ (
list of RelationalDecisionTreeClassifier): Fitted trees:n_estimatorsof them, unless a callback stopped the fit (see Notes). - estimators_samples_ (
list of ndarray): Indices of the rows ofXdrawn 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): 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 ofX. - expression_importances_ (
dict): Importance per canonical expression name, averaged over the trees and normalized to sum to one, in decreasing order. - oob_score_ (
float): Out-of-bag accuracy (or the given score); only withoob_score. - oob_decision_function_ (
ndarray of shape (n_samples, n_classes)): Out-of-bag class probabilities; only withoob_score. - schema_ (
Schema or None): Part of the database schema the model reads. - visibility_ (
Visibility): Visibility rules used during fit. - n_features_in_ (
int): Number of columns ofX. - feature_names_in_ (
ndarray of shape (n_features_in_,)): Column names ofXwhen it has them.
See Also
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.
Notes
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. 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:
>>> 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: Leaf index of every sample in every tree.
- fit: Grow the trees.
- predict: Class with the highest mean probability.
- predict_log_proba: Logarithm of
predict_proba. - predict_proba: Mean class probabilities of the trees.
sklink.ensemble.RelationalRandomForestClassifier.allow_reverse_paths
allow_reverse_paths = allow_reverse_pathssklink.ensemble.RelationalRandomForestClassifier.apply
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 infit.
Returns:
- X_leaves (
ndarray of shape (n_samples, n_estimators)): Leaf of each sample in each tree.
sklink.ensemble.RelationalRandomForestClassifier.bootstrap
bootstrap = bootstrapsklink.ensemble.RelationalRandomForestClassifier.class_weight
class_weight = class_weightsklink.ensemble.RelationalRandomForestClassifier.condition_penalty
condition_penalty = condition_penaltysklink.ensemble.RelationalRandomForestClassifier.criterion
criterion = criterionsklink.ensemble.RelationalRandomForestClassifier.database
database = databasesklink.ensemble.RelationalRandomForestClassifier.entity
entity = entitysklink.ensemble.RelationalRandomForestClassifier.estimators_samples_
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
fit(X: Any, y: Any, sample_weight: Any = None) -> SelfGrow 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. Withbootstrap=Truethey 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 inX.
Returns:
- self (
RelationalRandomForestClassifier): Fitted estimator.
sklink.ensemble.RelationalRandomForestClassifier.handle_unknown_entity
handle_unknown_entity = handle_unknown_entitysklink.ensemble.RelationalRandomForestClassifier.key
key = keysklink.ensemble.RelationalRandomForestClassifier.max_bins
max_bins = max_binssklink.ensemble.RelationalRandomForestClassifier.max_categories
max_categories = max_categoriessklink.ensemble.RelationalRandomForestClassifier.max_condition_bins
max_condition_bins = max_condition_binssklink.ensemble.RelationalRandomForestClassifier.max_conditions
max_conditions = max_conditionssklink.ensemble.RelationalRandomForestClassifier.max_depth
max_depth = max_depthsklink.ensemble.RelationalRandomForestClassifier.max_features
max_features = max_featuressklink.ensemble.RelationalRandomForestClassifier.max_leaf_nodes
max_leaf_nodes = max_leaf_nodessklink.ensemble.RelationalRandomForestClassifier.max_lookup_depth
max_lookup_depth = max_lookup_depthsklink.ensemble.RelationalRandomForestClassifier.max_relationship_depth
max_relationship_depth = max_relationship_depthsklink.ensemble.RelationalRandomForestClassifier.max_samples
max_samples = max_samplessklink.ensemble.RelationalRandomForestClassifier.max_search_samples
max_search_samples = max_search_samplessklink.ensemble.RelationalRandomForestClassifier.min_impurity_decrease
min_impurity_decrease = min_impurity_decreasesklink.ensemble.RelationalRandomForestClassifier.min_samples_leaf
min_samples_leaf = min_samples_leafsklink.ensemble.RelationalRandomForestClassifier.min_samples_split
min_samples_split = min_samples_splitsklink.ensemble.RelationalRandomForestClassifier.min_weight_fraction_leaf
min_weight_fraction_leaf = min_weight_fraction_leafsklink.ensemble.RelationalRandomForestClassifier.n_estimators
n_estimators = n_estimatorssklink.ensemble.RelationalRandomForestClassifier.n_jobs
n_jobs = n_jobssklink.ensemble.RelationalRandomForestClassifier.oob_score
oob_score = oob_scoresklink.ensemble.RelationalRandomForestClassifier.predict
predict(X: Any) -> np.ndarrayClass with the highest mean probability.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- y_pred (
ndarray of shape (n_samples,)): Predicted labels.
sklink.ensemble.RelationalRandomForestClassifier.predict_log_proba
predict_log_proba(X: Any) -> np.ndarrayLogarithm of predict_proba.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- log_proba (
ndarray of shape (n_samples, n_classes)): Columns in the order ofclasses_.
sklink.ensemble.RelationalRandomForestClassifier.predict_proba
predict_proba(X: Any) -> np.ndarrayMean class probabilities of the trees.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- proba (
ndarray of shape (n_samples, n_classes)): Columns in the order ofclasses_.
sklink.ensemble.RelationalRandomForestClassifier.primitives
primitives = primitivessklink.ensemble.RelationalRandomForestClassifier.random_state
random_state = random_statesklink.ensemble.RelationalRandomForestClassifier.record_candidates
record_candidates = record_candidatessklink.ensemble.RelationalRandomForestClassifier.schema_
schema_: Schema | Nonesklink.ensemble.RelationalRandomForestClassifier.time
time = timesklink.ensemble.RelationalRandomForestClassifier.verbose
verbose = verbosesklink.ensemble.RelationalRandomForestRegressor
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) -> NoneBases: RegressorMixin, 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, Tune trees and forests
Parameters:
- database (
Database): Related tables.Nonegives a standard forest onX. - entity (
str): Table whose rows are the samples; required with a database. - key (
(str, int or sequence)): Column(s) ofXholding the entity key. - time (
str or int): Column ofXwith the cutoff of each sample;Noneis static. - n_estimators (
int): Number of trees. - criterion (
squared_error): Impurity measure. - max_depth (
int): Maximum depth of each tree. - min_samples_split (
int or float): Minimum number of samples to split a node. - min_samples_leaf (
int or float): Minimum number of samples in each leaf. - min_weight_fraction_leaf (
float): Minimum fraction of the total sample weight in each leaf. - max_features (
(int, float, {sqrt, log2} or None)): Number of candidate groups tried at each node. - max_leaf_nodes (
int): Grow each tree best-first with at most this many leaves. - min_impurity_decrease (
float): A node is split only if the weighted impurity decrease reaches this. - bootstrap (
bool): Draw a bootstrap sample of the rows ofXfor each tree. Rows are drawn with probability proportional tosample_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. WithFalseevery tree sees every row with its weight. - max_samples (
int or float): Size of each bootstrap sample: all rows whenNone, that many draws for an int (it may exceed the number of rows), and that fraction of the number of rows, or of the totalsample_weightwhen it is given, for a float. - oob_score (
bool or callable): Score the forest (R², or the given score) on the rows each tree did not draw. - max_relationship_depth (
int): Maximum number of relationship hops of a path. - max_lookup_depth (
int): Maximum number of lookups (many-to-one steps after the last table of a path) from the rows a path aggregates to the columns its conditions read, such asproportion(orders.order_items[products.category == 'toys']). These lookups start wheremax_relationship_depthstops and do not count as hops of it. The columns of the looked-up tables are also aggregated without conditions, such asmean(orders.order_items.products.price).0keeps conditions and aggregates on the last table of the path. A numeric column of a looked-up table getsmax(2, max_condition_bins // 4)candidate cuts. - primitives (
"default" or sequence of str): Primitives of the unconditioned aggregates. - max_conditions (
int): Conditions learned inside an aggregate: 0, 1 or 2. With 2, the second condition is searched for the best few first ones, such ascount(orders[amount > 100.0 & type == 'express']); 1 fits about twice as fast. - condition_penalty (
float): Gain each learned condition must pay before it is chosen: this value times the gain one condition makes by chance at the node (the node impurity for the Gini index and the squared error, a constant for the entropy, times the mean sample weight per row) and the log of the number of conditions its path offers. The best of many conditions gains by chance alone, so this Bonferroni-style correction keeps conditions that only fit noise out of small nodes; a question whose conditions do not pay for themselves is not asked. Improvements and importances stay the impurity decrease itself. Higher values prefer aggregates without conditions on small or noisy data;0disables it. - max_search_samples (
int or None): Samples on which a node searches its aggregates with learned conditions. A node with more samples searches them on this many, drawn at random once per tree, with the leaf limits scaled to that share, then scores the best few on all its samples, so that the condition search costs the same at any size of the data. Withrecord_candidates, such a node records only those few among the questions with learned conditions.Nonesearches on all samples. - max_bins (
int): Thresholds per base feature. - max_condition_bins (
int): Candidate cuts per numeric condition column before refinement; a quarter of it, at least 2, for a column of a looked-up table (seemax_lookup_depth). - max_categories (
int): Most frequent categories tried in==conditions. In regression and binary classification, a column with more categories also gets conditions on sets of categories ranked by the mean target, as inRelationalDecisionTreeClassifier. 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): Number of best questions each tree keeps for each split node, intree_.candidatesof its estimator (see the tree).0keeps none. - allow_reverse_paths (
bool): Allow paths that read rows of other entities through shared tables. - handle_unknown_entity (
(error, empty)): What to do with keys that are not in the entity table. - n_jobs (
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, RandomState or None)): Controls bootstrapping, the sampling ofmax_featuresand the samples drawn formax_search_samples. - verbose (
int): Verbosity of the parallel loop.
Attributes:
- estimators_ (
list of RelationalDecisionTreeRegressor): Fitted trees:n_estimatorsof them, unless a callback stopped the fit (see Notes). - estimators_samples_ (
list of ndarray): Indices of the rows ofXdrawn 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 ofX. - expression_importances_ (
dict): Importance per canonical expression name, averaged over the trees and normalized to sum to one, in decreasing order. - oob_score_ (
float): Out-of-bag R² (or the given score); only withoob_score. - oob_prediction_ (
ndarray of shape (n_samples,)): Out-of-bag predictions; only withoob_score. - schema_ (
Schema or None): Part of the database schema the model reads. - visibility_ (
Visibility): Visibility rules used during fit. - n_features_in_ (
int): Number of columns ofX. - feature_names_in_ (
ndarray of shape (n_features_in_,)): Column names ofXwhen it has them.
See Also
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.
Notes
With scikit-learn 1.9 or later, set_callbacks follows the fit tree by tree, as described for RelationalRandomForestClassifier.
Examples:
>>> 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: Leaf index of every sample in every tree.
- fit: Grow the trees.
- predict: Mean prediction of the trees.
sklink.ensemble.RelationalRandomForestRegressor.allow_reverse_paths
allow_reverse_paths = allow_reverse_pathssklink.ensemble.RelationalRandomForestRegressor.apply
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 infit.
Returns:
- X_leaves (
ndarray of shape (n_samples, n_estimators)): Leaf of each sample in each tree.
sklink.ensemble.RelationalRandomForestRegressor.bootstrap
bootstrap = bootstrapsklink.ensemble.RelationalRandomForestRegressor.condition_penalty
condition_penalty = condition_penaltysklink.ensemble.RelationalRandomForestRegressor.criterion
criterion = criterionsklink.ensemble.RelationalRandomForestRegressor.database
database = databasesklink.ensemble.RelationalRandomForestRegressor.entity
entity = entitysklink.ensemble.RelationalRandomForestRegressor.estimators_samples_
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
fit(X: Any, y: Any, sample_weight: Any = None) -> SelfGrow 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. Withbootstrap=Truethey 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 inX.
Returns:
- self (
RelationalRandomForestRegressor): Fitted estimator.
sklink.ensemble.RelationalRandomForestRegressor.handle_unknown_entity
handle_unknown_entity = handle_unknown_entitysklink.ensemble.RelationalRandomForestRegressor.key
key = keysklink.ensemble.RelationalRandomForestRegressor.max_bins
max_bins = max_binssklink.ensemble.RelationalRandomForestRegressor.max_categories
max_categories = max_categoriessklink.ensemble.RelationalRandomForestRegressor.max_condition_bins
max_condition_bins = max_condition_binssklink.ensemble.RelationalRandomForestRegressor.max_conditions
max_conditions = max_conditionssklink.ensemble.RelationalRandomForestRegressor.max_depth
max_depth = max_depthsklink.ensemble.RelationalRandomForestRegressor.max_features
max_features = max_featuressklink.ensemble.RelationalRandomForestRegressor.max_leaf_nodes
max_leaf_nodes = max_leaf_nodessklink.ensemble.RelationalRandomForestRegressor.max_lookup_depth
max_lookup_depth = max_lookup_depthsklink.ensemble.RelationalRandomForestRegressor.max_relationship_depth
max_relationship_depth = max_relationship_depthsklink.ensemble.RelationalRandomForestRegressor.max_samples
max_samples = max_samplessklink.ensemble.RelationalRandomForestRegressor.max_search_samples
max_search_samples = max_search_samplessklink.ensemble.RelationalRandomForestRegressor.min_impurity_decrease
min_impurity_decrease = min_impurity_decreasesklink.ensemble.RelationalRandomForestRegressor.min_samples_leaf
min_samples_leaf = min_samples_leafsklink.ensemble.RelationalRandomForestRegressor.min_samples_split
min_samples_split = min_samples_splitsklink.ensemble.RelationalRandomForestRegressor.min_weight_fraction_leaf
min_weight_fraction_leaf = min_weight_fraction_leafsklink.ensemble.RelationalRandomForestRegressor.n_estimators
n_estimators = n_estimatorssklink.ensemble.RelationalRandomForestRegressor.n_jobs
n_jobs = n_jobssklink.ensemble.RelationalRandomForestRegressor.oob_score
oob_score = oob_scoresklink.ensemble.RelationalRandomForestRegressor.predict
predict(X: Any) -> np.ndarrayMean prediction of the trees.
Parameters:
- X (
DataFrame or array-like of shape (n_samples, n_columns)): Population table with the same columns as infit.
Returns:
- y_pred (
ndarray of shape (n_samples,)): Predicted values.
sklink.ensemble.RelationalRandomForestRegressor.primitives
primitives = primitivessklink.ensemble.RelationalRandomForestRegressor.random_state
random_state = random_statesklink.ensemble.RelationalRandomForestRegressor.record_candidates
record_candidates = record_candidatessklink.ensemble.RelationalRandomForestRegressor.schema_
schema_: Schema | Nonesklink.ensemble.RelationalRandomForestRegressor.time
time = timesklink.ensemble.RelationalRandomForestRegressor.verbose
verbose = verbose