KNeighborsClassifier#
- class skfda.ml.classification.KNeighborsClassifier(*, n_neighbors: int = 5, weights: typing_extensions.Literal[uniform, distance] | Callable[[ndarray[Any, dtype[float64]]], ndarray[Any, dtype[float64]]] = 'uniform', algorithm: typing_extensions.Literal[auto, ball_tree, kd_tree, brute] = 'auto', leaf_size: int = 30, metric: typing_extensions.Literal[precomputed], n_jobs: int | None = None)[source]#
- class skfda.ml.classification.KNeighborsClassifier(*, n_neighbors: int = 5, weights: typing_extensions.Literal[uniform, distance] | Callable[[ndarray[Any, dtype[float64]]], ndarray[Any, dtype[float64]]] = 'uniform', algorithm: typing_extensions.Literal[auto, ball_tree, kd_tree, brute] = 'auto', leaf_size: int = 30, n_jobs: int | None = None)
- class skfda.ml.classification.KNeighborsClassifier(*, n_neighbors: int = 5, weights: typing_extensions.Literal[uniform, distance] | Callable[[ndarray[Any, dtype[float64]]], ndarray[Any, dtype[float64]]] = 'uniform', algorithm: typing_extensions.Literal[auto, ball_tree, kd_tree, brute] = 'auto', leaf_size: int = 30, metric: Metric[Input] = l2_distance, n_jobs: int | None = None)
Classifier implementing the k-nearest neighbors vote.
- Parameters:
n_neighbors (int) – Number of neighbors to use by default for
kneighbors()
queries.weights (WeightsType) –
Weight function used in prediction. Possible values:
’uniform’: uniform weights. All points in each neighborhood are weighted equally.
’distance’: weight points by the inverse of their distance. in this case, closer neighbors of a query point will have a greater influence than neighbors which are further away.
[callable]: a user-defined function which accepts an array of distances, and returns an array of the same shape containing the weights.
algorithm (AlgorithmType) –
Algorithm used to compute the nearest neighbors:
’ball_tree’ will use
sklearn.neighbors.BallTree
.’brute’ will use a brute-force search.
’auto’ will attempt to decide the most appropriate algorithm based on the values passed to
fit()
method.
leaf_size (int) – Leaf size passed to BallTree or KDTree. 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.
metric (Literal['precomputed'] | Metric[Input]) – The distance metric to use for the tree. The default metric is the L2 distance. See the documentation of the metrics module for a list of available metrics.
n_jobs (int | None) – The number of parallel jobs to run for neighbors search.
None
means 1 unless in ajoblib.parallel_backend
context.-1
means using all processors. Doesn’t affectfit()
method.
Examples
Firstly, we will create a toy dataset with 2 classes
>>> from skfda.datasets import make_sinusoidal_process >>> fd1 = make_sinusoidal_process(phase_std=.25, random_state=0) >>> fd2 = make_sinusoidal_process(phase_mean=1.8, error_std=0., ... phase_std=.25, random_state=0) >>> fd = fd1.concatenate(fd2) >>> y = 15*[0] + 15*[1]
We will fit a K-Nearest Neighbors classifier
>>> from skfda.ml.classification import KNeighborsClassifier >>> neigh = KNeighborsClassifier() >>> neigh.fit(fd, y) KNeighborsClassifier(...)
We can predict the class of new samples
>>> neigh.predict(fd[::2]) # Predict labels for even samples array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1])
And the estimated probabilities.
>>> neigh.predict_proba(fd[0]) # Probabilities of sample 0 array([[ 1., 0.]])
See also
RadiusNeighborsClassifier
NearestCentroid
KNeighborsRegressor
RadiusNeighborsRegressor
NearestNeighbors
Notes
See Nearest Neighbors in the sklearn online documentation for a discussion of the choice of
algorithm
andleaf_size
.This class wraps the sklearn classifier sklearn.neighbors.KNeighborsClassifier.
Warning
Regarding the Nearest Neighbors algorithms, if it is found that two neighbors, neighbor k+1 and k, have identical distances but different labels, the results will depend on the ordering of the training data.
Methods
fit
(X, y)Fit the model using X as training data and y as responses.
Get metadata routing of this object.
get_params
([deep])Get parameters for this estimator.
kneighbors
([X, n_neighbors, return_distance])Find the K-neighbors of a point.
kneighbors_graph
([X, n_neighbors, mode])Compute the (weighted) graph of k-Neighbors for points in X.
predict
(X)Predict the class labels for the provided data.
Calculate probability estimates for the test data X.
score
(X, y[, sample_weight])Return the mean accuracy on the given test data and labels.
set_params
(**params)Set the parameters of this estimator.
set_score_request
(*[, sample_weight])Request metadata passed to the
score
method.- fit(X, y)[source]#
Fit the model using X as training data and y as responses.
- Parameters:
X (Input) – Training data. FDataGrid with the training data or array matrix with shape [n_samples, n_samples] if metric=’precomputed’.
y (TargetClassification) – Training data. FData with the training respones (functional response case) or array matrix with length n_samples in the multivariate response case.
self (SelfTypeClassifier) –
- Returns:
Self.
- Return type:
SelfTypeClassifier
Note
This method adds the attribute classes_ to the classifier.
- get_metadata_routing()#
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
routing – A
MetadataRequest
encapsulating routing information.- Return type:
MetadataRequest
- get_params(deep=True)#
Get parameters for this estimator.
- kneighbors(X=None, n_neighbors=None, *, return_distance=True)[source]#
Find the K-neighbors of a point.
Returns indices of and distances to the neighbors of each point.
- Parameters:
X (Input | None) – FDatagrid with the query functions or matrix (n_query, n_indexed) if metric == ‘precomputed’. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor.
n_neighbors (int | None) – Number of neighbors to get (default is the value passed to the constructor).
return_distance (bool) – Defaults to True. If False, distances will not be returned.
- Returns:
- array
Array representing the lengths to points, only present if return_distance=True
- indarray
Indices of the nearest points in the population matrix.
- Return type:
dist
Examples
Firstly, we will create a toy dataset.
>>> from skfda.datasets import make_sinusoidal_process >>> fd1 = make_sinusoidal_process(phase_std=.25, random_state=0) >>> fd2 = make_sinusoidal_process(phase_mean=1.8, error_std=0., ... phase_std=.25, random_state=0) >>> fd = fd1.concatenate(fd2)
We will fit a Nearest Neighbors estimator
>>> from skfda.ml.clustering import NearestNeighbors >>> neigh = NearestNeighbors() >>> neigh.fit(fd) NearestNeighbors(...)
Now we can query the k-nearest neighbors.
>>> distances, index = neigh.kneighbors(fd[:2]) >>> index # Index of k-neighbors of samples 0 and 1 array([[ 0, 7, 6, 11, 2],...)
>>> distances.round(2) # Distances to k-neighbors array([[ 0. , 0.28, 0.29, 0.29, 0.3 ], [ 0. , 0.27, 0.28, 0.29, 0.3 ]])
Notes
This method wraps the corresponding sklearn routine in the module
sklearn.neighbors
.
- kneighbors_graph(X=None, n_neighbors=None, mode='connectivity')[source]#
Compute the (weighted) graph of k-Neighbors for points in X.
- Parameters:
X (Input | None) – FDatagrid with the query functions or matrix (n_query, n_indexed) if metric == ‘precomputed’. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor.
n_neighbors (int | None) – Number of neighbors to get (default is the value passed to the constructor).
mode (Literal['connectivity', 'distance']) – Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are distance between points.
- Returns:
Sparse matrix in CSR format, shape = [n_samples, n_samples_fit] n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j.
- Return type:
csr_matrix
Examples
Firstly, we will create a toy dataset.
>>> from skfda.datasets import make_sinusoidal_process >>> fd1 = make_sinusoidal_process(phase_std=.25, random_state=0) >>> fd2 = make_sinusoidal_process(phase_mean=1.8, error_std=0., ... phase_std=.25, random_state=0) >>> fd = fd1.concatenate(fd2)
We will fit a Nearest Neighbors estimator.
>>> from skfda.ml.clustering import NearestNeighbors >>> neigh = NearestNeighbors() >>> neigh.fit(fd) NearestNeighbors(...)
Now we can obtain the graph of k-neighbors of a sample.
>>> graph = neigh.kneighbors_graph(fd[0]) >>> print(graph) (0, 0) 1.0 (0, 7) 1.0 (0, 6) 1.0 (0, 11) 1.0 (0, 2) 1.0
Notes
This method wraps the corresponding sklearn routine in the module
sklearn.neighbors
.
- predict(X)[source]#
Predict the class labels for the provided data.
- Parameters:
X (Input) – Test samples or array (n_query, n_indexed) if metric == ‘precomputed’.
- Returns:
Array of shape [n_samples] or [n_samples, n_outputs] with class labels for each data sample.
- Return type:
TargetClassification
Notes
This method wraps the corresponding sklearn routine in the module
sklearn.neighbors
.
- score(X, y, sample_weight=None)[source]#
Return the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Test samples.
y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True labels for X.
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.
- Returns:
score – Mean accuracy of
self.predict(X)
w.r.t. y.- Return type:
- 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:
**params (dict) – Estimator parameters.
- Returns:
self – Estimator instance.
- Return type:
estimator instance
- set_score_request(*, sample_weight='$UNCHANGED$')#
Request metadata passed to the
score
method.Note that this method is only relevant if
enable_metadata_routing=True
(seesklearn.set_config()
). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True
: metadata is requested, and passed toscore
if 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.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline
. Otherwise it has no effect.- Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
sample_weight
parameter inscore
.self (KNeighborsClassifier) –
- Returns:
self – The updated object.
- Return type:
Examples using skfda.ml.classification.KNeighborsClassifier
#
K-nearest neighbors classification
Voice signals: smoothing, registration, and classification