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 knearest neighbors vote for Time Series.
Parameters:  n_neighbors : int (default: 5)
Number of nearest neighbors to be considered for the decision.
 weights : str 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 userdefined function which accepts an array of distances, and returns an array of the same shape containing the weights.
 metric : one of the metrics allowed for
KNeighborsTimeSeries
 class (default: ‘dtw’)
Metric to be used at the core of the nearest neighbor procedure
 metric_params : dict or None (default: None)
Dictionnary of metric parameters. For metrics that accept parallelization of the crossdistance 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 hyperparameters to be passed at the creation of the SymbolicAggregateApproximation object.
 n_jobs : int or None, optional (default=None)
The number of jobs to run in parallel for crossdistance matrix computations. Ignored if the crossdistance matrix cannot be computed using parallelization.
None
means 1 unless in ajoblib.parallel_backend
context.1
means using all processors. See scikitlearns’ Glossary for more details. verbose : int, 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
(self, 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_params
(self[, deep])Get parameters for this estimator. kneighbors
(self[, X, n_neighbors, …])Finds the Kneighbors of a point. kneighbors_graph
(self[, X, n_neighbors, mode])Computes the (weighted) graph of kNeighbors for points in X predict
(self, X)Predict the class labels for the provided data predict_proba
(self, X)Predict the class probabilities for the provided data score
(self, X, y[, sample_weight])Return the mean accuracy on the given test data and labels. set_params
(self, **params)Set the parameters of this estimator. to_hdf5
(self, path)Save model to a HDF5 file. to_json
(self, path)Save model to a JSON file. to_pickle
(self, path)Save model to a pickle file. 
fit
(self, X, y)[source]¶ Fit the model using X as training data and y as target values
Parameters:  X : arraylike, shape (n_ts, sz, d)
Training data.
 y : arraylike, 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:  path : str
Full path to file.
Returns:  Model instance

classmethod
from_json
(path)[source]¶ Load model from a JSON file.
Parameters:  path : str
Full path to file.
Returns:  Model instance

classmethod
from_pickle
(path)[source]¶ Load model from a pickle file.
Parameters:  path : str
Full path to file.
Returns:  Model instance

get_params
(self, deep=True)[source]¶ Get parameters for this estimator.
Parameters:  deep : bool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators.
Returns:  params : mapping of string to any
Parameter names mapped to their values.

kneighbors
(self, X=None, n_neighbors=None, return_distance=True)[source]¶ Finds the Kneighbors of a point.
Returns indices of and distances to the neighbors of each point.
Parameters:  X : arraylike, 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_neighbors : int
Number of neighbors to get (default is the value passed to the constructor).
 return_distance : boolean, optional. Defaults to True.
If False, distances will not be returned
Returns:  dist : array
Array representing the distance to points, only present if return_distance=True
 ind : array
Indices of the nearest points in the population matrix.

kneighbors_graph
(self, X=None, n_neighbors=None, mode='connectivity')[source]¶ Computes the (weighted) graph of kNeighbors for points in X
Parameters:  X : arraylike, shape (n_queries, n_features), or (n_queries, n_indexed) if metric == ‘precomputed’
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.
 n_neighbors : int
Number of neighbors for each sample. (default is value passed to the constructor).
 mode : {‘connectivity’, ‘distance’}, optional
Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points.
Returns:  A : sparse graph in CSR format, shape = [n_queries, 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.
See also
NearestNeighbors.radius_neighbors_graph
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
(self, X)[source]¶ Predict the class labels for the provided data
Parameters:  X : arraylike, shape (n_ts, sz, d)
Test samples.
Returns:  array, shape = (n_ts, )
Array of predicted class labels

predict_proba
(self, X)[source]¶ Predict the class probabilities for the provided data
Parameters:  X : arraylike, shape (n_ts, sz, d)
Test samples.
Returns:  array, shape = (n_ts, n_classes)
Array of predicted class probabilities

score
(self, X, y, sample_weight=None)[source]¶ Return the mean accuracy on the given test data and labels.
In multilabel 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 : arraylike of shape (n_samples, n_features)
Test samples.
 y : arraylike of shape (n_samples,) or (n_samples, n_outputs)
True labels for X.
 sample_weight : arraylike of shape (n_samples,), default=None
Sample weights.
Returns:  score : float
Mean accuracy of self.predict(X) wrt. y.

set_params
(self, **params)[source]¶ Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects (such as pipelines). 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 : object
Estimator instance.

to_hdf5
(self, path)[source]¶ Save model to a HDF5 file. Requires
h5py
http://docs.h5py.org/Parameters:  path : str
Full file path. File must not already exist.
Raises:  FileExistsError
If a file with the same path already exists.