tslearn.neighbors.KNeighborsTimeSeriesClassifier

class tslearn.neighbors.KNeighborsTimeSeriesClassifier(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.

Notes

The training data are saved to disk if this model is serialized and may result in a large model file if the training dataset is large.

Examples

>>> clf = KNeighborsTimeSeriesClassifier(n_neighbors=2, metric="dtw")
>>> clf.fit([[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]],
...         y=[0, 0, 1]).predict([[1, 2.2, 3.5]])
array([0])
>>> clf = KNeighborsTimeSeriesClassifier(n_neighbors=2,
...                                      metric="dtw",
...                                      n_jobs=2)
>>> clf.fit([[1, 2, 3], [1, 1.2, 3.2], [3, 2, 1]],
...         y=[0, 0, 1]).predict([[1, 2.2, 3.5]])
array([0])
>>> clf = KNeighborsTimeSeriesClassifier(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, 0, 1]).predict([[1, 2.2, 3.5]])
array([0])

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()

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 class labels for the provided data

predict_proba(X)

Predict the class probabilities for the provided data

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.

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, )

Target values.

Returns:
KNeighborsTimeSeriesClassifier

The fitted estimator

classmethod from_hdf5(path)[source]

Load model from a HDF5 file. Requires h5py http://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()[source]

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:
routingMetadataRequest

A MetadataRequest encapsulating routing information.

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 class labels for the provided data

Parameters:
Xarray-like, shape (n_ts, sz, d)

Test samples.

Returns:
array, shape = (n_ts, )

Array of predicted class labels

predict_proba(X)[source]

Predict the class probabilities for the provided data

Parameters:
Xarray-like, shape (n_ts, sz, d)

Test samples.

Returns:
array, shape = (n_ts, n_classes)

Array of predicted class probabilities

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:
Xarray-like of shape (n_samples, n_features)

Test samples.

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.

sample_weightarray-like of shape (n_samples,), default=None

Sample weights.

Returns:
scorefloat

Mean accuracy of self.predict(X) w.r.t. y.

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.

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') KNeighborsTimeSeriesClassifier[source]

Request metadata passed to the score method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • 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_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for sample_weight parameter in score.

Returns:
selfobject

The updated object.

to_hdf5(path)[source]

Save model to a HDF5 file. Requires h5py http://docs.h5py.org/

Parameters:
pathstr

Full file path. File must not already exist.

Raises:
FileExistsError

If a file with the same path already exists.

to_json(path)[source]

Save model to a JSON file.

Parameters:
pathstr

Full file path.

to_pickle(path)[source]

Save model to a pickle file.

Parameters:
pathstr

Full file path.

Examples using tslearn.neighbors.KNeighborsTimeSeriesClassifier

Nearest neighbors

Nearest neighbors

Hyper-parameter tuning of a Pipeline with KNeighborsTimeSeriesClassifier

Hyper-parameter tuning of a Pipeline with KNeighborsTimeSeriesClassifier

1-NN with SAX + MINDIST

1-NN with SAX + MINDIST