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_neighborsint (default: 5)

Number of nearest neighbors to be considered for the decision.

metric{‘dtw’, ‘softdtw’, ‘ctw’, ‘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_paramsdict 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_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.

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

radius_neighbors([X, radius, ...])

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

radius_neighbors_graph([X, radius, mode, ...])

Compute the (weighted) graph of Neighbors for points in X.

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

Fit the model using X as training data

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

Find 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, sparse matrix} of (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.

radiusfloat, default=None

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

return_distancebool, default=True

Whether or not to return the distances.

sort_resultsbool, default=False

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

New in version 0.22.

Returns:
neigh_distndarray of 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_indndarray of 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(X=None, radius=None, mode='connectivity', sort_results=False)[source]

Compute the (weighted) graph of Neighbors for points in X.

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

Parameters:
X{array-like, sparse matrix} 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.

radiusfloat, default=None

Radius of neighborhoods. 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.

sort_resultsbool, default=False

If True, in each row of the result, the non-zero entries will be sorted by increasing distances. If False, the non-zero entries may not be sorted. Only used with mode=’distance’.

New in version 0.22.

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

kneighbors_graph

Compute the (weighted) graph of k-Neighbors for points in X.

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

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.KNeighborsTimeSeries

k-NN search

k-NN search

Nearest neighbors

Nearest neighbors