KNeighborsTimeSeriesRegressor#
- class tslearn.neighbors.KNeighborsTimeSeriesRegressor(n_neighbors=5, weights='uniform', metric='dtw', metric_params=None, n_jobs=None, verbose=0)[source]#
Classifier implementing the k-nearest neighbors vote for Time Series.
- Parameters:
- n_neighborsint (default: 5)
Number of nearest neighbors to be considered for the decision.
- weightsstr or callable, optional (default: ‘uniform’)
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.
- metricone of the metrics allowed for
KNeighborsTimeSeries - class (default: ‘dtw’)
Metric to be used at the core of the nearest neighbor procedure
- metric_paramsdict or None (default: None)
Dictionnary of metric parameters. For metrics that accept parallelization of the cross-distance matrix computations, n_jobs and verbose keys passed in metric_params are overridden by the n_jobs and verbose arguments. For ‘sax’ metric, these are hyper-parameters to be passed at the creation of the SymbolicAggregateApproximation object.
- n_jobsint or None, optional (default=None)
The number of jobs to run in parallel for cross-distance matrix computations. Ignored if the cross-distance matrix cannot be computed using parallelization.
Nonemeans 1 unless in ajoblib.parallel_backendcontext.-1means using all processors. See scikit-learns’ Glossary for more details.- verboseint, optional (default=0)
The verbosity level: if non zero, progress messages are printed. Above 50, the output is sent to stdout. The frequency of the messages increases with the verbosity level. If it more than 10, all iterations are reported. Glossary for more details.
Examples
>>> clf = KNeighborsTimeSeriesRegressor(n_neighbors=2, metric="dtw") >>> clf.fit([[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]], ... y=[0.1, 0.1, 1.1]).predict([[1, 2.2, 3.5]]) array([0.1]) >>> clf = KNeighborsTimeSeriesRegressor(n_neighbors=2, ... metric="dtw", ... n_jobs=2) >>> clf.fit([[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]], ... y=[0.1, 0.1, 1.1]).predict([[1, 2.2, 3.5]]) array([0.1]) >>> clf = KNeighborsTimeSeriesRegressor(n_neighbors=2, ... metric="dtw", ... metric_params={ ... "itakura_max_slope": 2.}, ... n_jobs=2) >>> clf.fit([[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]], ... y=[0.1, 0.1, 1.1]).predict([[1, 2.2, 3.5]]) array([0.1])
Methods
fit(X, y)Fit the model using X as training data and y as target values
from_hdf5(path)Load model from a HDF5 file.
from_json(path)Load model from a JSON file.
from_pickle(path)Load model from a pickle file.
Get metadata routing of this object.
get_params([deep])Get parameters for this estimator.
kneighbors([X, n_neighbors, return_distance])Finds 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 coefficient of determination on test data.
set_params(**params)Set the parameters of this estimator.
set_score_request(*[, sample_weight])Configure whether metadata should be requested to be passed to the
scoremethod.to_hdf5(path)Save model to a HDF5 file.
to_json(path)Save model to a JSON file.
to_pickle(path)Save model to a pickle file.
- fit(X, y)[source]#
Fit the model using X as training data and y as target values
- Parameters:
- Xarray-like, shape (n_ts, sz, d)
Training data.
- yarray-like, shape (n_ts, ) or (n_ts, dim_y)
Target values.
- Returns:
- KNeighborsTimeSeriesRegressor
The fitted estimator
- classmethod from_hdf5(path)[source]#
Load model from a HDF5 file. Requires
h5pyhttp://docs.h5py.org/- Parameters:
- pathstr
Full path to file.
- Returns:
- Model instance
- classmethod from_json(path)[source]#
Load model from a JSON file.
- Parameters:
- pathstr
Full path to file.
- Returns:
- Model instance
- classmethod from_pickle(path)[source]#
Load model from a pickle file.
- Parameters:
- pathstr
Full path to file.
- Returns:
- Model instance
- 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)[source]#
Finds the K-neighbors of a point.
Returns indices of and distances to the neighbors of each point.
- Parameters:
- Xarray-like, shape (n_ts, sz, d)
The query time series. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor.
- n_neighborsint
Number of neighbors to get (default is the value passed to the constructor).
- return_distanceboolean, optional. Defaults to True.
If False, distances will not be returned
- Returns:
- distarray
Array representing the distance to points, only present if return_distance=True
- indarray
Indices of the nearest points in the population matrix.
- 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_fit is the number of samples in the fitted data. A[i, j] gives the weight of the edge connecting i to j. 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)[source]#
Predict the target for the provided data
- Parameters:
- Xarray-like, shape (n_ts, sz, d)
Test samples.
- Returns:
- array, shape = (n_ts, ) or (n_ts, dim_y)
Array of predicted targets
- score(X, y, sample_weight=None)#
Return coefficient of determination on test data.
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:
- Xarray-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_fittedis the number of samples used in the fitting for the estimator.- yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
- sample_weightarray-like of shape (n_samples,), default=None
Sample weights.
- Returns:
- scorefloat
\(R^2\) of
self.predict(X)w.r.t. y.
Notes
The \(R^2\) score used when calling
scoreon a regressor usesmultioutput='uniform_average'from version 0.23 to keep consistent with default value ofr2_score(). This influences thescoremethod 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:
- **paramsdict
Estimator parameters.
- Returns:
- selfestimator instance
Estimator instance.
- set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') KNeighborsTimeSeriesRegressor#
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.
- to_hdf5(path)[source]#
Save model to a HDF5 file. Requires
h5pyhttp://docs.h5py.org/- Parameters:
- pathstr
Full file path. File must not already exist.
- Raises:
- FileExistsError
If a file with the same path already exists.