DTW for Python

1.7.4 · active · verified Thu Apr 16

dtw-python is a comprehensive Python library that provides a faithful, functionally equivalent implementation of Dynamic Time Warping (DTW) algorithms, mirroring the capabilities of the popular R 'dtw' package. It enables optimal alignment between two time series, even if they have different lengths or time axes, and supports various local (slope) and global (window) constraints. The library is currently at version 1.7.4 and maintains an active, though irregular, release cadence, with several updates per year. It is widely used for classification and clustering tasks across domains like bioinformatics, econometrics, and general time series analysis.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to compute Dynamic Time Warping between two NumPy arrays. It defines a query and a template time series, then uses the `dtw()` function to find their optimal alignment. The resulting `alignment` object contains the DTW distance and can be used for plotting the warping path (if `matplotlib` is installed).

import numpy as np
from dtw import *

# Create two noisy sine waves
idx = np.linspace(0, 6.28, num=100)
query = np.sin(idx) + np.random.uniform(size=100) / 10.0
template = np.cos(idx)

# Compute DTW alignment
alignment = dtw(query, template, keep_internals=True)

# Print the distance
print(f"DTW Distance: {alignment.distance:.2f}")

# Optionally, visualize the alignment (requires matplotlib)
try:
    import matplotlib.pyplot as plt
    alignment.plot(type="threeway")
    plt.title("DTW Alignment")
    plt.show()
except ImportError:
    print("Matplotlib not installed. Install with `pip install dtw-python[plots]` to enable plotting.")

view raw JSON →