Majid Al-RaimiMinimum edit distance: alignments and search

ICS 582Lecture 02Part 10

Minimum edit distance: alignments and search

Measuring how far apart two strings are with insertions, deletions and substitutions, seeing the answer as an alignment, and recognizing the problem as a shortest path that dynamic programming solves.

Concepts
4
Slides
79-86
Reading
24 min
Understood
0/4 concepts

Why this part matters

Edit distance is the first dynamic programming algorithm in this course, and its shape returns in the Viterbi decoder and in CKY parsing. It is also the metric under word error rate, so any speech or Arabic ASR work in the research project will report it. It is a reliable exam item: define it, write the recurrence, fill a table, recover an alignment.

This part builds the idea in four moves. First the definition and why anyone needs it. Then the alignment view, which turns a distance into columns you can read and add up, and which exposes a trap: the slides define substitution at cost 1, but the worked table in part 11 (taken from SLP3) charges 2, and the same pair of words comes out as 5 or 8 depending on that choice. Then the search view, which shows why brute force fails and what dynamic programming remembers. Finally the recurrence itself and the cost function it plugs in.

By the end you can

  1. Define minimum edit distance, name the three operations, and say what each costs under unit costs.
  2. Read and cost an alignment under unit costs and under substitution cost 2, and declare which convention you use.
  3. Explain why naive search over edit sequences is exponential and why the grid of prefix pairs is O(mn).
  4. Write the initialization and the recurrence for D[i,j] and justify D[i,0] = i.
  5. Compute a word error rate from an alignment and describe weighted substitution and transposition extensions.

A speech recognizer hears "turn on the kitchen light" and writes "turn on a kitchen light please". A spell checker sees "acress". An OCR engine reads the two letters "rn" as an "m". In each case there is a string we have and a string we want, and the question is the same: how much editing separates them?

The answer is the Minimum edit distance: the minimum total cost of the editing operations that turn a source string into a target string. Three operations are allowed. An insertion adds one symbol, a deletion removes one, and a substitution replaces one with another. Each operation has a cost, most often 1, and the distance is the cheapest way of getting from source to target, not the first way you happen to find. With every operation at cost 1 (and a substitution of a letter by itself at cost 0) this quantity is the Levenshtein distance, after the 1966 paper that introduced it for error correcting codes. Nothing in the definition says the symbols must be letters. Take words as the symbols and the same definition measures how far a recognized sentence is from its transcript, which is exactly how speech recognition uses it.

Where edit distance is used, and the mechanism in each case

Spelling correction
Generate candidates within edit distance 1 of the typo and rank them: for acress, the candidates are actress, cress, caress, access, across and acres.
OCR post-processing
Map a recognized string with a misread rn or m to the nearest entry of a lexicon.
Speech recognition (WER)
Align the recognized word sequence to the reference transcript and count the word-level insertions, substitutions and deletions.
Approximate matching
Search a text for a pattern while allowing a bounded number of edits, for example in DNA or in fuzzy search boxes.
Alignment
Make explicit which characters correspond, which is the view the next concept builds on.

The spelling application is older than most of NLP. Damerau found in 1964 that a single wrong, missing, extra or transposed letter accounts for about 80 percent of spelling errors, which is why candidate generation at edit distance 1 works so well: Kernighan, Church and Gale's spelling corrector lists exactly the six one-edit candidates for "acress" shown in the table and then picks among them with a probabilistic model. Approximate matching generalizes the search direction: instead of comparing two whole strings, you look for places in a long text that a pattern would match after at most k edits.

Word error rate, computed

The Word error rate (WER) is edit distance applied to words. Align the recognizer's hypothesis to the human reference at the word level, count the insertions, substitutions and deletions on that alignment, and divide by the number of words in the reference. The denominator is the reference, never the hypothesis, and because insertions are counted the rate can exceed 100 percent.

WER=I+S+Dwords in the reference\mathrm{WER} = \frac{I + S + D}{\text{words in the reference}}
Word error rate from a word-level minimum edit distance alignment (SLP3 section 16.6)

Worked example

