KNeighborsRegressor#
- class skfda.ml.regression.KNeighborsRegressor(*, 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.regression.KNeighborsRegressor(*, 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.regression.KNeighborsRegressor(*, 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)
Regression based on k-nearest neighbors.
Regression with scalar, multivariate or functional response.
The target is predicted by local interpolation of the targets associated of the nearest neighbors in the training set.
- 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 gaussian-like samples shifted.
>>> from skfda.ml.regression import KNeighborsRegressor >>> from skfda.datasets import make_multimodal_samples >>> from skfda.datasets import make_multimodal_landmarks >>> y = make_multimodal_landmarks( ... n_samples=30, ... std=0.5, ... random_state=0, ... ) >>> y_train = y.flatten() >>> X_train = make_multimodal_samples( ... n_samples=30, ... std=0.5, ... random_state=0, ... ) >>> X_test = make_multimodal_samples( ... n_samples=5, ... std=0.05, ... random_state=0, ... )
We will fit a K-Nearest Neighbors regressor to regress a scalar response.
>>> neigh = KNeighborsRegressor() >>> neigh.fit(X_train, y_train) KNeighborsRegressor(...)
We can predict the modes of new samples
>>> neigh.predict(X_test).round(2) # Predict test data array([ 0.38, 0.14, 0.27, 0.52, 0.38])
Now we will create a functional response to train the model
>>> y_train = 5 * X_train + 1 >>> y_train FDataGrid(...)
We train the estimator with the functional response
>>> neigh.fit(X_train, y_train) KNeighborsRegressor(...)
And predict the responses as in the first case.
>>> neigh.predict(X_test) FDataGrid(...)
See also
KNeighborsClassifier
RadiusNeighborsClassifier
NearestCentroids
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 regressor sklearn.neighbors.KNeighborsRegressor.
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.
https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm
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 target for the provided data.
score
(X, y[, sample_weight])Return the coefficient of determination of the prediction.
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 (TargetRegression) – Training data. FData with the training respones (functional response case) or array matrix with length n_samples in the multivariate response case.
self (SelfTypeRegressor) –
- Returns:
Self.
- Return type:
SelfTypeRegressor
- 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 target for the provided data.
- Parameters:
X (Input) – FDataGrid with the test samples or array (n_query, n_indexed) if metric == ‘precomputed’.
- Returns:
array of shape = [n_samples] or [n_samples, n_outputs] or
FData
containing as many samples as X.- Return type:
TargetRegression
- score(X, y, sample_weight=None)[source]#
Return the coefficient of determination of the prediction.
The coefficient of determination \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares
((y_true - y_pred)** 2).sum()
and \(v\) is the total sum of squares((y_true - y_true.mean()) ** 2).sum()
. The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0.- Parameters:
X (array-like of shape (n_samples, n_features)) – Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape
(n_samples, n_samples_fitted)
, wheren_samples_fitted
is the number of samples used in the fitting for the estimator.y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – True values for X.
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.
- Returns:
score – \(R^2\) of
self.predict(X)
w.r.t. y.- Return type:
Notes
The \(R^2\) score used when calling
score
on a regressor usesmultioutput='uniform_average'
from version 0.23 to keep consistent with default value ofr2_score()
. This influences thescore
method of all the multioutput regressors (except forMultiOutputRegressor
).
- 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 (KNeighborsRegressor) –
- Returns:
self – The updated object.
- Return type:
Examples using skfda.ml.regression.KNeighborsRegressor
#
Neighbors Functional Regression