Skip to main content
Ctrl+K
tslearn 0.8.1 documentation - Home tslearn 0.8.1 documentation - Home
  • Quick-start guide
  • User Guide
  • API Reference
  • Gallery of examples
  • Citing tslearn
  • GitHub
  • Quick-start guide
  • User Guide
  • API Reference
  • Gallery of examples
  • Citing tslearn
  • GitHub

Section Navigation

  • Metrics
    • Canonical Time Warping
    • Dynamic Time Warping
    • DTW computation with a custom distance metric
    • Frechet
    • LB_Keogh
    • Longest Common Subsequence
    • Longest Common Subsequence with a custom distance metric
    • sDTW multi path matching
    • Soft Dynamic Time Warping
  • Nearest Neighbors
    • k-NN search
    • Hyper-parameter tuning of a pipeline with KNeighbors time series classifier
    • Nearest neighbors
    • 1-NN with SAX + MINDIST
  • Clustering and Barycenters
    • DBSCAN
    • Soft-DTW weighted barycenters
    • Barycenters
    • Kernel k-means
    • k-means
    • KShape
  • Classification
    • Early Classification
    • Learning Shapelets: decision boundaries in 2D distance space
    • Aligning discovered shapelets with timeseries
    • Learning Shapelets
    • SVM and GAK
  • Automatic differentiation
    • Soft-DTW loss for PyTorch neural network
  • Miscellaneous
    • Distance and Matrix Profiles
    • Matrix Profile
    • PAA and SAX features
    • Model Persistence
  • Gallery of examples
  • Nearest Neighbors
  • k-NN search

Note

Go to the end to download the full example code.

k-NN search#

This example performs a \(k\)-Nearest-Neighbor search in a database of time series using DTW as a base metric.

To do so, we use the tslearn.neighbors.KNeighborsTimeSeries class which provides utilities for the \(k\)-Nearest-Neighbor algorithm for time series.

[1] Wikipedia entry for the k-nearest neighbors algorithm

[2] H. Sakoe and S. Chiba, “Dynamic programming algorithm optimization for spoken word recognition”. IEEE Transactions on Acoustics, Speech, and Signal Processing, 26(1), 43-49 (1978).

Queries (in black) and their nearest neighbors (red)
# Author: Romain Tavenard
# License: BSD 3 clause

import numpy
import matplotlib.pyplot as plt

from tslearn.neighbors import KNeighborsTimeSeries
from tslearn.datasets import CachedDatasets

seed = 0
numpy.random.seed(seed)
X_train, y_train, X_test, y_test = CachedDatasets().load_dataset("Trace")

n_queries = 2
n_neighbors = 4

knn = KNeighborsTimeSeries(n_neighbors=n_neighbors)
knn.fit(X_train)
ind = knn.kneighbors(X_test[:n_queries], return_distance=False)

plt.figure()
for idx_ts in range(n_queries):
    plt.subplot(n_neighbors + 1, n_queries, idx_ts + 1)
    plt.plot(X_test[idx_ts].ravel(), "k-")
    plt.xticks([])
    for rank_nn in range(n_neighbors):
        plt.subplot(n_neighbors + 1, n_queries,
                    idx_ts + (n_queries * (rank_nn + 1)) + 1)
        plt.plot(X_train[ind[idx_ts, rank_nn]].ravel(), "r-")
        plt.xticks([])


plt.suptitle("Queries (in black) and their nearest neighbors (red)")
plt.show()

Total running time of the script: (0 minutes 0.901 seconds)

Download Jupyter notebook: plot_knn_search.ipynb

Download Python source code: plot_knn_search.py

Download zipped: plot_knn_search.zip

Gallery generated by Sphinx-Gallery

previous

Nearest Neighbors

next

Hyper-parameter tuning of a pipeline with KNeighbors time series classifier

© Copyright 2025, Romain Tavenard.

Created using Sphinx 9.1.0.

Built with the PyData Sphinx Theme 0.16.1.