WER for the kitchen light

  1. Reference and hypothesis

    Reference: "turn on the kitchen light" (5 words). Hypothesis: "turn on a kitchen light please" (6 words).
  2. Align at the word level

    turn and on match, the becomes a (one substitution), kitchen and light match, please has nothing above it (one insertion).
  3. Count and divide

    I + S + D = 1 + 1 + 0 = 2, over 5 reference words.
  4. Result

    WER = 2 / 5 = 40 percent. A 2-word reference recognized as 5 words with three insertions would give 3 / 2 = 150 percent, which is legal and common on noisy audio.

SLP3's own CallHome example has 6 substitutions, 3 insertions and 1 deletion over 13 reference words, a WER of 76.9 percent. The standard scorer is NIST's sclite in the SCTK toolkit, which does the alignment and the arithmetic for you but reports exactly these counts.

Recall

Define minimum edit distance and name the three operations. What is it called when every operation costs one?

The minimum total cost of edit operations that turn a source string into a target string. The operations are insertion, deletion and substitution. With unit costs it is the Levenshtein distance.

Recall

How does WER use edit distance, and can it exceed 100 percent?

Align the hypothesis to the reference with a word-level minimum edit distance, then compute (I + S + D) divided by the number of reference words. Yes, because insertions are counted: SLP3's example gives (6 + 3 + 1) / 13 = 76.9 percent, and a short reference with many insertions goes past 100.

Quick check

A 10-word reference is recognized with 2 substitutions, 1 deletion and 2 insertions. What is the WER?

Lay the two words on top of each other as on slide 82, with a star for a gap, and read the ten columns from left to right: I over a star, N over E, T over X, E over E, a star over C, N over U, and then T I O N over T I O N. The row underneath, d s s _ i s, names the columns that cost something: delete I, substitute N by E, substitute T by X, insert C, substitute N by U. Five operations, and five is the minimum edit distance.

INTE*NTION over *EXECUTION: ten columns, ten bars, five operations lit beneath. Deletions and insertions in teal, substitutions in the accent.

What you just read is an Alignment: a correspondence between the two strings that says, for every symbol, what it lines up with. A column with the same letter top and bottom is a match and costs nothing. A column with two different letters is a substitution. A letter over a gap is a deletion (the source letter is consumed without producing anything), and a gap over a letter is an insertion. The cost of an alignment is the sum of its column costs, and the minimum edit distance is simply the cost of the cheapest alignment. The practical half of the story is that the dynamic programming table does not just give the number, it stores a Backpointer in each cell, and following those pointers back from the last cell recovers one cheapest alignment. Part 11 does that recovery by hand.

Two cost conventions, and the same words come out as 5 or 8

Here is the trap this lecture sets, and the reason this section exists. Slides 85 and 86 define the Substitution cost as 1 for two different letters. The filled table you will meet in part 11 (slides 89 and 91) is copied from SLP3, and SLP3 fills it with a substitution cost of 2. Levenshtein proposed both: in his second version insertions and deletions cost 1 and substitutions are simply not allowed, and since any substitution can be written as a deletion followed by an insertion, that is the same as allowing it at cost 2. Both are legitimate cost functions. They give different numbers, and they can disagree about which alignment is best.

OperationUnit costs (slides 85, 86)SLP3 table costs (substitution 2)
Match (same letter)00
Insertion11
Deletion11
Substitution (different letters)12
The two cost conventions used in this lecture
ColumnOperationUnit costsSubstitution 2
I over *delete11
N over Esubstitute12
T over Xsubstitute12
E over Ematch00
* over Cinsert11
N over Usubstitute12
T I O N over T I O Nfour matches00
Total58
The slide 82 alignment costed column by column under each convention

Read the totals again: 1 + 1 + 1 + 0 + 1 + 1 = 5 under unit costs and 1 + 2 + 2 + 0 + 1 + 2 = 8 with substitutions at 2. Both describe the same alignment. If an exam asks for the distance from intention to execution and you answer 8 without saying why, the grader who has the slide 85 recurrence in mind will mark it wrong, and the reverse is also true.

Try it: label the columns yourself

The editor below shows three alignments of intention and execution, with the four trailing matches already labeled. Label every remaining column, watch the two totals update, and then compare the presets. The third one pairs the letters position by position with no gaps at all: five substitutions. Under unit costs it ties the slide alignment at 5. With substitutions at 2 it costs 10 and loses to 8. The cost function does not only change the total; it changes which alignments are optimal.

InteractiveAlignment editor: label each column, then cost it two ways

