tslearn.neighbors.KNeighborsTimeSeries

class tslearn.neighbors.KNeighborsTimeSeries(n_neighbors=5, metric='dtw', metric_params=None, n_jobs=None, verbose=0)[source]

Unsupervised learner for implementing neighbor searches for Time Series.

Parameters:
n_neighbors : int (default: 5)

Number of nearest neighbors to be considered for the decision.

metric : {‘dtw’, ‘softdtw’, ‘euclidean’, ‘sqeuclidean’, ‘cityblock’, ‘sax’} (default: ‘dtw’)

Metric to be used at the core of the nearest neighbor procedure. DTW and SAX are described in more detail in tslearn.metrics. When SAX is provided as a metric, the data is expected to be normalized such that each time series has zero mean and unit variance. Other metrics are described in scipy.spatial.distance doc.

metric_params : dict or None (default: None)

Dictionary 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_jobs : int 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.

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

>>> time_series = to_time_series_dataset([[1, 2, 3, 4],
...                                       [3, 3, 2, 0],
...                                       [1, 2, 2, 4]])
>>> knn = KNeighborsTimeSeries(n_neighbors=1).fit(time_series)
>>> dataset = to_time_series_dataset([[1, 1, 2, 2, 2, 3, 4]])
>>> dist, ind = knn.kneighbors(dataset, return_distance=True)
>>> dist
array([[0.]])
>>> print(ind)
[[0]]
>>> knn2 = KNeighborsTimeSeries(n_neighbors=10,
...                             metric="euclidean").fit(time_series)
>>> print(knn2.kneighbors(return_distance=False))
[[2 1]
 [2 0]
 [0 1]]

Methods

fit(self, X[, y]) Fit the model using X as training data
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 K-neighbors of a point.
kneighbors_graph(self[, X, n_neighbors, mode]) Computes the (weighted) graph of k-Neighbors for points in X
radius_neighbors(self[, X, radius, …]) Finds the neighbors within a given radius of a point or points.
radius_neighbors_graph(self[, X, radius, …]) Computes the (weighted) graph of Neighbors for points in X
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=None)[source]

Fit the model using X as training data

Parameters:
X : array-like, shape (n_ts, sz, d)

Training data.

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 K-neighbors of a point.

Returns indices of and distances to the neighbors of each point.

Parameters:
X : array-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_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 k-Neighbors for points in X

Parameters:
X : array-like, 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.]])
radius_neighbors(self, X=None, radius=None, return_distance=True, sort_results=False)[source]

Finds the neighbors within a given radius of a point or points.

Return the indices and distances of each point from the dataset lying in a ball with size radius around the points of the query array. Points lying on the boundary are included in the results.

The result points are not necessarily sorted by distance to their query point.

Parameters:
X : array-like, (n_samples, n_features), optional

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.

radius : float

Limiting distance of neighbors to return. (default is the value passed to the constructor).

return_distance : boolean, optional. Defaults to True.

If False, distances will not be returned.

sort_results : boolean, optional. Defaults to False.

If True, the distances and indices will be sorted before being returned. If False, the results will not be sorted. If return_distance == False, setting sort_results = True will result in an error.

New in version 0.22.

Returns:
neigh_dist : array, shape (n_samples,) of arrays

Array representing the distances to each point, only present if return_distance=True. The distance values are computed according to the metric constructor parameter.

neigh_ind : array, shape (n_samples,) of arrays

An array of arrays of indices of the approximate nearest points from the population matrix that lie within a ball of size radius around the query points.

Notes

Because the number of neighbors of each point is not necessarily equal, the results for multiple query points cannot be fit in a standard data array. For efficiency, radius_neighbors returns arrays of objects, where each object is a 1D array of indices or distances.

Examples

In the following example, we construct a NeighborsClassifier class from an array representing our data set and ask who’s the closest point to [1, 1, 1]:

>>> import numpy as np
>>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]
>>> from sklearn.neighbors import NearestNeighbors
>>> neigh = NearestNeighbors(radius=1.6)
>>> neigh.fit(samples)
NearestNeighbors(radius=1.6)
>>> rng = neigh.radius_neighbors([[1., 1., 1.]])
>>> print(np.asarray(rng[0][0]))
[1.5 0.5]
>>> print(np.asarray(rng[1][0]))
[1 2]

The first array returned contains the distances to all points which are closer than 1.6, while the second array returned contains their indices. In general, multiple points can be queried at the same time.

radius_neighbors_graph(self, X=None, radius=None, mode='connectivity', sort_results=False)[source]

Computes the (weighted) graph of Neighbors for points in X

Neighborhoods are restricted the points at a distance lower than radius.

Parameters:
X : array-like of shape (n_samples, n_features), 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.

radius : float

Radius of neighborhoods. (default is the 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.

sort_results : boolean, optional. Defaults to False.

If True, the distances and indices will be sorted before being returned. If False, the results will not be sorted. Only used with mode=’distance’.

New in version 0.22.

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

kneighbors_graph

Examples

>>> X = [[0], [3], [1]]
>>> from sklearn.neighbors import NearestNeighbors
>>> neigh = NearestNeighbors(radius=1.5)
>>> neigh.fit(X)
NearestNeighbors(radius=1.5)
>>> A = neigh.radius_neighbors_graph(X)
>>> A.toarray()
array([[1., 0., 1.],
       [0., 1., 0.],
       [1., 0., 1.]])
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.

to_json(self, path)[source]

Save model to a JSON file.

Parameters:
path : str

Full file path.

to_pickle(self, path)[source]

Save model to a pickle file.

Parameters:
path : str

Full file path.

Examples using tslearn.neighbors.KNeighborsTimeSeries