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
(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
([deep])Get parameters for this estimator. kneighbors
([X, n_neighbors, return_distance])Finds the Kneighbors of a point. kneighbors_graph
([X, n_neighbors, mode])Computes the (weighted) graph of kNeighbors 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. 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:  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
(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 : dict
Parameter names mapped to their values.

kneighbors
(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
(X=None, n_neighbors=None, mode='connectivity')[source]¶ Computes the (weighted) graph of kNeighbors for points in X
Parameters:  X : arraylike 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_neighbors : int, 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 Euclidean distance between points.
Returns:  A : sparsematrix of 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. The matrix is of CSR format.
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
(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
(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
(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
(**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:  **params : dict
Estimator parameters.
Returns:  self : estimator instance
Estimator instance.

to_hdf5
(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.