Read each column of the alignment (source letter on top, target letter below, * for a gap) and label it match, substitution, insertion or deletion. The last 4 columns (T I O N) come pre-labeled as matches. The totals update from your labels under both cost conventions. Press check to grade the columns.

4 / 10 labeled
I*
NE
TX
EE
*C
NU
TT
II
OO
NN
Unit costs0totalins + del + sub, expected 5
Substitution costs 20totalins + del + 2 sub, expected 8
Counted so far0/0/0s/i/dsub / ins / del, matches cost nothing
Minimum over all alignments5 / 8unit / sub 2, intention to execution
AlignmentOperationsUnit costsSubstitution 2
Slide 82: d s s _ i s1 del, 3 sub, 1 ins58
SLP3 figure 2.19: delete i, n to e, t to x, insert u, n to c1 del, 3 sub, 1 ins58
Position by position, no gaps5 sub510
Three alignments of intention and execution under both conventions

Worked example

A second pair: kitten to sitting

  1. Write the alignment

    k over s, i over i, t over t, t over t, e over i, n over n, and a gap over g.
  2. Name the columns

    substitution, match, match, match, substitution, match, insertion.
  3. Cost it both ways

    Unit costs: 1 + 0 + 0 + 0 + 1 + 0 + 1 = 3. Substitution at 2: 2 + 0 + 0 + 0 + 2 + 0 + 1 = 5.
  4. Result

    Distance 3 under unit costs, 5 under substitution cost 2. The alignment is optimal under both, because no cheaper one exists for either function.

Recall

Cost the slide 82 alignment d s s _ i s under unit costs and under substitution cost 2.

Unit: 1 + 1 + 1 + 1 + 1 = 5 (one deletion, three substitutions, one insertion; the four matches cost nothing). Substitution cost 2: 1 + 2 + 2 + 1 + 2 = 8.

Quick check

Under unit costs, what is the minimum edit distance from intention to execution?

The obvious algorithm is search. Start at intention and try one edit: delete a letter and you get ntention, insert a letter and you get intecntion, substitute a letter and you get inxention. Those are three of the children. Count all of them for a 26-letter alphabet: 9 possible deletions, 26 × 10 = 260 insertions and 25 × 9 = 225 substitutions, which is 494 children for one step. A blind search that needs five steps to reach execution touches on the order of 494^5, about 3 × 10^13 strings. SLP3 puts it plainly: the space of all possible edits is enormous, so we cannot search naively.

One string fans out into hundreds of children, and two different edit orders land on the same string. Remembering the best cost per state is the whole trick.

The visual shows the observation that rescues the problem. Delete the i of intention and then substitute t by x and you reach nxention. Substitute t by x first and then delete the i and you reach nxention again. Two paths, one state, and once you know the cheapest way to reach a state there is no reason to explore any other route into it. SLP3 states the idea directly: many distinct edit paths end up in the same string, so rather than recomputing all those paths we can remember the shortest path to a state each time we see it. Remembering subproblem answers and combining them is Dynamic programming, Bellman's table-driven method from 1957.

Why only prefix pairs matter

Remembering strings is still too many states. The step that makes the table small is to notice which states can matter at all. Suppose exention lies on an optimal path from intention to execution. Then the part of the path from intention to exention must itself be optimal, because if a shorter way to exention existed we could splice it in and shorten the whole path, a contradiction. This is the Optimal substructure argument in SLP3, and it means the only thing worth remembering about a partial solution is how much of the source it has consumed and how much of the target it has produced: the pair (i, j). For two 9-letter words there are only (m + 1)(n + 1) = 10 × 10 = 100 such pairs. Put as a picture: edits are moves in a grid from (0, 0) to (m, n), each move is one operation, and dynamic programming finds the best path efficiently.

Rows consume source letters, columns produce target letters. From any cell, down is a deletion, right an insertion, diagonal a substitution or match. The faint staircase is the slide 82 alignment as a path.
MoveWhat it doesOperationRecurrence term
Down, (i - 1, j) to (i, j)Consume a source letter, produce nothingDeletionD[i - 1, j] + del
Right, (i, j - 1) to (i, j)Produce a target letter from nothingInsertionD[i, j - 1] + ins
Diagonal, (i - 1, j - 1) to (i, j)Pair a source letter with a target letterSubstitution or matchD[i - 1, j - 1] + sub(x_i, y_j)
The three moves in the grid, with source letters down the rows and target letters across the columns (slide 85 notation)

