Dynamic time warping (DTW) is an algorithm that measures the similarity between two sequences by finding the optimal nonlinear alignment of their time axes, so that patterns occurring at different speeds or with shifts in timing can still be matched. In time series & forecasting work within artificial intelligence, DTW serves as a distance measure for classification, clustering, similarity search and the selection of analog histories that inform a forecast.
Unlike the Euclidean distance, which compares the first point of one series with the first point of the other and so on, DTW allows one point to match several points in the other series. This elastic matching makes it robust to stretching, compression and lag, at the price of quadratic computational cost and a few well-known pitfalls.
How dynamic time warping aligns two sequences
DTW builds a cost matrix in which cell (i, j) holds the local distance between point i of the first series and point j of the second, usually the squared or absolute difference. It then searches for a warping path from the bottom-left corner to the top-right corner of the matrix that minimizes the summed cost.
The search uses dynamic programming. The cumulative cost of each cell equals its local cost plus the minimum of the cumulative costs of its three predecessors: the cell to the left, the cell below and the diagonal cell. Filling the matrix takes O(n × m) time and memory for series of lengths n and m, and the value in the final cell is the DTW distance.
Every valid warping path must satisfy three constraints, summarized below.
| Constraint | Meaning | Why it matters |
|---|---|---|
| Boundary condition | The path starts at both first points and ends at both last points | The whole of each series is compared |
| Monotonicity | Indices never decrease along the path | Time order is preserved |
| Continuity | Each step moves by at most one index | No points are skipped |
Because the path may repeat indices, DTW is not a true metric: it violates the triangle inequality. This matters for indexing structures that rely on metric properties, and it is one reason why lower bounds are used for fast search.
Variants and global constraints
Plain DTW can produce pathological warpings, in which a single point maps to a long stretch of the other series. Practitioners therefore restrict the path with a global constraint window or modify the cost function, and several variants are now standard.
The table below compares the most common variants and their typical use.
| Variant | Key idea | Typical use |
|---|---|---|
| Sakoe-Chiba band | Path must stay within a fixed width of the diagonal | Default for classification, often 5 to 10 percent of length |
| Itakura parallelogram | Window narrows near the start and end | Speech, where endpoints are well aligned |
| Derivative DTW | Compares local slopes instead of raw values | Series with offset or trend differences |
| Weighted DTW | Penalizes large phase differences | Reducing excessive warping |
| Soft-DTW | Replaces the minimum with a smooth soft minimum | Differentiable loss for neural networks |
| FastDTW | Approximates the path at multiple resolutions | Long series where exact cost is too high |
| Multivariate DTW | Local cost over vectors of channels | Sensor and motion data |
The window width is the most important hyperparameter. A narrow band speeds computation and prevents absurd alignments, and empirical studies on benchmark archives show that a learned window often improves accuracy over unconstrained DTW. The width is usually tuned by cross-validation on the training set.
How DTW compares with other distance measures
DTW is one of several ways to compare time series, and the right choice depends on whether timing differences carry meaning. If a one-hour shift in a demand curve is a real difference, the Euclidean distance is appropriate; if it is noise, an elastic measure such as DTW is better.
| Measure | Handles time shifts | Cost per comparison |
|---|---|---|
| Euclidean distance | No | Linear |
| Dynamic time warping | Yes, nonlinear | Quadratic, reduced by windows |
| Cross-correlation | Global shift only | n log n with FFT |
| Longest common subsequence | Yes, tolerates outliers | Quadratic |
| Learned embeddings | Depends on training | Linear after encoding |
In time series classification, a one-nearest-neighbor classifier with DTW remained a hard-to-beat baseline for many years. Modern methods such as convolutional ensembles and random-kernel transforms now often surpass it, yet DTW still serves as a transparent reference point.
Using DTW in forecasting and machine learning workflows
Although DTW does not produce forecasts by itself, it supports forecasting through similarity-based methods. Analysts use it to cluster many series into groups with similar shape, to choose analog periods from history, and to select training series for a global forecasting model.
- Clustering: DTW Barycenter Averaging computes a representative average shape for each cluster.
- Analog forecasting: the nearest historical windows under DTW suggest how the current pattern may continue.
- Anomaly detection: a large DTW distance from typical patterns flags unusual behavior.
- Training loss: Soft-DTW lets a neural forecaster be rewarded for correct shape even when peaks are slightly misplaced.
For speed, libraries apply the LB_Keogh lower bound and early abandoning, which discard most candidates without computing the full matrix. Inputs should almost always be z-normalized first, because DTW compares raw amplitudes and otherwise confuses level differences with shape differences.
Limitations and common mistakes
DTW is powerful but easy to misuse, and most failures come from preprocessing and parameter choices rather than from the algorithm itself. The table lists frequent problems with their causes and fixes.
| Symptom | Likely cause | Fix |
|---|---|---|
| Unrealistic alignments | No window constraint | Add a Sakoe-Chiba band |
| Scale dominates results | Series not normalized | Apply z-normalization |
| Runtime too long | Quadratic cost on long series | Use lower bounds or downsampling |
| Distorted cluster centers | Arithmetic mean of misaligned series | Use DTW Barycenter Averaging |
| Overly optimistic accuracy | Window tuned on test data | Tune only on training folds |
A final caveat is conceptual: DTW assumes that timing distortions are irrelevant. In forecasting evaluation, where a late peak is a genuine error, DTW should not replace standard error metrics such as MASE.
A non-technical view
Imagine two people singing the same song. One sings faster in some parts and slower in others. A simple comparison, note by note at the same second, would say the songs differ. Dynamic time warping lines up the matching parts first. It stretches and squeezes time so the same notes meet.
After that alignment, it measures how different the two songs really are. The result is a fair similarity score that ignores tempo changes and focuses on shape.
A concrete example
A utility analyzes daily electricity load curves from 20,000 smart meters to build customer segments for forecasting. Households wake up at different times, so their morning peaks occur between 6 a.m. and 9 a.m. Euclidean clustering splits similar households into separate groups simply because their peaks are shifted.
The data team z-normalizes each 48-point half-hourly curve and runs k-means clustering with DTW and a window of four steps, which allows shifts of up to two hours. Cluster centers are computed with DTW Barycenter Averaging, and LB_Keogh pruning keeps the run within a few hours on one server.
The result is eight interpretable load profiles instead of twenty fragmented ones. A separate forecasting model is trained for each profile, and the forecast error on held-out weeks drops noticeably compared with a single model for all customers.