tslearn.neighbors.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. None means 1 unless in a joblib.parallel_backend context. -1 means 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

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 the coefficient of determination of the prediction.

set_params(**params)

Set the parameters of this estimator.

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

get_params(deep=True)[source]

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')[source]

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_graph

Compute 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)[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
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), where n_samples_fitted is 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) wrt. y.

Notes

The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score(). This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).

set_params(**params)[source]

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.