A path from the top-left corner to the bottom-right corner that uses only these three moves is an alignment: each step is one column. Reading the slide 82 alignment as moves gives down, diagonal, diagonal, diagonal, right, then five diagonals, which is the staircase in the figure. Wagner and Fischer showed in 1974 that filling the grid solves the problem in time proportional to the product of the two lengths, O(mn) time and, with backpointers stored, O(mn) space. Each cell is filled once with three comparisons.

tree nodes(2ΣL)dgrid cells=(m+1)(n+1)\text{tree nodes} \approx (2|\Sigma| L)^{d} \qquad \text{grid cells} = (m+1)(n+1)
Branching over strings versus cells over prefix pairs, with alphabet size |Σ|, word length L and distance d

Recall

Why is the search tree over edit sequences exponential while the grid is polynomial?

The tree's nodes are strings and each string has hundreds of one-edit children (about 494 for a 9-letter word over 26 letters), so the number of nodes grows as branching to the power of the distance. The grid's nodes are prefix pairs (i, j), only (m + 1)(n + 1) of them, each filled once, because many different edit orders arrive at the same pair.

Quick check

In the DP grid with source letters down the rows, which move is an insertion?

Quick check

Why does dynamic programming beat naive search over edit sequences?

Three small questions give you the whole initialization. What is the distance from int to the empty string? You must delete i, n and t, so 3. From the empty string to ex? Insert e and x, so 2. From empty to empty? Nothing to do, 0. Write those as D[3, 0] = 3, D[0, 2] = 2 and D[0, 0] = 0 and you have the first row and column of every table you will ever fill.

Slide 85 sets the notation. The source x has length m, the target y has length n, and D[i, j] is the minimum edit distance between the prefix x[1..i] and the prefix y[1..j]. The answer to the whole problem is the last cell, D[m, n]. The Edit distance recurrence says how to fill every other cell from three neighbors.

