LabelwiseLabelRanker#
- class sklr.reduction.LabelwiseLabelRanker(estimator: object | None = None, *, loss: Literal['absolute_error', 'squared_error'] = 'absolute_error', n_jobs: int | None = None)#
Label ranker that learns the position of each label separately.
The labelwise decomposition of [cheng_labelwise_2013] fits, for each label, a probabilistic classifier that predicts the probability of each of its positions, and predicts the ranking that minimizes the expected
lossunder those probabilities, as if the positions of the labels were independent. The training rankings may be incomplete, as if their unranked labels had been removed at random from complete rankings, with the defaultestimatoror any other that implementsfit_likelihood.Read more in the User Guide.
- Parameters:
- estimatorestimator object, default=None
Probabilistic classifier fitted to the positions of each label, from
1to the number of labels, which implements fit and predict_proba. The positions are ordered, so an ordinal classifier suits them best.Nonemeans the ordinal logistic regression of [cheng_labelwise_2013].To learn from incomplete rankings, the estimator also has to implement
fit_likelihood(X, likelihood, classes, sample_weight=None), as the default one does, which is then used instead offitfor all the training rankings.likelihood[i, k]is the probability of what is observed of sampleiif its class isclasses[k], and the method maximizes the sum over the samples of the logarithm oflikelihood[i] @ proba[i], weighted bysample_weight, whereproba[i]holds the probabilities of the classes of sampleithat predict_proba predicts afterwards. It returns the fitted estimator, withclasses_set toclasses, which are the positions of the label. An estimator withoutfit_likelihoodonly accepts complete rankings, and predicts a zero probability for the positions that a label never takes in them. Ifsample_weightis given, the method that fits the estimator has to support it.- loss{“absolute_error”, “squared_error”}, default=”absolute_error”
Loss between the true and the predicted position of each label, summed over the labels, whose expected value the predicted ranking minimizes.
"absolute_error"is the absolute difference, whose sum is an affine transformation of Spearman’s footrule, and the ranking solves an assignment problem."squared_error"is the squared difference, whose sum is an affine transformation of Spearman’s \(\rho\), and the ranking sorts the labels by increasing expected position. In both cases, among the rankings of minimum expected loss, the predicted one gives the smallest position to the first label, then to the second one, and so on.- n_jobsint, default=None
Number of jobs to run in parallel to fit the estimators of the labels.
Nonemeans 1 unless in ajoblib.parallel_backendcontext.-1means using all processors. See Glossary for more details.
- Attributes:
- estimators_list of estimator objects or None
Estimator fitted to the positions of each label, or
Nonefor a label that no training ranking of positive weight ranks together with another label, whose positions are predicted as equally likely.- 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.
See also
PairwiseLabelRankerLabel ranker that learns the preference between each pair of labels.
sklr.neighbors.KNeighborsLabelRankerLabel ranker based on the k-nearest neighbors.
sklr.tree.DecisionTreeLabelRankerA decision tree label ranker.
sklearn.multioutput.MultiOutputClassifierMulti target classification by fitting one classifier per target.
Notes
The estimator of each label \(y_j\) predicts the probability \(P_j(r \mid \boldsymbol{x})\) that its position is \(r\), for \(r = 1, \dots, n\), given an instance \(\boldsymbol{x}\). The expected loss of putting \(y_j\) at position \(r\) is
\[L_j(r) = \sum_{r'=1}^n \ell(r', r) P_j(r' \mid \boldsymbol{x}),\]with \(\ell(r', r) = |r' - r|\) for
loss="absolute_error"and \(\ell(r', r) = (r' - r)^2\) forloss="squared_error", and the predicted ranking is\[\hat\pi = \arg\min_{\pi \in \Omega} \sum_{j=1}^n L_j(\pi(j)),\]where \(\Omega\) is the set of the rankings of the \(n\) labels. It is an assignment of the labels to the positions [cheng_labelwise_2013]. With the absolute difference, it is solved by
scipy.optimize.linear_sum_assignment(). With the squared difference, \(\sum_{j=1}^n \pi(j)^2\) is the same for all the permutations, so \(\hat\pi\) sorts the labels by increasing expected position \(\sum_{r=1}^n r P_j(r \mid \boldsymbol{x})\).The default estimator is the cumulative logit model of equation (20) of [cheng_labelwise_2013], whose coefficients have the \(L_2\) penalty of
LogisticRegressionwith its default strength, and whose thresholds are not penalized. Its likelihood is maximized by L-BFGS-B, andfit()issues aConvergenceWarningif it does not converge within100iterations.An incomplete ranking \(\sigma\) only ranks a subset \(\mathcal{Y}(\sigma) \subseteq \mathcal{Y}\) of the labels, with \(m = |\mathcal{Y}(\sigma)| \leq n\) labels, and if the other \(n - m\) labels were removed at random from a complete ranking, the probability of observing a ranked label \(y_j\) at position \(\sigma(j)\) is
\[\sum_{r=\sigma(j)}^{\sigma(j) + n - m} P_j(r \mid \boldsymbol{x}) \frac{\binom{r - 1}{r - \sigma(j)} \binom{n - r}{n - m - r + \sigma(j)}}{\binom{n}{m}},\]equation (16) of [cheng_labelwise_2013]. The fractions of binomial coefficients are the
likelihoodthatfit_likelihoodreceives, so that the model of each label maximizes the weighted log-likelihood of the rankings that rank that label, equation (17) of [cheng_labelwise_2013], which is the usual one for complete rankings. The rankings that do not rank the label, or rank it alone, observe it with the same probability for any model, so they are left out, as are those of zero weight. If no ranking is left for a label,fit()warns with aUserWarning, and the positions of the label are predicted as equally likely.References
Examples
>>> from sklr.reduction import LabelwiseLabelRanker >>> X = [[0], [1], [2], [3]] >>> y = [[1, 2, 3], [2, 1, 3], [1, 2, 3], [3, 1, 2]] >>> ranker = LabelwiseLabelRanker().fit(X, y) >>> ranker.predict([[1.1], [2.2]]) array([[1, 2, 3], [2, 1, 3]])
The training rankings may be incomplete, with
np.nanfor the unranked labels:>>> import numpy as np >>> y = [[1, 2, np.nan], [2, 1, 3], [1, np.nan, 2], [3, 1, 2]] >>> ranker = LabelwiseLabelRanker().fit(X, y) >>> ranker.predict([[1.1], [2.2]]) array([[2, 1, 3], [2, 1, 3]])
- fit(X: ArrayLike, y: ArrayLike, sample_weight: ArrayLike | None = None) Self#
Fit an estimator to the positions of each label.
- Parameters:
- Xarray-like of shape (n_samples, n_features)
Training data.
- yarray-like of shape (n_samples, n_labels)
Training rankings, as described in Ranking representation, without ties, and incomplete only if
estimatorimplementsfit_likelihood, as the default one does.- sample_weightarray-like of shape (n_samples,), default=None
Sample weights, non-negative.
Nonemeans that all the samples weigh the same.
- Returns:
- selfobject
Fitted estimator.
- 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_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) ndarray#
Predict the rankings of the samples.
- Parameters:
- Xarray-like of shape (n_samples, n_features)
Test samples.
- 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$') LabelwiseLabelRanker#
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$') LabelwiseLabelRanker#
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.