Dynamic time warping

Also known as: DTW

On this page 7

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.

ConstraintMeaningWhy it matters
Boundary conditionThe path starts at both first points and ends at both last pointsThe whole of each series is compared
MonotonicityIndices never decrease along the pathTime order is preserved
ContinuityEach step moves by at most one indexNo points are skipped
Constraints on a valid warping path

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.

VariantKey ideaTypical use
Sakoe-Chiba bandPath must stay within a fixed width of the diagonalDefault for classification, often 5 to 10 percent of length
Itakura parallelogramWindow narrows near the start and endSpeech, where endpoints are well aligned
Derivative DTWCompares local slopes instead of raw valuesSeries with offset or trend differences
Weighted DTWPenalizes large phase differencesReducing excessive warping
Soft-DTWReplaces the minimum with a smooth soft minimumDifferentiable loss for neural networks
FastDTWApproximates the path at multiple resolutionsLong series where exact cost is too high
Multivariate DTWLocal cost over vectors of channelsSensor and motion data
Common variants of dynamic time warping

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.

MeasureHandles time shiftsCost per comparison
Euclidean distanceNoLinear
Dynamic time warpingYes, nonlinearQuadratic, reduced by windows
Cross-correlationGlobal shift onlyn log n with FFT
Longest common subsequenceYes, tolerates outliersQuadratic
Learned embeddingsDepends on trainingLinear after encoding
DTW and alternative similarity measures

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.

SymptomLikely causeFix
Unrealistic alignmentsNo window constraintAdd a Sakoe-Chiba band
Scale dominates resultsSeries not normalizedApply z-normalization
Runtime too longQuadratic cost on long seriesUse lower bounds or downsampling
Distorted cluster centersArithmetic mean of misaligned seriesUse DTW Barycenter Averaging
Overly optimistic accuracyWindow tuned on test dataTune only on training folds
Typical DTW problems and remedies

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.