KNeighborsPartialLabelRanker#
- class sklr.neighbors.KNeighborsPartialLabelRanker(n_neighbors: int = 5, *, 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, n_jobs: int | None = None)#
Partial label ranker based on the k-nearest neighbors.
The bucket order predicted for a sample is the consensus of the partial rankings of its
n_neighborsnearest neighbors in the training set, found by the Bucket Pivot Algorithm of [aledo_utopia_2017], as in the instance-based partial label ranker of [alfaro_learning_2021]. The training rankings may have ties and 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().- 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], 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". If all the neighbors of a sample weigh zero, they are weighted equally.- 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.- n_jobsint, default=None
Number of parallel jobs to run for the neighbors search and the consensus of the neighbors.
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
KNeighborsLabelRankerLabel ranker based on the k-nearest neighbors.
sklearn.neighbors.KNeighborsClassifierClassifier implementing the k-nearest neighbors vote.
sklearn.neighbors.NearestNeighborsUnsupervised learner for implementing neighbor searches.
Notes
Let \(\sigma_1, \dots, \sigma_k\) be the partial rankings of the \(k\) nearest neighbors of an instance \(\boldsymbol{x}\), with weights \(w_1, \dots, w_k\) computed from their distances to \(\boldsymbol{x}\) as described in
weights. Unlike inKNeighborsLabelRankerwithmodel="mallows", the weights are not multiplied by the fraction of the labels that each ranking ranks, since the consensus does not complete the rankings. For each pair of labels \(y_i\) and \(y_j\), the entry \(C(y_i, y_j)\) of the pair order matrix is the weighted fraction of the rankings ranking both labels that put \(y_i\) ahead of \(y_j\), with a ranking that ties them counting one half, as in equation (3) of [alfaro_learning_2021]. The predicted bucket order \(\hat\pi\) is the solution that the Bucket Pivot Algorithm with the least indecision assumption, global DANI indices and two-stage multiple pivots, \(\mathrm{LIA}_G^{\mathrm{MP2}}\) in [aledo_utopia_2017], gives for this matrix, with the threshold \(\beta = 0.25\). When several labels could be the pivot, the one with the smaller index is chosen, so the prediction is deterministic.Only the labels that some neighbor of positive weight ranks together with another label are ordered, and \(C(y_i, y_j)\) is one half for two of them that no such neighbor ranks together. The other labels are tied in a last bucket, since nothing is known about how they compare with the rest, and if no such neighbor ranks two labels, all the labels are tied.
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
[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)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.
[dudani_distance_1976]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.
Examples
>>> from sklr.neighbors import KNeighborsPartialLabelRanker >>> X = [[0], [1], [2], [3]] >>> y = [[1, 2, 2], [1, 1, 2], [1, 2, 3], [2, 1, 3]] >>> ranker = KNeighborsPartialLabelRanker(n_neighbors=3) >>> ranker.fit(X, y) KNeighborsPartialLabelRanker(n_neighbors=3) >>> ranker.predict([[0.9], [2.2]]) array([[1, 2, 3], [1, 1, 2]])
With the weights of Dudani, the nearest neighbor of each sample weighs more:
>>> ranker = KNeighborsPartialLabelRanker(n_neighbors=3, weights="dudani") >>> ranker.fit(X, y).predict([[0.9], [2.2]]) array([[1, 1, 2], [1, 1, 2]])
- fit(X: ArrayLike, y: ArrayLike) Self#
Fit the k-nearest neighbors partial 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 with ties and incomplete.
- 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 bucket orders 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 bucket orders of the training samples are predicted, and no training sample is its own neighbor.
- Returns:
- yndarray of shape (n_queries, 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 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$') KNeighborsPartialLabelRanker#
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.
Gallery examples#
Partial label ranking with the k-nearest neighbors