DecisionTreePartialLabelRanker#

class sklr.tree.DecisionTreePartialLabelRanker(*, criterion: Literal['disagreements', 'distance', 'entropy', 'gini'] = 'entropy', 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)#

A decision tree partial label ranker.

The tree is grown as in [alfaro_learning_2021]: each split is the threshold on a feature that best separates the partial rankings of the samples of a node, measured on each pair of labels by how much the rankings of each child disagree on it, and each leaf predicts the consensus bucket order of its rankings, found by the Bucket Pivot Algorithm of [aledo_utopia_2017]. The training rankings may have ties and be incomplete.

Read more in the User Guide.

Parameters:
criterion{“disagreements”, “distance”, “entropy”, “gini”}, default=”entropy”

The function to measure the quality of a split. "disagreements" adds up, over the pairs of labels, the fraction of the rankings that order the pair unlike the consensus of the node, "distance" weighs those that reverse the pair twice as much as those that only tie or untie it, and "entropy" and "gini" average the entropy and the Gini index of the relations of the pairs in the rankings. The impurity is zero when the rankings of the node 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 than min_samples_split samples.

min_samples_splitint or float, default=2

The minimum number of samples required to split an internal node. If int, then consider min_samples_split as the minimum number. If float, then min_samples_split is a fraction and ceil(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_leaf training samples in each of the left and right branches. If int, then consider min_samples_leaf as the minimum number. If float, then min_samples_leaf is a fraction and ceil(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_weight is 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_features features at each split. If float, then max_features is a fraction and max(1, int(max_features * n_features_in_)) features are considered at each split. If "sqrt", then max_features=sqrt(n_features). If "log2", then max_features=log2(n_features). If None, then max_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 than max_features features.

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 splitter is set to "best". When max_features < n_features, the algorithm will select max_features at random at each split before finding the best split among them. But the best found split may vary across different runs, even if max_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_state has to be fixed to an integer. See Glossary for details.

max_leaf_nodesint, default=None

Grow a tree with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then 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_alpha will be chosen. By default, no pruning is performed. See Minimal Cost-Complexity Pruning for details.

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 X has 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 value attribute holds the bucket order of each node, with shape (node_count, n_labels, 1). Please refer to help(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

DecisionTreeLabelRanker

A decision tree label ranker.

sklr.neighbors.KNeighborsPartialLabelRanker

Partial label ranker based on the k-nearest neighbors.

Notes

Let \(n\) be the number of labels and, for a node \(t\) and a pair of labels \(y_i\) and \(y_j\) with \(i < j\), let \(p_{ij}\), \(e_{ij}\) and \(p_{ji}\) be the weights of the partial rankings of the node that put \(y_i\) ahead of \(y_j\), tie them and put \(y_j\) ahead of \(y_i\), and \(s_{ij} = p_{ij} + e_{ij} + p_{ji}\). Let also \(\hat\pi_t\) be the consensus bucket order of the node. The impurities, equations (5) to (10) of [alfaro_learning_2021], are as follows, where the sums run over the pairs that some ranking of the node ranks, those with \(s_{ij} > 0\):

\[I_t^{\mathrm{disagreements}} = \sum_{i < j} \frac{\rho_{ij}}{s_{ij}}, \qquad I_t^{\mathrm{distance}} = \sum_{i < j} \frac{\gamma_{ij}}{s_{ij}},\]

where \(\rho_{ij}\) is the weight of the rankings that do not order the pair as \(\hat\pi_t\), which is \(e_{ij} + p_{ji}\), \(p_{ij} + p_{ji}\) or \(p_{ij} + e_{ij}\) when \(\hat\pi_t\) puts \(y_i\) ahead of \(y_j\), ties them or puts \(y_j\) ahead of \(y_i\), and \(\gamma_{ij}\) counts twice those that reverse it, which gives \(e_{ij} + 2 p_{ji}\), \(p_{ij} + p_{ji}\) or \(2 p_{ij} + e_{ij}\), and

\[I_t^{\mathrm{entropy}} = \frac{2}{n (n - 1)} \sum_{i < j} H\left(\frac{p_{ij}}{s_{ij}}, \frac{e_{ij}}{s_{ij}}, \frac{p_{ji}}{s_{ij}}\right), \qquad I_t^{\mathrm{gini}} = \frac{2}{n (n - 1)} \sum_{i < j} G\left(\frac{p_{ij}}{s_{ij}}, \frac{e_{ij}}{s_{ij}}, \frac{p_{ji}}{s_{ij}}\right),\]

where \(H(q_1, q_2, q_3) = -\sum_{r=1}^{3} q_r \log_2 q_r\), with \(0 \log_2 0 = 0\), and \(G(q_1, q_2, q_3) = 1 - \sum_{r=1}^{3} q_r^2\). Equation (9) of [alfaro_learning_2021] averages \(1 - G\) instead, which grows as the rankings agree, so it is read as an erratum. The pairs that no ranking of the node ranks, undefined in [alfaro_learning_2021], add nothing, and the factor of the entropy and the Gini index stays \(2 / (n (n - 1))\).

The impurity is 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 [alfaro_learning_2021]. For "entropy" and "gini" this follows from their definition, but "disagreements" and "distance" would be positive on incomplete consistent rankings that no bucket order agrees with, such as those that put \(y_1\) ahead of \(y_2\), \(y_2\) ahead of \(y_3\) and \(y_3\) ahead of \(y_1\).

The tree chooses the split that minimizes the weighted mean of the impurities of the children, equation (4) of [alfaro_learning_2021], 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_weight is passed, and a node becomes a leaf when that of its best split is below min_impurity_decrease.

The bucket order of each node is the consensus of its rankings found as in KNeighborsPartialLabelRanker: the Bucket Pivot Algorithm \(\mathrm{LIA}_G^{\mathrm{MP2}}\) of [aledo_utopia_2017] with \(\beta = 0.25\), applied to the pair order matrix of the rankings of the node, equation (3) of [alfaro_learning_2021], orders the labels that some of them rank together with another label, and the others are tied in a last bucket.

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

[aledo_utopia_2017] (1,2)

J. A. Aledo, J. A. Gámez and A. Rosete, “Utopia in the solution of the bucket order problem”, Decision Support Systems, vol. 97, pp. 69-80, 2017.

[alfaro_learning_2021] (1,2,3,4,5,6,7)

J. C. Alfaro, J. A. Aledo and J. A. Gámez, “Learning decision trees for the partial label ranking problem”, International Journal of Intelligent Systems, vol. 36, no. 2, pp. 890-918, 2021.

Examples

>>> from sklr.tree import DecisionTreePartialLabelRanker
>>> X = [[0, 1, 0], [1, 0, 1], [1, 1, 0], [0, 1, 0]]
>>> y = [[1, 2, 2], [2, 1, 3], [1, 2, 3], [1, 1, 2]]
>>> ranker = DecisionTreePartialLabelRanker(random_state=0).fit(X, y)
>>> ranker.predict([[0, 1, 0], [1, 1, 0]])
array([[1, 1, 2],
       [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.float32 and if a sparse matrix is provided to a sparse csr_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.float32 and if a sparse matrix is provided to a sparse csc_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_pathBunch

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.

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.float32 and if a sparse matrix is provided to a sparse csr_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 partial 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.float32 and if a sparse matrix is provided to a sparse csc_matrix.

yarray-like of shape (n_samples, n_labels)

Training partial rankings, as described in Ranking representation, possibly with ties and incomplete.

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 MetadataRequest encapsulating 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 bucket orders 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.float32 and if a sparse matrix is provided to a sparse csr_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 bucket orders, complete and possibly with ties, as the positions of the labels.

score(X: ArrayLike, y: ArrayLike, sample_weight: ArrayLike | None = None) → float#

Return the mean \(\tau_x\) coefficient on the given data.

It is computed with tau_x_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 possibly with ties.

sample_weightarray-like of shape (n_samples,), default=None

Sample weights.

Returns:
scorefloat

Mean \(\tau_x\) of self.predict(X) with respect to y.

set_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$') → DecisionTreePartialLabelRanker#

Configure whether metadata should be requested to be passed to the fit method.

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 (see sklearn.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 to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • 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_weight parameter in fit.

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$') → DecisionTreePartialLabelRanker#

Configure whether metadata should be requested to be passed to the score method.

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 (see sklearn.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 to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • 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_weight parameter in score.

Returns:
selfobject

The updated object.