DecisionTreeLabelRanker#
- class sklr.tree.DecisionTreeLabelRanker(*, criterion: Literal['mallows'] = 'mallows', splitter: Literal['best', 'random'] = 'best', max_depth: int | None = None, min_samples_split: float = 2, min_samples_leaf: float = 1, min_weight_fraction_leaf: float = 0.0, max_features: float | Literal['sqrt', 'log2'] | None = None, random_state: int | RandomState | None = None, max_leaf_nodes: int | None = None, min_impurity_decrease: float = 0.0, ccp_alpha: float = 0.0, max_iter: int = 100)#
A decision tree label ranker.
The tree is grown as in [cheng_decision_2009]: each split is the threshold on a feature that best separates the rankings of the samples of a node, measured by the spread of the Mallows model of the rankings of each child, and each leaf predicts the center ranking of that model. The training rankings may be incomplete.
Read more in the User Guide.
- Parameters:
- criterion{“mallows”}, default=”mallows”
The function to measure the quality of a split. With
"mallows", the impurity of a node is \(1 / (1 + \hat{\theta})\), where \(\hat{\theta}\) is the estimated spread of the Mallows model of its rankings, and it is zero when its rankings are consistent. See the Notes for details.- splitter{“best”, “random”}, default=”best”
The strategy used to choose the split at each node. Supported strategies are
"best"to choose the best split and"random"to choose the best random split.- max_depthint, default=None
The maximum depth of the tree. If
None, then nodes are expanded until all leaves are pure or until all leaves contain less thanmin_samples_splitsamples.- min_samples_splitint or float, default=2
The minimum number of samples required to split an internal node. If int, then consider
min_samples_splitas the minimum number. If float, thenmin_samples_splitis a fraction andceil(min_samples_split * n_samples)are the minimum number of samples for each split.- min_samples_leafint or float, default=1
The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least
min_samples_leaftraining samples in each of the left and right branches. If int, then considermin_samples_leafas the minimum number. If float, thenmin_samples_leafis a fraction andceil(min_samples_leaf * n_samples)are the minimum number of samples for each node.- min_weight_fraction_leaffloat, default=0.0
The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when
sample_weightis not provided.- max_featuresint, float, {“sqrt”, “log2”} or None, default=None
The number of features to consider when looking for the best split. If int, then consider
max_featuresfeatures at each split. If float, thenmax_featuresis a fraction andmax(1, int(max_features * n_features_in_))features are considered at each split. If"sqrt", thenmax_features=sqrt(n_features). If"log2", thenmax_features=log2(n_features). IfNone, thenmax_features=n_features. The search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more thanmax_featuresfeatures.- random_stateint, RandomState instance or None, default=None
Controls the randomness of the estimator. The features are always randomly permuted at each split, even if
splitteris set to"best". Whenmax_features < n_features, the algorithm will selectmax_featuresat random at each split before finding the best split among them. But the best found split may vary across different runs, even ifmax_features == n_features. That is the case if the improvement of the criterion is identical for several splits and one split has to be selected at random. To obtain a deterministic behaviour during fitting,random_statehas to be fixed to an integer. See Glossary for details.- max_leaf_nodesint, default=None
Grow a tree with
max_leaf_nodesin best-first fashion. Best nodes are defined as relative reduction in impurity. IfNonethen unlimited number of leaf nodes.- min_impurity_decreasefloat, default=0.0
A node will be split if this split induces a decrease of the impurity greater than or equal to this value. See the Notes for the weighted impurity decrease.
- ccp_alphanon-negative float, default=0.0
Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than
ccp_alphawill be chosen. By default, no pruning is performed. See Minimal Cost-Complexity Pruning for details.- max_iterint, default=100
Maximum number of iterations of Algorithm 1 of [cheng_decision_2009], which estimates the center ranking of the Mallows model of each node and only iterates when some of its rankings are incomplete. A
ConvergenceWarningis issued if the center ranking of some node does not converge.
- Attributes:
- max_features_int
The inferred value of
max_features.- n_features_in_int
Number of features seen during fit.
- feature_names_in_ndarray of shape (
n_features_in_,) Names of features seen during fit. Defined only when
Xhas feature names that are all strings.- n_outputs_int
The number of labels when
fit()is performed.feature_importances_ndarray of shape (n_features,)Return the feature importances.
- tree_Tree instance
The underlying Tree object, whose
valueattribute holds the ranking of each node, with shape(node_count, n_labels, 1). Please refer tohelp(sklearn.tree._tree.Tree)for attributes of Tree object and Understanding the decision tree structure in the examples of scikit-learn for basic usage of these attributes.
See also
sklearn.tree.DecisionTreeRegressorA decision tree regressor.
sklr.neighbors.KNeighborsLabelRankerLabel ranker based on the k-nearest neighbors.
Notes
The center ranking \(\pi\) and the spread \(\theta \geq 0\) of the Mallows model of the rankings of a node \(t\) are estimated as in [cheng_decision_2009], by Algorithm 1 and by maximum likelihood, on the labels ranked by some of those rankings, which gives \(\hat{\pi}_t\) and \(\hat{\theta}_t\). The impurity of the node is
\[I_t = \frac{1}{1 + \hat{\theta}_t},\]which is zero when \(\hat{\theta}_t\) is infinite, the case of rankings that agree with \(\hat{\pi}_t\), and one when \(\hat{\theta}_t\) is zero, the case of rankings whose mean Kendall distance to \(\hat{\pi}_t\) is not below that of rankings drawn uniformly at random. It is also zero when the rankings of the node are consistent, that is, when no two of them order a pair of labels differently, so that the node becomes a leaf as in [cheng_decision_2009]. Incomplete rankings may be consistent without agreeing with any center ranking, such as those that put \(y_1\) ahead of \(y_2\), \(y_2\) ahead of \(y_3\) and \(y_3\) ahead of \(y_1\).
[cheng_decision_2009] choose the split that maximizes the weighted mean of the spreads of the children instead, which is infinite whenever a child has a single sample. The tree chooses the split that minimizes the weighted mean of their impurities, as the trees of scikit-learn do. The weighted impurity decrease of a split of a node \(t\) with \(N_t\) of the \(N\) samples into children \(t_L\) and \(t_R\) with \(N_{t_L}\) and \(N_{t_R}\) samples is
\[\frac{N_t}{N} \left(I_t - \frac{N_{t_L}}{N_t} I_{t_L} - \frac{N_{t_R}}{N_t} I_{t_R}\right),\]where all the numbers of samples are weighted if
sample_weightis passed, and a node becomes a leaf when that of its best split is belowmin_impurity_decrease. With the default value, this happens when even the best split increases the impurity, which [cheng_decision_2009] do not consider.The ranking of each node orders the labels ranked by its samples as their center ranking does, and it is completed as in Section 5.2 of [cheng_decision_2009], with its closest extension to the ranking of its parent, so the other labels are ordered as in the closest ancestor that ranks them. The ranking of the root, which only misses the labels never ranked in the training set, is completed with its closest extension to its own Borda count.
The default values for the parameters controlling the size of the trees (e.g.
max_depth,min_samples_leaf, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values.References
Examples
>>> from sklr.tree import DecisionTreeLabelRanker >>> X = [[0, 1, 0], [1, 0, 1], [1, 1, 0], [0, 1, 0]] >>> y = [[1, 2, 3], [2, 1, 3], [1, 2, 3], [3, 1, 2]] >>> ranker = DecisionTreeLabelRanker(random_state=0).fit(X, y) >>> ranker.predict([[0, 1, 0], [1, 1, 0]]) array([[2, 1, 3], [1, 2, 3]])
- apply(X, check_input=True)#
Return the index of the leaf that each sample is predicted as.
Added in version 0.17.
- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to
dtype=np.float32and if a sparse matrix is provided to a sparsecsr_matrix.- check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you’re doing.
- Returns:
- X_leavesarray-like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within
[0; self.tree_.node_count), possibly with gaps in the numbering.
- cost_complexity_pruning_path(X, y, sample_weight=None)#
Compute the pruning path during Minimal Cost-Complexity Pruning.
See Minimal Cost-Complexity Pruning for details on the pruning process.
- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to
dtype=np.float32and if a sparse matrix is provided to a sparsecsc_matrix.- yarray-like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
- sample_weightarray-like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
- Returns:
- ccp_path
Bunch Dictionary-like object, with the following attributes.
- ccp_alphasndarray
Effective alphas of subtree during pruning.
- impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in
ccp_alphas.
- ccp_path
- decision_path(X, check_input=True)#
Return the decision path in the tree.
Added in version 0.18.
- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to
dtype=np.float32and if a sparse matrix is provided to a sparsecsr_matrix.- check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you’re doing.
- Returns:
- indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
- property feature_importances_#
Return the feature importances.
The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance.
Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See
sklearn.inspection.permutation_importance()as an alternative.- Returns:
- feature_importances_ndarray of shape (n_features,)
Normalized total reduction of criteria by feature (Gini importance).
- fit(X: ArrayLike, y: ArrayLike, sample_weight: ArrayLike | None = None) Self#
Build a decision tree label ranker from the training set.
- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to
dtype=np.float32and if a sparse matrix is provided to a sparsecsc_matrix.- yarray-like of shape (n_samples, n_labels)
Training rankings, as described in Ranking representation, possibly incomplete but without ties.
- sample_weightarray-like of shape (n_samples,), default=None
Sample weights, which must be non-negative. If
None, then samples are equally weighted. Samples with zero weight are left out of the nodes.
- Returns:
- selfobject
Fitted estimator.
- get_depth()#
Return the depth of the decision tree.
The depth of a tree is the maximum distance between the root and any leaf.
- Returns:
- self.tree_.max_depthint
The maximum depth of the tree.
- get_metadata_routing()#
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
- routingMetadataRequest
A
MetadataRequestencapsulating routing information.
- get_n_leaves()#
Return the number of leaves of the decision tree.
- Returns:
- self.tree_.n_leavesint
Number of leaves.
- get_params(deep=True)#
Get parameters for this estimator.
- Parameters:
- deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns:
- paramsdict
Parameter names mapped to their values.
- predict(X: ArrayLike, check_input: bool = True) ndarray#
Predict the rankings for the provided data.
- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to
dtype=np.float32and if a sparse matrix is provided to a sparsecsr_matrix.- check_inputbool, default=True
Allow to bypass several input checking. Don’t use this parameter unless you know what you’re doing.
- Returns:
- yndarray of shape (n_samples, n_labels)
Predicted rankings, complete and without ties, as the positions of the labels.
- score(X: ArrayLike, y: ArrayLike, sample_weight: ArrayLike | None = None) float#
Return the mean Kendall’s \(\tau\) on the given data.
It is computed with
kendall_tau_score().- Parameters:
- Xarray-like of shape (n_samples, n_features)
Test samples.
- yarray-like of shape (n_samples, n_labels)
True rankings for
X, complete and without ties.- sample_weightarray-like of shape (n_samples,), default=None
Sample weights.
- Returns:
- scorefloat
Mean Kendall’s \(\tau\) of
self.predict(X)with respect toy.
- set_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$') DecisionTreeLabelRanker#
Configure whether metadata should be requested to be passed to the
fitmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.
- Parameters:
- sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
sample_weightparameter infit.
- Returns:
- selfobject
The updated object.
- set_params(**params)#
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as
Pipeline). The latter have parameters of the form<component>__<parameter>so that it’s possible to update each component of a nested object.- Parameters:
- **paramsdict
Estimator parameters.
- Returns:
- selfestimator instance
Estimator instance.
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') DecisionTreeLabelRanker#
Configure whether metadata should be requested to be passed to the
scoremethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed toscoreif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it toscore.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.
- Parameters:
- sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
sample_weightparameter inscore.
- Returns:
- selfobject
The updated object.