KNeighborsLabelRanker#
- class sklr.neighbors.KNeighborsLabelRanker(n_neighbors: int = 5, *, model: Literal['mallows', 'plackett_luce'] = 'mallows', weights: Literal['uniform', 'distance', 'dudani'] | Callable[[ndarray], ndarray] | None = 'uniform', algorithm: Literal['auto', 'ball_tree', 'kd_tree', 'brute'] = 'auto', leaf_size: int = 30, p: float = 2, metric: str | Callable = 'minkowski', metric_params: dict | None = None, max_iter: int | None = None, tol: float = 1e-06, n_jobs: int | None = None)#
Label ranker based on the k-nearest neighbors.
The ranking predicted for a sample is the mode of a probability model of the rankings, the Mallows or the Plackett-Luce model, estimated from the rankings of its
n_neighborsnearest neighbors in the training set, as in the instance-based label rankers of [cheng_decision_2009] and [cheng_label_2010]. The training rankings may be incomplete, and the neighbors may be weighted by their distance to the sample.Read more in the User Guide.
- Parameters:
- n_neighborsint, default=5
Number of neighbors of each sample, used by
predict()and by default bykneighbors().- model{“mallows”, “plackett_luce”}, default=”mallows”
Probability model of the rankings of the neighbors. With
"mallows", the predicted ranking is the center ranking of the Mallows model, found by the weighted Borda count, and by Algorithm 1 of [cheng_decision_2009] when some neighbors have incomplete rankings. With"plackett_luce", the predicted ranking sorts the labels by decreasing parameter of the Plackett-Luce model, whose maximum likelihood estimate is found by the MM algorithm of [hunter_mm_2004]. In both cases, ties between labels go to the one with the smaller index.- weights{“uniform”, “distance”, “dudani”}, callable or None, default=”uniform”
Weight function of the neighbors. With
"uniform", all the neighbors of a sample weigh the same. With"distance", each neighbor weighs the inverse of its distance to the sample, and if some neighbors are at zero distance, only they weigh. With"dudani", the weights follow the rule of [dudani_distance_1976] used by [cheng_decision_2009], which decreases linearly from one for the nearest neighbor to zero for the farthest one, and gives one to all the neighbors if they are at the same distance. A callable receives an array of distances and returns an array of the same shape with non-negative weights.Nonemeans"uniform".With
model="mallows", the weight of each neighbor is also multiplied by the fraction of the labels that its ranking ranks. If all the neighbors of a sample weigh zero, they are weighted by that fraction alone withmodel="mallows", and equally withmodel="plackett_luce"or if that fraction is also zero.- algorithm{“auto”, “ball_tree”, “kd_tree”, “brute”}, default=”auto”
Algorithm used to compute the nearest neighbors, which are found with a
BallTreewith"ball_tree", with aKDTreewith"kd_tree"and by brute force with"brute"."auto"chooses the most appropriate algorithm from the data passed tofit(). Fitting on sparse input always uses brute force, and warns if another algorithm than"auto"or"brute"was chosen.- leaf_sizeint, default=30
Leaf size passed to
BallTreeorKDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.- pfloat, default=2
Power parameter for the Minkowski metric.
p=1gives the Manhattan distance andp=2the Euclidean distance. It must be positive.- metricstr, DistanceMetric object or callable, default=”minkowski”
Metric to use for distance computation. The default,
"minkowski", gives the Euclidean distance withp=2. See the documentation ofscipy.spatial.distanceand the metrics listed insklearn.metrics.pairwise.distance_metrics()for valid metric values.If
metricis"precomputed",Xis assumed to be a distance matrix and must be square infit().Xmay be a sparse graph, in which case only its nonzero elements may be considered neighbors.If
metricis a callable, it takes two one-dimensional arrays that represent two samples and returns their distance.- metric_paramsdict, default=None
Additional keyword arguments for the metric function.
Nonemeans no additional arguments.- max_iterint, default=None
Maximum number of iterations of the estimation of the model of each sample.
Nonemeans100withmodel="mallows"and1000withmodel="plackett_luce". Withmodel="mallows", the estimation only iterates when some neighbor has an incomplete ranking. AConvergenceWarningis issued if some estimation does not converge, which is common withmodel="plackett_luce"when the rankings of the neighbors agree, because the maximum likelihood estimate does not exist.- tolfloat, default=1e-6
Tolerance of the estimation of the Plackett-Luce model, which stops when no parameter changes by more than
tol. Ignored withmodel="mallows".- n_jobsint, default=None
Number of parallel jobs to run for the neighbors search and the estimation of the models.
Nonemeans 1 unless in ajoblib.parallel_backendcontext.-1means using all processors. See Glossary for more details.
- Attributes:
- effective_metric_str or callable
Distance metric used. It is the same as the
metricparameter or a synonym of it, such as"euclidean"ifmetricis"minkowski"andpis2.- effective_metric_params_dict
Additional keyword arguments for the metric function. For most metrics, it is the same as the
metric_paramsparameter, but it may also contain the value ofpifeffective_metric_is"minkowski".- 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_samples_fit_int
Number of samples in the fitted data.
See also
KNeighborsPartialLabelRankerPartial label ranker based on the k-nearest neighbors.
sklearn.neighbors.KNeighborsClassifierClassifier implementing the k-nearest neighbors vote.
sklearn.neighbors.KNeighborsRegressorRegression based on k-nearest neighbors.
sklearn.neighbors.NearestNeighborsUnsupervised learner for implementing neighbor searches.
Notes
Let \(d_{(1)} \leq \dots \leq d_{(k)}\) be the sorted distances \(d(\boldsymbol{x}, \boldsymbol{x}_i)\) of the \(k\) nearest neighbors \(\boldsymbol{x}_1, \dots, \boldsymbol{x}_k\) of an instance \(\boldsymbol{x}\), numbered from the nearest one, whose rankings are \(\sigma_1, \dots, \sigma_k\). With
weights="distance", the weight of the \(i\)-th nearest neighbor is \(w_i = 1 / d_{(i)}\), and withweights="dudani"it is\[w_i = \frac{d_{(k)} - d_{(i)}}{d_{(k)} - d_{(1)}},\]or
1if \(d_{(k)} = d_{(1)}\), as in equation (1) of [dudani_distance_1976]. Withmodel="mallows", the weight is multiplied by the fraction \(|\mathcal{Y}(\sigma_i)| / n\) of the \(n\) labels ranked by \(\sigma_i\), where \(\mathcal{Y}(\sigma_i)\) is the set of labels that it ranks, because Algorithm 1 of [cheng_decision_2009] completes the incomplete rankings, and a completed ranking is less reliable than an observed one. The Plackett-Luce model does not complete the rankings, since the probability of an incomplete ranking has a closed form [cheng_label_2010], so its weights are not multiplied by that fraction.See Nearest Neighbors in the user guide of scikit-learn for a discussion of the choice of
algorithmandleaf_size. If the \(k\)-th and the \((k + 1)\)-th nearest neighbors of a sample are at the same distance but have different rankings, the prediction depends on the order of the training data.References
[cheng_decision_2009] (1,2,3,4)W. Cheng, J. Hühn and E. Hüllermeier, “Decision tree and instance-based learning for label ranking”, in Proceedings of the 26th International Conference on Machine Learning, Montreal, Canada, pp. 161-168, 2009.
[cheng_label_2010] (1,2)W. Cheng, K. Dembczyński and E. Hüllermeier, “Label ranking methods based on the Plackett-Luce model”, in Proceedings of the 27th International Conference on Machine Learning, Haifa, Israel, pp. 215-222, 2010.
[dudani_distance_1976] (1,2)S. A. Dudani, “The distance-weighted k-nearest-neighbor rule”, IEEE Transactions on Systems, Man, and Cybernetics, vol. SMC-6, no. 4, pp. 325-327, 1976.
[hunter_mm_2004]D. R. Hunter, “MM algorithms for generalized Bradley-Terry models”, The Annals of Statistics, vol. 32, no. 1, pp. 384-406, 2004.
Examples
>>> from sklr.neighbors import KNeighborsLabelRanker >>> X = [[0], [1], [2], [3]] >>> y = [[1, 2, 3], [2, 1, 3], [1, 2, 3], [3, 1, 2]] >>> ranker = KNeighborsLabelRanker(n_neighbors=3) >>> ranker.fit(X, y) KNeighborsLabelRanker(n_neighbors=3) >>> ranker.predict([[1.1], [2.2]]) array([[1, 2, 3], [2, 1, 3]])
With the weights of Dudani, the nearest neighbor of each sample weighs more:
>>> ranker = KNeighborsLabelRanker(n_neighbors=3, weights="dudani").fit(X, y) >>> ranker.predict([[1.1], [2.2]]) array([[2, 1, 3], [1, 2, 3]])
- fit(X: ArrayLike, y: ArrayLike) Self#
Fit the k-nearest neighbors label ranker from the training dataset.
- Parameters:
- X{array-like, sparse matrix} of shape (n_samples, n_features) or (n_samples, n_samples) if metric=”precomputed”
Training data.
- yarray-like of shape (n_samples, n_labels)
Training rankings, as described in Ranking representation, possibly incomplete but without ties.
- 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.
- kneighbors(X=None, n_neighbors=None, return_distance=True)#
Find the K-neighbors of a point.
Returns indices of and distances to the neighbors of each point.
- Parameters:
- X{array-like, sparse matrix}, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None
The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor.
- n_neighborsint, default=None
Number of neighbors required for each sample. The default is the value passed to the constructor.
- return_distancebool, default=True
Whether or not to return the distances.
- Returns:
- neigh_distndarray of shape (n_queries, n_neighbors)
Array representing the lengths to points, only present if return_distance=True.
- neigh_indndarray of shape (n_queries, n_neighbors)
Indices of the nearest points in the population matrix.
Examples
In the following example, we construct a NearestNeighbors class from an array representing our data set and ask who’s the closest point to [1,1,1]
>>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=1) >>> neigh.fit(samples) NearestNeighbors(n_neighbors=1) >>> print(neigh.kneighbors([[1., 1., 1.]])) (array([[0.5]]), array([[2]]))
As you can see, it returns [[0.5]], and [[2]], which means that the element is at distance 0.5 and is the third element of samples (indexes start at 0). You can also query for multiple points:
>>> X = [[0., 1., 0.], [1., 0., 1.]] >>> neigh.kneighbors(X, return_distance=False) array([[1], [2]]...)
- kneighbors_graph(X=None, n_neighbors=None, mode='connectivity')#
Compute the (weighted) graph of k-Neighbors for points in X.
- Parameters:
- X{array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’, default=None
The query point or points. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor. For
metric='precomputed'the shape should be (n_queries, n_indexed). Otherwise the shape should be (n_queries, n_features).- n_neighborsint, default=None
Number of neighbors for each sample. The default is the value passed to the constructor.
- mode{‘connectivity’, ‘distance’}, default=’connectivity’
Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are distances between points, type of distance depends on the selected metric parameter in NearestNeighbors class.
- Returns:
- Asparse-matrix of shape (n_queries, n_samples_fit)
n_samples_fitis the number of samples in the fitted data.A[i, j]gives the weight of the edge connectingitoj. The matrix is of CSR format.
See also
NearestNeighbors.radius_neighbors_graphCompute the (weighted) graph of Neighbors for points in X.
Examples
>>> X = [[0], [3], [1]] >>> from sklearn.neighbors import NearestNeighbors >>> neigh = NearestNeighbors(n_neighbors=2) >>> neigh.fit(X) NearestNeighbors(n_neighbors=2) >>> A = neigh.kneighbors_graph(X) >>> A.toarray() array([[1., 0., 1.], [0., 1., 1.], [1., 0., 1.]])
- predict(X: ArrayLike | None) ndarray#
Predict the rankings for the provided data.
- Parameters:
- X{array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric=”precomputed”, or None
Test samples. If
None, the rankings of the training samples are predicted, and no training sample is its own neighbor.
- Returns:
- yndarray of shape (n_queries, 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_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$') KNeighborsLabelRanker#
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.