D[0,0]=0,D[i,0]=i,D[0,j]=j(unit costs)D[0,0] = 0, \qquad D[i,0] = i, \qquad D[0,j] = j \quad \text{(unit costs)}
Initialization: an empty target forces i deletions, an empty source forces j insertions
D[i,j]=min{D[i1,j]+del(xi)D[i,j1]+ins(yj)D[i1,j1]+sub(xi,yj)D[i,j] = \min \begin{cases} D[i-1,j] + \mathrm{del}(x_i) \\ D[i,j-1] + \mathrm{ins}(y_j) \\ D[i-1,j-1] + \mathrm{sub}(x_i, y_j) \end{cases}
The recurrence of slide 85 and SLP3 equation 2.19

Each line is one possible last column of an optimal alignment of the two prefixes. Either the last column is x_i over a gap, in which case the rest is an optimal alignment of x[1..i-1] with y[1..j] and we pay a deletion; or it is a gap over y_j, the rest aligns x[1..i] with y[1..j-1] and we pay an insertion; or it is x_i over y_j, the rest aligns the two shorter prefixes and we pay the substitution cost, which is zero when the letters agree. There is no fourth shape a column can take, so the minimum over these three is exact. That is the optimal substructure of the previous concept written as an equation.

Now the exam favorite: why is D[i, 0] = i? The target prefix is empty, so every one of the i source letters has to disappear, and the only operation that removes a source letter is a deletion. No insertion can help, since it would produce a target letter where none is wanted, and no substitution can help, since it leaves a letter in place. At one unit per deletion the cost is exactly i. The mirror argument gives D[0, j] = j. In the general form of SLP3's pseudocode the border is built incrementally, D[i, 0] = D[i-1, 0] + del(x_i), which reduces to i when deletions cost one.

A table you can fill in one minute

Before the 10 × 10 table of part 11, fill a tiny one under unit costs: cat to cats. The first row and column are the initialization. Every other cell is the minimum of the cell above plus one, the cell to the left plus one, and the diagonal cell plus zero or one.

εcats
ε01234
c10123
a21012
t32101
D for source cat (rows) and target cats (columns), unit costs

Worked example

Two cells in full

  1. D[1, 1], c against c

    Above: D[0, 1] + 1 = 2. Left: D[1, 0] + 1 = 2. Diagonal: D[0, 0] + sub(c, c) = 0 + 0 = 0. Minimum 0.
  2. D[3, 4], cat against cats

    Above: D[2, 4] + 1 = 3. Left: D[3, 3] + 1 = 1. Diagonal: D[2, 3] + sub(t, s) = 1 + 1 = 2. Minimum 1, from the left, which is an insertion of s.
  3. Result

    D[3, 4] = 1: one insertion turns cat into cats, and the backpointer of the last cell already says so.

What the cost function can encode

Slide 86 spells out the unit Substitution cost: sub(a, b) = 0 if a = b, else 1. It also says the cost can be weighted, and this is where edit distance stops being a counting exercise and becomes a model. SLP3's caption to its pseudocode notes that costs can be specific to the letter, and its text adds that for spelling correction substitutions are more likely between letters that are next to each other on the keyboard. Kernighan, Church and Gale estimated four confusion matrices (deletion, addition, substitution and reversal counts) from the typos in 44 million words of 1988 AP newswire and used them as the channel probabilities of a noisy-channel spelling corrector; their top candidate agreed with the majority of three human judges in 87 percent of 329 cases. Set a substitution cost to the negative log of such a probability and the cheapest alignment becomes the most probable one.

Cost functionsub(a, b)Nameintention to execution
Unit (slides 85 and 86)0 if a = b, else 1Levenshtein distance5
Substitution cost 2 (SLP3 tables)0 if a = b, else 2Levenshtein's no-substitution variant8
Confusion-weightedA value from a confusion matrixNoisy-channel spelling correctionDepends on the matrix
Three cost functions for the same recurrence

A cost function can also grow a fourth operation. Damerau's 1964 study listed transposition of two adjacent letters as one of the four single-error types. The simplest extension adds a fourth line to the Wagner-Fischer table, D[i-2, j-2] + cost, that applies when x_{i-1} = y_j and x_i = y_{j-1}; this restricted form is often called optimal string alignment distance, and it can overcount when a transposed pair is edited again. Lowrance and Wagner's 1975 algorithm handles that general case, and both are commonly labelled Damerau-Levenshtein distance. The typo teh for the costs 2 with the three classic operations (delete one letter, insert it elsewhere) but only 1 with transposition. The slide recurrence does not include this move; treat it as an optional fourth line you can add when the application calls for it.

Recall

Write the recurrence for D[i, j] with its initialization and say where the answer sits.

D[0, 0] = 0, D[i, 0] = i, D[0, j] = j. Then D[i, j] = min(D[i-1, j] + del, D[i, j-1] + ins, D[i-1, j-1] + sub(x_i, y_j)). The answer is D[m, n].

Recall

Why is D[i, 0] = i?

The target prefix is empty, so all i source letters must be removed, and only deletion removes a letter. One unit each gives i, and no insertion or substitution can lower it.

Recall

flaw versus lawn: what are the Hamming distance and the edit distance, and why do they differ?

Hamming 4 (every position differs), edit distance 2 (delete f, insert n). Hamming only allows substitutions at fixed positions and needs equal lengths, so it cannot see that the shared law has simply shifted by one.

Quick check

Which operation explains why D[i, 0] = i under unit costs?

Recap

If you remember nothing else

  • Minimum edit distance is the cheapest sequence of insertions, deletions and substitutions from source to target; with unit costs it is the Levenshtein distance.
  • Applications: spelling correction, OCR post-processing, word error rate for speech recognition, approximate matching and alignment.
  • WER = (I + S + D) / reference words, read off a word-level alignment; insertions count, so it can exceed 100 percent.
  • An alignment is a set of columns; its cost is the sum of column costs; the distance is the cost of the cheapest alignment; several alignments can tie.
  • intention to execution costs 5 under unit costs and 8 when a substitution costs 2. Always state the convention.
  • The search tree over strings explodes (about 494 children per step for a 9-letter word); the grid over prefix pairs has (m + 1)(n + 1) = 100 cells.
  • Down consumes a source letter (deletion), right produces a target letter (insertion), diagonal pairs two letters (substitution or match).
  • D[0,0] = 0, D[i,0] = i, D[0,j] = j; D[i,j] is the minimum of the three neighbors plus their operation cost; the answer is D[m,n].
  • sub(a,b) = 0 if a = b else 1 is one choice; substitution cost 2, confusion-weighted costs and transposition (Damerau-Levenshtein) are others.

Sources