DTW for Python
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
-
ImportError: cannot import name 'dtw' from 'dtw-python'
cause Attempting to import `dtw` directly from a module named `dtw-python`, which is the PyPI package name but not the internal module name.fixThe correct import statement is `import dtw` or `from dtw import dtw` (or `from dtw import *`). The package name `dtw-python` is for `pip install`. -
librosa.util.exceptions.ParameterError: DTW cost matrix C has NaN values.
cause The local distance function (specified by `dist_method`) produced `NaN` values, often due to inputs incompatible with the chosen metric (e.g., zero vectors with cosine distance).fixInspect the input time series for `NaN`s, `inf`s, or problematic values (e.g., all zeros if using cosine distance). Consider changing the `dist_method` parameter to a more numerically stable option like 'euclidean' if the current metric is not essential. -
Unexpected DTW distance or path results compared to R's 'dtw' package or other Python DTW libraries.
cause Differences often stem from varying default step patterns, local distance metrics, or windowing functions used across implementations. `dtw-python` defaults to `symmetric2` step pattern.fixExplicitly set the `step_pattern`, `dist_method`, and `window_type` arguments in `dtw-python` to match the configuration used in the other library for a fair comparison. Pay attention to 0-based vs 1-based indexing conventions.
Warnings
- gotcha Indexing in `dtw-python` is 0-based, consistent with Python conventions. This differs from the 1-based indexing used in the R 'dtw' package, which can be a source of error when porting code or comparing results directly.
- gotcha Function argument names in Python use underscores (e.g., `keep_internals`) while the R version commonly uses dots (e.g., `keep.int`). Python does not accept abbreviated argument names.
- gotcha Plotting functionality, such as `alignment.plot()`, relies on `matplotlib`. If `matplotlib` is not installed, these methods will raise an `ImportError` or fail silently.
- gotcha The `dtw` function may return `NaN` values in the cost matrix, particularly when using certain `dist_method` arguments like 'cosine' with inappropriate input data. This can lead to `ParameterError: DTW cost matrix C has NaN values.`
- gotcha Uncommon build issues related to `undefined symbol: alloca` or `C99 mode` can arise when compiling from source on older systems or with outdated compilers.
Install
-
pip install dtw-python -
pip install dtw-python[plots]
Imports
- dtw
from dtw-python import dtw
import dtw
- *
from dtw import *
Quickstart
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.")