Techniquecore
Sakoe-Chiba band
Also called Sakoe-Chiba constraint.
Restrict the warping path of DTW to the cells within a fixed distance r of the diagonal. This saves time and stops degenerate alignments, but it can miss the optimum.
The Sakoe-Chiba band is a global constraint on dynamic time warping: a warping path may use only the cells with , for a fixed band width . The dynamic program then fills about cells in place of , and no element of one sequence can pair with a long run of the other. The price is that the best path inside the band can cost more than the best path overall. The Itakura parallelogram is a related constraint (Itakura 1975) that limits the slope of the path and so restricts it to a parallelogram around the diagonal.
In plain words
DTW lets one sequence wait while the other moves on, and it fills a table with one entry for each pair of positions. Most of that table is far from the diagonal, where one sequence is far ahead of the other. Such pairings are rarely right: two recordings of one word do not drift apart by half a second.
The band keeps only a strip of the table along the diagonal, and treats everything outside the strip as forbidden. The program fills only the strip, so it runs much faster on long sequences. It also cannot pick a strange pairing far from the diagonal. But if the true best pairing leaves the strip, the band gives a worse answer, so the width of the strip is a trade-off.
When it applies
The technique applies to a dynamic program over a two-dimensional table in which a path moves from the top left corner to the bottom right corner with monotone steps, and in which good paths stay near the diagonal. DTW is the first case. The same idea works for edit distance and for global alignment, where it is called banded alignment.
It fits when the two sequences have about the same speed, so the offset of a good path stays small, and when . If the lengths differ a lot, use a band around the line from to in place of the main diagonal, or rescale one sequence first.
The template
BANDED-DTW(x, y, d, BAND) ▷ BAND(i) is the hole: the range of columns j allowed in row i- 1
if the cell (n, m) is not in BAND(n), or (1, 1) is not in BAND(1), then report "no path in the band" - 2
D[0][0] ← 0, and every cell outside the band counts as ∞ - 3
for i ← 1 to n do - 4
for j in BAND(i), clipped to 1 .. m do - 5
D[i][j] ← d(x_i, y_j) + min(D[i-1][j-1], D[i-1][j], D[i][j-1]) - 6
return D[n][m], and the path from the back pointers
The hole is BAND. The Sakoe-Chiba band of width is . With this band, a warping path exists if and only if : the last cell must satisfy , and if it does, the path that goes along the diagonal and then straight to stays in the band. Line L1 checks this. Line L5 is the recurrence of the symmetric1 pattern on the dynamic time warping page, and the other step patterns work the same way.
Walk through the template with , and .
- Without a band, the best path is . It pairs the three zeros of with the zero of and the five of with the three fives of , and it costs 0. It uses the cells and , which have .
- With that path is in the band, and the cost is 0.
- With it is not. The best path in the band is , which pairs the third zero of with a five and costs 5.
- With only the diagonal is left, and the cost is .
So the band missed the optimum for . The test test_band_misses_the_optimum checks these values.
Cost. Row has at most cells, so the template fills at most cells, and exactly when . The time and the memory are for , against without the band. The code stores only the cells of the band.
What the band guarantees. The banded cost is the least cost over the warping paths inside the band (a theorem, from the same induction as for DTW, applied to the cells of the band). It is at least the unconstrained cost, it does not increase as grows, and it equals the unconstrained cost when . The tests check all three. The banded cost is exact only if some optimal path stays in the band, and the band has no way to check this.
Classic examples
- Isolated word recognition. Sakoe and Chiba 1978 compared spoken words with stored templates by dynamic time warping under an adjustment window , together with a slope constraint. The window cut the cost of each comparison and removed alignments that were not plausible for speech.
- Banded alignment of strings. For edit distance and global alignment of similar strings, banded alignment fills only the diagonals near the main one. For unit costs, the band can be doubled until its width exceeds the cost found, which makes the result exact.
- Nearest neighbor search over time series. A nearest neighbor search that compares a query with many stored series uses a band of a few percent of the length. The band cuts the cost of each comparison, and its width becomes a parameter of the classifier, chosen on held-out data like any other.
- Alignment with a known transcript. The limits and of forced alignment are a band in the frame and state table, but there they are exact: they only drop cells that no complete path can use.
Variations
- Itakura parallelogram. Itakura 1975 limited the local slope of the path, so that each sequence advances at most twice as fast as the other. Together with the fixed ends, this keeps the path in a parallelogram with corners and and sides of slope and , so a path exists only if , roughly. The parallelogram is narrow near the ends and wide in the middle, while the band has the same width everywhere.
- Slope constraints. Sakoe and Chiba 1978 also gave step patterns that allow at most a few horizontal or vertical steps in a row. A slope constraint acts on each step, while a band acts on the position.
- A band around the scaled diagonal. For sequences of different lengths, allow the cells with , so the band follows the line from to .
- Data-dependent bands. Compute the path at a coarse resolution, project it to the fine resolution, and fill only a band around it. This is fast, but it is a heuristic and not exact.
- Beam pruning. A time-synchronous beam search keeps the cells whose score is close to the best one in each column. The beam adapts to the data, but like the band it can lose the best path.
Pitfalls
- A band that is too narrow. The banded cost is only an upper bound on the true DTW cost. If the sequences have a large time offset, every path in the band is poor. The band width is a heuristic, to be set on development data, often as a percentage of the length.
- Different lengths. With there is no path. The code raises an error, and a silent could look like a very bad match.
- Mixing constraints. The band and a slope limit together can leave no path, even when each one alone leaves one.
- Comparing costs across widths. The banded cost depends on . Use the same width for all the comparisons of one task.
- Assuming exactness. Lower bounds and pruning rules that are proved for the banded cost do not bound the unconstrained cost from the same side.
Code
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/sakoe-chiba-band/. The authors are listed in prov/HMGHCC.jsonl.
"""DTW restricted to a Sakoe-Chiba band.
x = x_1 ... x_n and y = y_1 ... y_m. A warping path from (1, 1) to (n, m) uses
the steps (1, 0), (0, 1) and (1, 1). The band of width r keeps only the cells
with |i - j| <= r, so a path in the band exists if and only if |n - m| <= r.
The recurrence is the symmetric1 pattern of the dynamic-time-warping page:
D[i][j] = d(x_i, y_j) + min(D[i-1][j-1], D[i-1][j], D[i][j-1]),
with D[0][0] = 0 and every other cell outside the band at infinity. Only the
cells of the band are stored, so time and memory are O(n r) for r >= 1.
"""
import math
from typing import Callable, Dict, Sequence, Tuple
INF = math.inf
def abs_dist(a, b) -> float:
return abs(a - b)
def band_dtw(x: Sequence, y: Sequence, r: int, dist: Callable = abs_dist):
"""Return (cost, path, cells): the best cost in the band, a best path, and the number of cells filled.
Ties in the traceback go to the diagonal, then (i - 1, j), then (i, j - 1).
Raise ValueError if no warping path fits in the band (|n - m| > r).
"""
n, m = len(x), len(y)
if n == 0 or m == 0 or r < 0:
raise ValueError("need non-empty sequences and r >= 0")
if abs(n - m) > r: # @line L1
raise ValueError("no warping path fits in the band: |n - m| > r")
D: Dict[Tuple[int, int], float] = {(0, 0): 0.0} # @line L2
back: Dict[Tuple[int, int], Tuple[int, int]] = {}
for i in range(1, n + 1): # @line L3
for j in range(max(1, i - r), min(m, i + r) + 1): # @line L4
best, arg = D.get((i - 1, j - 1), INF), (i - 1, j - 1) # @line L5
for cell in ((i - 1, j), (i, j - 1)):
v = D.get(cell, INF)
if v < best:
best, arg = v, cell
D[(i, j)] = dist(x[i - 1], y[j - 1]) + best
back[(i, j)] = arg
path = [(n, m)]
while path[-1] != (1, 1):
path.append(back[path[-1]])
path.reverse()
return D[(n, m)], path, len(D) - 1 # @line L6
def full_dtw(x: Sequence, y: Sequence, dist: Callable = abs_dist) -> float:
"""The unconstrained symmetric1 DTW cost, O(n m), for comparison."""
n, m = len(x), len(y)
D = [[INF] * (m + 1) for _ in range(n + 1)]
D[0][0] = 0.0
for i in range(1, n + 1):
for j in range(1, m + 1):
D[i][j] = dist(x[i - 1], y[j - 1]) + min(D[i - 1][j - 1], D[i - 1][j], D[i][j - 1])
return D[n][m]
test_sakoe_chiba_band.py 89 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sakoe-chiba-band/. The authors are listed in prov/HMGHCC.jsonl.
import random
import pytest
from sakoe_chiba_band import band_dtw, full_dtw
def all_paths(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 cost(x, y, path):
return sum(abs(x[i - 1] - y[j - 1]) for i, j in path)
def test_against_brute_force_inside_the_band():
rng = random.Random(1)
cache = {}
for _ in range(200):
n, m = rng.randint(1, 6), rng.randint(1, 6)
r = rng.randint(abs(n - m), 5)
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)
inside = [p for p in cache[(n, m)] if all(abs(i - j) <= r for i, j in p)]
c, path, _ = band_dtw(x, y, r)
assert c == min(cost(x, y, p) for p in inside)
assert path in inside and cost(x, y, path) == c
def test_wide_band_equals_full_dtw():
rng = random.Random(2)
for _ in range(100):
x = [rng.randint(0, 9) for _ in range(rng.randint(1, 12))]
y = [rng.randint(0, 9) for _ in range(rng.randint(1, 12))]
r = max(len(x), len(y)) - 1
assert band_dtw(x, y, r)[0] == full_dtw(x, y)
def test_band_misses_the_optimum():
x, y = [0, 0, 0, 5], [0, 5, 5, 5]
assert full_dtw(x, y) == 0
assert band_dtw(x, y, 2)[0] == 0
c1, path, _ = band_dtw(x, y, 1)
assert c1 == 5 and path == [(1, 1), (2, 1), (3, 2), (4, 3), (4, 4)]
assert band_dtw(x, y, 0)[0] == 10
def test_cost_does_not_increase_with_r():
rng = random.Random(3)
for _ in range(100):
n = rng.randint(1, 10)
x = [rng.randint(0, 9) for _ in range(n)]
y = [rng.randint(0, 9) for _ in range(n)]
costs = [band_dtw(x, y, r)[0] for r in range(n)]
assert all(costs[k + 1] <= costs[k] for k in range(n - 1))
assert costs[-1] == full_dtw(x, y)
def test_cells_filled():
x = list(range(100))
for r in (0, 1, 5, 10):
_, _, cells = band_dtw(x, x, r)
assert cells == sum(min(100, i + r) - max(1, i - r) + 1 for i in range(1, 101))
assert cells <= 100 * (2 * r + 1)
def test_no_path_in_a_narrow_band():
with pytest.raises(ValueError):
band_dtw([1, 2, 3, 4], [1, 2], 1)
assert band_dtw([1, 2, 3, 4], [1, 2], 2)[0] == full_dtw([1, 2, 3, 4], [1, 2])
Exercises
- Prove that a warping path with in every cell exists if and only if .
- Show that the band of width has exactly cells when , and check it against the test test_cells_filled.
- Prove that the banded cost does not increase when grows, and that it equals the unconstrained DTW cost for .
- Find two sequences of length 3 whose banded cost with is larger than with , and two sequences for which the two costs are equal although the best paths differ.
- In one form of the Itakura constraint, each step advances by 1 and by 0, 1 or 2, and no two consecutive steps advance by 0. Show that a path from to exists only if and .
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 adjustment window condition on the warping path and the slope constraint
- 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 local slope constraint of the warping path, which gives the parallelogram
- Lawrence Rabiner and Biing-Hwang Juang, Fundamentals of Speech Recognition, Prentice Hall, 1993, Chapter 4 (pattern comparison techniques, time alignment and normalization)
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag HMGHCC Edit this page History Report an error Markdown