Algorithmcore
Dynamic time warping
Also called DTW.
Align two sequences of feature vectors by dynamic programming over monotone warping paths, minimizing the summed local distances.
- Time
- Θ(n m) worst
- Space
- Θ(n m) extra
- Where
- m = the length of the second sequence; n = the length of the first sequence
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Taras K. Vintsyuk, Hiroaki Sakoe, Seibi Chiba, 1968
Dynamic time warping (DTW) compares two sequences that follow the same shape at different speeds, for example two recordings of one word, two gait signals or two price curves. It finds a monotone alignment of the positions of the two sequences, a warping path, that makes the sum of the local distances between the aligned elements as small as possible. A dynamic program over an table finds this path in time. The least cost is often used as a distance, but it is not a metric.
In plain words
Two people say the same word, but one says it slowly and the other fast. A frame by frame comparison fails, because frame 10 of the slow one matches frame 6 of the fast one. DTW lets one sequence wait while the other moves on. Each element of one sequence pairs with one or more elements of the other, the pairs go forward in time in both sequences, and the first and the last elements pair with each other.
Among all such pairings, DTW finds the one with the smallest total difference. It fills a table: the entry for a pair of positions holds the best total for the two beginnings up to those positions. Each entry needs only three neighbors that are already known. The last entry is the answer, and following the choices back from it gives the pairing.
The problem
The input is two sequences and with , and a local distance , for example for numbers or the squared Euclidean distance for feature vectors such as MFCC frames. Write .
A warping path is a sequence of cells in which each step is , or . So the path is monotone and continuous, and it pairs the two first and the two last elements. Its length is between and .
A step pattern gives a weight , or to the diagonal step , the vertical step and the horizontal step . The cost of a path is , where the first cell counts as entered by a diagonal step from a sentinel cell . The code has three patterns:
| pattern | sum of the weights on every path | |||
|---|---|---|---|---|
| symmetric1 | 1 | 1 | 1 | depends on the path |
| symmetric2 | 2 | 1 | 1 | |
| asymmetric | 1 | 1 | 0 |
symmetric2 weights a step by and asymmetric by , as in Sakoe and Chiba 1978. For these two patterns the sum of the weights is the same on every path, so dividing the cost by it gives a normalized distance that does not favor short paths. The task is to find a path of least cost and its cost.
The problem is close to the edit distance and to Needleman-Wunsch alignment. The difference is that DTW has no gaps: every element is paired, and an element that is "skipped" in an edit alignment is instead paired again with a neighbor.
The algorithm
DTW(x, y, d, w_D, w_V, w_H)- 1
D[0][0] ← 0, D[i][0] ← ∞ and D[0][j] ← ∞ for i, j ≥ 1 - 2
for i ← 1 to n do - 3
for j ← 1 to m do - 4
c ← d(x_i, y_j) - 5
best ← the least of D[i-1][j-1] + w_D c, D[i-1][j] + w_V c, D[i][j-1] + w_H c ▷ a tie takes the first of these - 6
D[i][j] ← best, back[i][j] ← the cell that gave best - 7
path ← [(n, m)] - 8
while the last cell of path is not (1, 1) do append back[last cell] to path - 9
return D[n][m] and the reversed path
The table has a sentinel row and column. lets the cell use the diagonal rule, and the other sentinel cells are , so no path leaves the table. The rows are filled in order, so the three cells that line L5 reads are already final. The cost can be normalized afterwards: divide by for symmetric2 and by for asymmetric.
Example
Take , , and the pattern symmetric1. The table , without the sentinels, is:
| 0 | 3 | 11 | 18 | |
| 2 | 1 | 7 | 12 | |
| 5 | 1 | 6 | 10 | |
| 13 | 6 | 1 | 2 | |
| 20 | 10 | 2 | 1 |
For example, . The cost is , and the traceback gives the path . It pairs both 3 and 4 of with the 4 of , so the extra element of costs only .
With symmetric2 the same path costs , because the diagonal step into has weight 2, and the normalized distance is . With asymmetric the normalized distance is .
Correctness
The proof is in proofs/correctness.md. Let be the least cost of a path from the sentinel to . The last step of such a path enters from , or , and the part before it is a path to that cell. The cost is additive along the path, so
An induction over the cells in row-major order shows that line L6 sets . The back pointers give, for each cell, a predecessor that attains the minimum, so the traceback builds a path of cost . Each pointer decreases , and the only cell whose pointer is the sentinel is , so the traceback stops there. The weights of symmetric2 and asymmetric sum to and on every path, because they are and , and the steps from to add up to .
Proof: DTW returns a warping path of least weighted costfull
We use the notation of the page. The sequences are and with , and . A step pattern gives three weights , and for the steps , and ; on the page they are , and .
A path to is a sequence of cells in which each is , or , and every cell after has both coordinates at least 1. The first step from the sentinel to is a diagonal step. Write for the weight of a step. The cost of the path is
The warping paths of the page are exactly the paths to without the sentinel cell, and the cost above is the weighted cost of the page. Let be the least cost of a path to , for . Such a path always exists, so is finite. Set and for ; these cells are not reachable, except the sentinel itself.
Lemma (recurrence). For ,
Proof. The last step of a path to enters from one of the three cells , or , and the part of the path before it is a path to that cell (or the sentinel alone, when and the step is diagonal). The cost is the cost of that part plus the weight of the last step times . So the least cost over paths whose last step comes from a given cell is of that cell plus the weighted local cost, and is the least of the three. A predecessor with contributes no path. For the right side is , which is the cost of the only path.
Theorem. DTW returns , the least weighted cost of a warping path, and a warping path with that cost.
Proof. Line L1 sets the sentinel row and column to the values above. The loops of lines L2 and L3 visit the cells in row-major order, so when cell is filled, the cells , and are already final. By induction on this order and by the lemma, lines L4 to L6 set and store in the back pointer a predecessor that attains the minimum. The traceback of lines L7 and L8 starts at and follows the back pointers. Each pointer goes to a cell with a finite value and a smaller sum , and the only cell with whose pointer is the sentinel is , so the loop stops at after at most steps. Along the way, of each cell equals of its predecessor plus the weighted cost of the step, so the sum of the step costs of the path is .
Corollary (normalizers). For the pattern the weight of a step is , so the weights of every path to sum to . For the pattern the weight is , and the weights sum to . In both cases the normalizer is the same for all paths, so dividing by it does not change which path is best.
Cost. Lines L4 to L6 run once per cell, with one call of and a constant number of other operations, so the time is in the word-RAM, counting a call of as one operation. The table and the back pointers take words. If only is needed, two rows of the table are enough, and the space is after swapping the sequences when needed.
The paths counted. The number of warping paths from to is the Delannoy number , because a path is a lattice path from to with the steps east, north and northeast. For this is . The table has cells, so the dynamic program replaces an exponential search by a quadratic one.
Complexity
The table has cells, and each takes one call of and three comparisons, so the time is calls of and operations. For vectors of dimension , a call of costs . The table and the back pointers take space. If only the cost is needed, two rows are enough, which takes space when the shorter sequence indexes the columns. The path in linear space needs a divide and conquer method as in Hirschberg's algorithm for edit distance.
The number of warping paths from to is the Delannoy number , which is 1, 3, 13, 63, 321 and 1683 for . So the brute force search is exponential, and the dynamic program is the reason DTW is practical. The test test_path_counts_are_delannoy_numbers checks these counts.
Properties
- Not a metric. The DTW cost is symmetric for symmetric patterns and is 0 for equal sequences, but it fails the triangle inequality. With , and , the costs are , and . It also gives 0 to different sequences: and have cost 0. So the indexes of a metric space do not apply directly.
- Asymmetric patterns. With the asymmetric pattern the cost depends on the order of the arguments: against costs 5, but against costs 0, because the horizontal step has weight 0.
- Invariant to repeats. Repeating an element, as in a slowed copy of a signal, does not change the cost against the original under symmetric1. The test test_identity_and_time_shift checks a slowed copy.
- Exact. The cost is the least over all warping paths. A band or a slope limit, as in the Sakoe-Chiba band, can miss the optimum.
- A fixed tie rule. The code prefers the diagonal step, then the vertical step, then the horizontal step.
Variants and improvements
- Global constraints. The Sakoe-Chiba band allows only the cells with , and the Itakura parallelogram (Itakura 1975) limits the slope of the path. Both cut the time to the number of allowed cells and stop the path from pairing one element with a long run of the other.
- Slope constraints and other step patterns. Sakoe and Chiba 1978 give patterns that force a diagonal step after a few horizontal or vertical ones. In their word recognition tests the symmetric form gave fewer errors than the asymmetric form. This is a measurement on their data, not a general rule.
- Open ends. Free the start or the end of one sequence to match a short pattern inside a long one, as in word spotting.
- Connected words. Vintsyuk's method and the later one-pass algorithms run DTW against a network of word templates to recognize word sequences. This is the template version of the Viterbi search in forced alignment and HMM decoding.
- Lower bounds for search. For nearest neighbor search over many series, cheap lower bounds on the banded cost skip most of the full computations.
- Related alignments. The Fréchet distance takes the maximum of the local distances in place of the sum, and the longest common subsequence and Needleman-Wunsch allow gaps.
When to use it
Use DTW for sequences that differ by local changes of speed, when no model of the data exists: template matching of isolated words with few templates, gesture and signature matching, and nearest neighbor classification of time series. If the timing differs only by a constant shift, cross-correlation is simpler and faster. With a lot of training data, HMMs replaced DTW in speech recognition, because a statistical model of each word generalizes better than a set of templates.
Pitfalls
- Unnormalized costs. Under symmetric1 a longer path has more terms, so costs of pairs of different lengths do not compare. Use symmetric2 or asymmetric and divide by the sum of the weights.
- Pathological warping. Without a band, one element can pair with a long run of the other, and a sequence can match a very different one at a low cost. Use a band or a slope limit.
- Scale and offset. The local distance compares raw values, so two series with different offsets or scales get a large cost. Normalize each series first if only the shape matters.
- Treating the cost as a metric. The triangle inequality fails, so pruning rules that assume it can drop true nearest neighbors.
- Empty sequences. A warping path needs at least one element in each sequence. The code raises an error for an empty input.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-time-warping/. The authors are listed in prov/JJFMC2.jsonl.
"""Dynamic time warping (DTW) of two sequences.
x = x_1 ... x_n and y = y_1 ... y_m are sequences of numbers or of vectors, and
d(a, b) >= 0 is a local distance. A warping path is a list of cells (i, j),
1-based, from (1, 1) to (n, m), where each step is (1, 0), (0, 1) or (1, 1).
A step pattern gives the weight of each step as a multiple of d at the cell the
step enters. The three patterns here are
name diagonal (i-1, j-1) vertical (i-1, j) horizontal (i, j-1) divide by
symmetric1 1 1 1 1
symmetric2 2 1 1 n + m
asymmetric 1 1 0 n
symmetric2 weights each step by its delta i + delta j, and asymmetric by its
delta i, as in Sakoe and Chiba 1978. The first cell (1, 1) is entered by a
diagonal step from the sentinel cell (0, 0), with D[0][0] = 0 and D[i][0] =
D[0][j] = infinity, so the same recurrence covers all three patterns. Then the
sum of the step weights is n + m for symmetric2 and n for asymmetric on every
path, which is why those totals are the normalizers.
Tie rule of the traceback: the diagonal step first, then the vertical step,
then the horizontal step.
"""
import math
from typing import Callable, List, Sequence, Tuple
INF = math.inf
STEP_PATTERNS = {
"symmetric1": (1, 1, 1),
"symmetric2": (2, 1, 1),
"asymmetric": (1, 1, 0),
}
def abs_dist(a, b) -> float:
"""|a - b| for numbers."""
return abs(a - b)
def sq_euclidean(a, b) -> float:
"""Squared Euclidean distance of two vectors of the same length."""
return math.fsum((u - v) ** 2 for u, v in zip(a, b))
def dtw(x: Sequence, y: Sequence, dist: Callable = abs_dist, step: str = "symmetric1"):
"""Return (D, path): the cost D[n][m] of a best warping path, and that path.
The cost is not normalized; see dtw_distance. Cost: O(n m) calls of dist,
O(n m) time and O(n m) memory for the table and the back pointers.
"""
n, m = len(x), len(y)
if n == 0 or m == 0:
raise ValueError("both sequences must be non-empty")
wd, wv, wh = STEP_PATTERNS[step]
D = [[INF] * (m + 1) for _ in range(n + 1)]
back = [[(0, 0)] * (m + 1) for _ in range(n + 1)]
D[0][0] = 0.0 # @line L1
for i in range(1, n + 1): # @line L2
for j in range(1, m + 1): # @line L3
c = dist(x[i - 1], y[j - 1]) # @line L4
best, arg = D[i - 1][j - 1] + wd * c, (i - 1, j - 1) # @line L5
v = D[i - 1][j] + wv * c
if v < best:
best, arg = v, (i - 1, j)
h = D[i][j - 1] + wh * c
if h < best:
best, arg = h, (i, j - 1)
D[i][j], back[i][j] = best, arg # @line L6
path = [(n, m)] # @line L7
while path[-1] != (1, 1): # @line L8
i, j = path[-1]
path.append(back[i][j])
path.reverse()
return D[n][m], path # @line L9
def normalizer(n: int, m: int, step: str) -> int:
"""The sum of the step weights of every path: 1, n + m or n."""
return {"symmetric1": 1, "symmetric2": n + m, "asymmetric": n}[step]
def dtw_distance(x: Sequence, y: Sequence, dist: Callable = abs_dist, step: str = "symmetric1") -> float:
"""Return D[n][m] divided by the normalizer of the step pattern."""
cost, _ = dtw(x, y, dist, step)
return cost / normalizer(len(x), len(y), step)
def path_cost(x: Sequence, y: Sequence, path: Sequence[Tuple[int, int]], dist: Callable = abs_dist, step: str = "symmetric1"):
"""Return the weighted cost of a warping path under a step pattern."""
wd, wv, wh = STEP_PATTERNS[step]
total = 0.0
prev = (0, 0)
for i, j in path:
di, dj = i - prev[0], j - prev[1]
w = wd if (di, dj) == (1, 1) else wv if (di, dj) == (1, 0) else wh
total += w * dist(x[i - 1], y[j - 1])
prev = (i, j)
return total
def is_warping_path(path: Sequence[Tuple[int, int]], n: int, m: int) -> bool:
"""True if the path goes from (1, 1) to (n, m) with steps (1, 0), (0, 1) or (1, 1)."""
if not path or path[0] != (1, 1) or path[-1] != (n, m):
return False
return all((b[0] - a[0], b[1] - a[1]) in ((1, 0), (0, 1), (1, 1)) for a, b in zip(path, path[1:]))
test_dynamic_time_warping.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-time-warping/. The authors are listed in prov/JJFMC2.jsonl.
import math
import random
import pytest
from dynamic_time_warping import (
STEP_PATTERNS,
dtw,
dtw_distance,
is_warping_path,
path_cost,
sq_euclidean,
)
PATTERNS = list(STEP_PATTERNS)
def all_paths(n, m):
"""Every monotone warping path from (1, 1) to (n, m)."""
out = []
def go(path):
i, j = path[-1]
if (i, j) == (n, m):
out.append(list(path))
return
for di, dj in ((1, 1), (1, 0), (0, 1)):
if i + di <= n and j + dj <= m:
path.append((i + di, j + dj))
go(path)
path.pop()
go([(1, 1)])
return out
def test_path_counts_are_delannoy_numbers():
assert [len(all_paths(k, k)) for k in range(1, 7)] == [1, 3, 13, 63, 321, 1683]
assert len(all_paths(2, 3)) == 5 and len(all_paths(1, 5)) == 1
@pytest.mark.parametrize("step", PATTERNS)
def test_against_brute_force(step):
rng = random.Random(10 + PATTERNS.index(step))
cache = {}
for _ in range(120):
n, m = rng.randint(1, 6), rng.randint(1, 6)
x = [rng.randint(0, 9) for _ in range(n)]
y = [rng.randint(0, 9) for _ in range(m)]
if (n, m) not in cache:
cache[(n, m)] = all_paths(n, m)
best = min(path_cost(x, y, p, step=step) for p in cache[(n, m)])
cost, path = dtw(x, y, step=step)
assert cost == best # integer inputs: the sums are exact
assert is_warping_path(path, n, m)
assert path_cost(x, y, path, step=step) == cost
def test_worked_example():
x, y = [1, 3, 4, 9, 8], [1, 4, 9, 8]
cost, path = dtw(x, y)
assert cost == 1 and path == [(1, 1), (2, 2), (3, 2), (4, 3), (5, 4)]
assert dtw(x, y, step="symmetric2")[0] == 2
assert dtw_distance(x, y, step="symmetric2") == pytest.approx(2 / 9)
assert dtw_distance(x, y, step="asymmetric") == pytest.approx(1 / 5)
def test_not_a_metric():
a, b, c = [0], [2], [2, 2]
assert dtw(a, b)[0] == 2 and dtw(b, c)[0] == 0 and dtw(a, c)[0] == 4
assert dtw(a, c)[0] > dtw(a, b)[0] + dtw(b, c)[0] # the triangle inequality fails
# distance 0 between different sequences
assert dtw([1, 2, 2, 3], [1, 2, 3])[0] == 0
def test_symmetry():
rng = random.Random(3)
for _ in range(50):
x = [rng.randint(0, 9) for _ in range(rng.randint(1, 7))]
y = [rng.randint(0, 9) for _ in range(rng.randint(1, 7))]
for step in ("symmetric1", "symmetric2"):
assert dtw(x, y, step=step)[0] == dtw(y, x, step=step)[0]
# the asymmetric pattern is not symmetric
assert dtw([0, 5], [0], step="asymmetric")[0] == 5
assert dtw([0], [0, 5], step="asymmetric")[0] == 0
def test_identity_and_time_shift():
x = [math.sin(0.3 * t) for t in range(40)]
assert dtw(x, x)[0] == 0
# a slowed copy (each sample twice) is at distance 0
slow = [v for v in x for _ in range(2)]
cost, path = dtw(x, slow)
assert cost == 0
assert len(path) == len(slow)
def test_tie_rule():
# all costs 0: every path ties, and the traceback takes diagonals first
cost, path = dtw([0, 0, 0], [0, 0])
assert cost == 0 and path == [(1, 1), (2, 1), (3, 2)]
def test_vectors():
x = [(0.0, 0.0), (1.0, 1.0), (2.0, 0.0)]
y = [(0.0, 0.0), (2.0, 0.0)]
cost, path = dtw(x, y, dist=sq_euclidean)
assert cost == pytest.approx(2.0)
assert path_cost(x, y, path, dist=sq_euclidean) == pytest.approx(2.0)
def test_empty():
with pytest.raises(ValueError):
dtw([], [1])
History
Vintsyuk 1968 aligned speech to word templates by dynamic programming. The 1978 paper of Sakoe and Chiba compared the symmetric and asymmetric forms, used slope constraints and the adjustment window that is now called the Sakoe-Chiba band, and measured their effect on word recognition. Itakura 1975 used a slope constrained alignment with a distance from linear prediction. DTW template matching was the main method of isolated word recognition until HMMs took over in the 1980s (Rabiner and Juang 1993). The method later became a standard tool for time series outside speech.
References
- Hiroaki Sakoe and Seibi Chiba, Dynamic programming algorithm optimization for spoken word recognition, IEEE Transactions on Acoustics, Speech, and Signal Processing 26(1), 1978, pages 43 to 49, the symmetric and asymmetric forms of the recurrence, the normalization and the adjustment window
- T. K. Vintsyuk, Speech discrimination by dynamic programming, Cybernetics 4(1), 1968, pages 52 to 57 (Kibernetika 4(1), pages 81 to 88, in Russian), the dynamic programming alignment of an utterance with word templates
- Fumitada Itakura, Minimum prediction residual principle applied to speech recognition, IEEE Transactions on Acoustics, Speech, and Signal Processing 23(1), 1975, pages 67 to 72, the slope constraint of the warping path
- Lawrence Rabiner and Biing-Hwang Juang, Fundamentals of Speech Recognition, Prentice Hall, 1993, Chapter 4 (pattern comparison techniques)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag JJFMC2 Edit this page History Report an error Markdown