Algorithmcore
Noisy channel spelling correction
Also called Kernighan-Church-Gale correction, noisy channel model of spelling.
Chooses the correction w that maximizes P(w) P(typed word | w), from a language model and an error model of single edits.
- Time
- O(n^2 s) expected
- Space
- O(n s) extra
- Where
- n = the length of the typed string; s = the size of the alphabet
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mark D. Kernighan, Kenneth W. Church, William A. Gale, 1990
Noisy channel spelling correction is a method that corrects a typed string that is not a word by choosing the word that maximizes . The prior comes from word counts in a corpus, and the channel is the probability that a writer who meant typed . Kernighan, Church and Gale described it in 1990 for words one edit away from , with the channel read from four confusion matrices of typing errors. The edit distance and Damerau-Levenshtein distance pages count edits with fixed costs; this page puts probabilities on the edits and on the words, and the weighted edit distance page covers costs that vary by letter.
In plain words
When someone types a word that is not in the dictionary, the program asks two questions about each nearby word. How common is this word? And how likely is this particular slip, if the person meant this word? Some slips are common, such as missing a letter after "t" or hitting a key next to the right one, and some are rare. The program multiplies the two answers and picks the word with the best result. A rare word can win when the slip that leads to it is very common, and a common word can win even with an odd slip.
The problem
The input is a typed string , a vocabulary with counts and total , and an error model. If , keep it; correcting real words needs context and is a variant. Otherwise return
with ties to the smaller word in string order. By Bayes' theorem, , and is the same for every , so is also the most probable intended word.
The error model allows one edit. Following Jurafsky and Martin's Equation D.6, with before the first letter, the channel of one edit is a confusion count over the corpus count of the intended letters:
| edit from to | table entry | divided by |
|---|---|---|
| delete after ("pc" typed as "p") | ||
| insert after ("p" typed as "pc") | ||
| substitute by ( typed as ) | ||
| swap "cd" into "dc" |
When several edits turn into , is the sum of their probabilities.
The algorithm
The candidates are found from by undoing each possible edit, so the vocabulary is only used for lookups:
NOISY-CHANNEL-CORRECT(x, V, c, M) ▷ M: the four tables and the letter counts- 1
if x ∈ V then return x - 2
C ← empty map from words to channel probabilities - 3
for each position i from 0 to |x| and each letter a: ▷ a was deleted - 4
add del[x(i−1), a] / count[x(i−1) a] to C[x(<i) a x(≥i)] - 5
for each position i of x: - 6
add ins[x(i−1), x(i)] / count[x(i−1)] to C[x without x(i)] ▷ x(i) was inserted - 7
for each letter a ≠ x(i): add sub[a, x(i)] / count[a] to C[x with a at i] - 8
for each i with x(i) ≠ x(i+1): ▷ two letters were swapped - 9
add trans[x(i+1), x(i)] / count[x(i+1) x(i)] to C[x with x(i), x(i+1) swapped] - 10
keep in C only the words of V with a positive value - 11
for each w in C: score(w) ← c(w)/N · C[w] - 12
return the w of C with the largest score, ties to the smaller word
Here is . A zero count in a table, or a zero letter count, gives the probability 0, and such a candidate is dropped at line L10.
Example
Use the eight documents of the shared toy collection as the corpus: 79 tokens of 50 words, with before each token for the letter counts. Take these confusion counts, which stand for a small log of typing errors:
| table | entries |
|---|---|
| del | [t, e] = 6, [t, i] = 3, [e, r] = 2, [r, a] = 1 |
| ins | [t, d] = 1, [s, s] = 2 |
| sub | [h, m] = 1, [e, a] = 4, [a, e] = 3 |
| trans | [i, s] = 2, [e, i] = 1 |
The corpus has , , and .
For = "sortd", lines L3 to L9 find two words of the vocabulary. "sorted" lost an "e" after "t", with the channel and the prior , so the score is . "sort" got an extra "d" after "t", with the channel and the prior , so the score is . The answer is "sorted", which both factors favour.
For = "tme" the two factors disagree:
| candidate | edit | score | ||
|---|---|---|---|---|
| the | h typed as m | 0.004219 | ||
| time | i deleted after t | 0.009494 |
"the" is three times as common as "time", but losing an "i" after "t" is much more likely than typing "m" for "h" in this error log, so the answer is "time". Jurafsky and Martin show the same effect on real data: for "acress" with COCA counts, "across" scores about and "actress" about , so a unigram prior picks "across" although the writer meant "actress" in their example sentence. Only context can settle such cases.
Correctness
The file proofs/correctness.md gives the proof. Each tuple that lines L3 to L9 enumerate is the inverse of exactly one single edit from some string to : the kind of edit, its position and its letter fix both the string and the confusion entry. So the value that line L10 keeps for is the sum of the probabilities of all derivations of from , which is , and every word with appears. Words that do not appear have score 0. Line L12 scans the candidates in string order and replaces the best only on a strictly larger score, which gives the tie rule.
Proof: The noisy channel corrector returns the exact argmax of P(w) P(x | w) over one-edit candidatesfull
Let be a finite vocabulary with counts and total , so . Let be the alphabet and a boundary letter not in . For a string , write for its letter at position (from 0) and . The error model has four tables and a count table of letters and letter pairs. A derivation of from is one of these single edits, with its weight:
- deletion of : , weight ;
- insertion of before position : , weight ;
- substitution of by : weight ;
- transposition of with : weight .
A weight with a zero numerator or denominator is . The channel is of the weights of all derivations of from , and when there is none. This is the one-edit channel of Kernighan, Church and Gale, with the sum over derivations that Jurafsky and Martin use for "acres".
Lemma 1 (candidate generation). For a string , lines L2 to L10 compute the map with for every with , and with no other keys.
Proof. Lines L3 to L9 enumerate tuples, and each tuple names one string and one weight. We match these tuples one to one with the derivations of from strings , with the same weight.
- A deletion of gives , so , the letter before is (or for ), and . This is the tuple of lines L3 and L4, with the weight . Conversely each tuple of line L4 is the deletion of position from .
- An insertion of before position of gives and , so without . This is the tuple of line L6, and conversely.
- A substitution of by gives , so is with at position . This is the tuple of line L7, with the weight , and conversely.
- A transposition at gives and with . This is the tuple of lines L8 and L9, with the weight , and conversely.
Distinct derivations give distinct tuples, because the kind of edit, the position and the letter determine the tuple. So the sum of the weights that line L10 adds into is the sum over all derivations of from , which is . Line L10 keeps a key only if and a positive weight was added.
Theorem 2 (output). For , the procedure returns a word that maximizes over all of , the smallest such word in string order, with the score ; if every word has the score , it returns no word. For it returns unchanged.
Proof. Line L1 handles . Otherwise, by Lemma 1, the words outside have and score , and the words in have the score of line L11. Line L12 scans the words of in string order and replaces the best word only on a strictly larger score, so it keeps the first word, that is the smallest, among those with the largest score.
Lemma 3 (Bayes). For a fixed with , the argmax of is the argmax of .
Proof. by Bayes' theorem, and does not depend on .
Cost. For and , lines L3 to L9 form at most strings of length at most . With a hash table for and for the tables, each string costs expected time to build and look up, so a correction costs expected time and extra space. The work does not depend on .
The test file checks Theorem 2 against a forward enumeration from every word of the vocabulary, with exact rational weights, on the toy model of the page and on random models over a three-letter alphabet in which several derivations often lead to the same word.
Complexity
For and an alphabet of letters, lines L3 to L9 build strings of length at most . Each costs to build and to look up in hash tables for and for the confusion tables, so a correction takes expected time and extra space, independent of the size of the vocabulary. Building the letter counts is one pass over the corpus, and the confusion tables have at most entries each.
Properties
- Two independent parts. The language model and the error model are trained apart, from text and from pairs of typos and corrections, and either can be replaced.
- Exact for its model. The answer is the exact argmax over the vocabulary for a one-edit channel, not an approximation; words two edits away are never proposed.
- Context-free. The unigram prior ignores the surrounding words, so it cannot tell "across" from "actress" by meaning.
- Deterministic. The tie rule fixes the answer when two scores are equal.
Variants and improvements
- Context. Replace by the probability of given the neighbouring words, as from a bigram model. This also makes it possible to correct real words, such as "there" for "their", by adding itself to the candidates with a probability of no error.
- Generic edits. Brill and Moore's partition model splits into parts and lets each part become any string, such as "ph" typed as "f" or "al" typed as "le", with probabilities that depend on the position in the word (beginning, middle or end). It takes the probability of the best partition in place of a sum over all of them, as Jurafsky and Martin's Equation D.11 writes it.
- Learning the tables. Kernighan, Church and Gale also estimated the confusion matrices by iteration: start from equal values, correct a corpus of typos, count the edits of the chosen corrections, and repeat. This is close in spirit to expectation maximization.
- Candidates at distance two. Apply the edits twice, or search the vocabulary with a Levenshtein automaton or another approximate dictionary lookup method. The channel of two edits is the product of their probabilities.
- Query spelling. For a search box, train the prior on past queries, so that names and new words that a dictionary lacks are known, and correct whole queries word by word with a model of the query.
- Smoothing. Add a small constant to every count, so that an edit or a word that the training data did not show still gets a small probability.
When to use it
Use the noisy channel when you have word counts from the target domain and some data about typing errors, and you want a ranked list of corrections with a clear meaning. It suits search boxes, form fields and text editors, where most errors are one edit away. When the errors depend on context or on sound, add a context model or generic edits.
Pitfalls
- Zero counts. An edit that the error log never shows gets probability 0, which hides the right word. Smooth the tables.
- Order of the indexes. Papers write the confusion matrices with different index orders, such as or . State which letter is the intended one and which is the typed one, as the table of this page does.
- Unknown words. A correct word that is not in the vocabulary, such as a new product name, is "corrected" to a known one. Keep unless the best candidate beats it by a margin, or ask the user.
- Mixing the two models. The prior and the channel are on very different scales. Many systems put a weight on the log of one of them, tuned on held-out data.
- Several derivations. One word can reach by two edits of the same kind, as "acres" reaches "acress" by two insertions, and . Add their probabilities, or the channel is too small.
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
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.
Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""
DOCS = {
1: "binary search finds a key in a sorted array",
2: "merge sort merges two sorted runs into one sorted array",
3: "an inverted index maps each term to a posting list",
4: "a posting list is a sorted list of document ids",
5: "skip pointers speed up the merge of two posting lists",
6: "a hash table finds a key in constant expected time",
7: "search engines rank documents by a score for the query",
8: "the sorted array of ids is compressed with gap encoding",
}
N = len(DOCS)
QUERIES = {
"q1": "sorted array search",
"q2": "posting list merge",
"q3": "rank documents",
"q4": "quantum circuit",
}
# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
"q1": {1: 2, 2: 1, 8: 1},
"q2": {5: 2, 4: 1, 3: 1},
"q3": {7: 2},
"q4": {},
}
# A fixed run for the metric pages, as scores per query.
RUN = {
"q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}
def tokenize(text):
"""Lower-case words split on spaces."""
return text.lower().split()
_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}
def tf(term, doc_id):
"""Number of times term occurs in document doc_id."""
return _TOKENS[doc_id].count(term)
def df(term):
"""Number of documents that contain term."""
return sum(1 for toks in _TOKENS.values() if term in toks)
def cf(term):
"""Number of occurrences of term in the whole collection."""
return sum(toks.count(term) for toks in _TOKENS.values())
def doc_len(doc_id):
"""Number of tokens in document doc_id."""
return len(_TOKENS[doc_id])
def avgdl():
"""Average document length in tokens."""
return sum(len(toks) for toks in _TOKENS.values()) / N
noisy_channel_spelling_correction.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/noisy-channel-spelling-correction/. The authors are listed in prov/01YMRN.jsonl.
"""Noisy channel spelling correction in the style of Kernighan, Church and Gale.
A typed string x that is not a word of the vocabulary is corrected to the
word w that maximizes P(w) P(x | w). The candidates are the words that
give x by one edit: a deletion, an insertion, a substitution, or a swap of
two adjacent letters. The channel P(x | w) of one edit is a confusion count
divided by the count of the intended letters in a corpus, as in the
four confusion matrices of the method. When several edits turn w into x,
their probabilities are added.
The keys of the confusion tables are always (intended, typed context):
dels[(p, c)] number of times "pc" was typed as "p"
ins[(p, c)] number of times "p" was typed as "pc"
subs[(c, e)] number of times the letter c was typed as e
trans[(c, d)] number of times "cd" was typed as "dc"
The letter p before an edit at the start of a word is "#".
Ties between candidates go to the smaller word in string order.
"""
from collections import Counter
BOUNDARY = "#"
def char_counts(tokens):
"""Counts of single letters and adjacent pairs, with "#" before each token."""
counts = Counter()
for t in tokens:
s = BOUNDARY + t
for i, ch in enumerate(s):
counts[ch] += 1
if i + 1 < len(s):
counts[s[i : i + 2]] += 1
return counts
class ErrorModel:
"""The channel P(x | w) for one edit, from four confusion tables."""
def __init__(self, dels, ins, subs, trans, chars):
self.dels = dict(dels)
self.ins = dict(ins)
self.subs = dict(subs)
self.trans = dict(trans)
self.chars = dict(chars)
def _ratio(self, table, key, denom):
n = table.get(key, 0)
d = self.chars.get(denom, 0)
return n / d if n and d else 0.0
def p_deletion(self, p, c):
return self._ratio(self.dels, (p, c), p + c)
def p_insertion(self, p, c):
return self._ratio(self.ins, (p, c), p)
def p_substitution(self, c, e):
return self._ratio(self.subs, (c, e), c)
def p_transposition(self, c, d):
return self._ratio(self.trans, (c, d), c + d)
def candidates(x, vocab, model, alphabet):
"""Map each vocabulary word w one edit from x to P(x | w), by undoing each edit of x."""
out = {} # @line L2
def add(w, p):
if p > 0.0 and w in vocab: # @line L10
out[w] = out.get(w, 0.0) + p
for i in range(len(x) + 1): # @line L3
prev = x[i - 1] if i > 0 else BOUNDARY
for c in alphabet: # x lost the letter c after prev: w = x[:i] + c + x[i:]
add(x[:i] + c + x[i:], model.p_deletion(prev, c)) # @line L4
for i in range(len(x)): # @line L5
prev = x[i - 1] if i > 0 else BOUNDARY
add(x[:i] + x[i + 1 :], model.p_insertion(prev, x[i])) # x has an extra x[i] # @line L6
for c in alphabet: # x has x[i] where w has c
if c != x[i]:
add(x[:i] + c + x[i + 1 :], model.p_substitution(c, x[i])) # @line L7
for i in range(len(x) - 1): # @line L8
a, b = x[i], x[i + 1]
if a != b: # x has "ab" where w has "ba"
add(x[:i] + b + a + x[i + 2 :], model.p_transposition(b, a)) # @line L9
return out
def correct(x, word_counts, model, alphabet=None):
"""Return (best word, its score P(w) P(x | w)), or (x, None) for a known word, or (None, 0.0)."""
if x in word_counts: # @line L1
return x, None
if alphabet is None:
alphabet = sorted({ch for w in word_counts for ch in w})
total = sum(word_counts.values())
best, best_score = None, 0.0
for w, channel in sorted(candidates(x, word_counts, model, alphabet).items()):
score = word_counts[w] / total * channel # @line L11
if score > best_score: # ties keep the smaller word, seen first
best, best_score = w, score
return best, best_score # @line L12
test_noisy_channel_spelling_correction.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/noisy-channel-spelling-correction/. The authors are listed in prov/01YMRN.jsonl.
import math
import random
from collections import Counter
from fractions import Fraction
import pytest
import irtoy
from noisy_channel_spelling_correction import BOUNDARY, ErrorModel, candidates, char_counts, correct
TOKENS = [t for d in sorted(irtoy.DOCS) for t in irtoy.tokenize(irtoy.DOCS[d])]
WORDS = Counter(TOKENS)
# The toy confusion tables of the page.
DELS = {("t", "e"): 6, ("t", "i"): 3, ("e", "r"): 2, ("r", "a"): 1}
INS = {("t", "d"): 1, ("s", "s"): 2}
SUBS = {("h", "m"): 1, ("e", "a"): 4, ("a", "e"): 3}
TRANS = {("i", "s"): 2, ("e", "i"): 1}
def toy_model():
return ErrorModel(DELS, INS, SUBS, TRANS, char_counts(TOKENS))
def forward_channel(vocab, dels, ins, subs, trans, chars, alphabet):
"""Apply every single edit to every word w and record the exact P(x | w)."""
def ratio(table, key, denom):
n, d = table.get(key, 0), chars.get(denom, 0)
return Fraction(n, d) if n and d else Fraction(0)
chan = {}
def put(x, w, p):
if p:
chan.setdefault(x, {})
chan[x][w] = chan[x].get(w, Fraction(0)) + p
for w in vocab:
s = BOUNDARY + w # s[j] is the letter before position j of w
for j in range(len(w)): # delete w[j]
put(w[:j] + w[j + 1 :], w, ratio(dels, (s[j], w[j]), s[j] + w[j]))
for j in range(len(w) + 1): # insert c after position j - 1
for c in alphabet:
put(w[:j] + c + w[j:], w, ratio(ins, (s[j], c), s[j]))
for j in range(len(w)): # substitute w[j] by e
for e in alphabet:
if e != w[j]:
put(w[:j] + e + w[j + 1 :], w, ratio(subs, (w[j], e), w[j]))
for j in range(len(w) - 1): # swap w[j] and w[j + 1]
if w[j] != w[j + 1]:
put(w[:j] + w[j + 1] + w[j] + w[j + 2 :], w, ratio(trans, (w[j], w[j + 1]), w[j : j + 2]))
return chan
def brute(x, vocab, chan):
"""Exact argmax of P(w) P(x | w) over every word of the vocabulary; ties to the smaller word."""
total = sum(vocab.values())
scores = {w: Fraction(vocab[w], total) * chan.get(x, {}).get(w, Fraction(0)) for w in vocab}
top = max(scores.values())
return top, sorted(w for w in vocab if scores[w] == top), scores
def check(x, vocab, model, chan, alphabet):
got, score = correct(x, vocab, model, alphabet)
top, winners, scores = brute(x, vocab, chan)
if top == 0:
assert got is None and score == 0.0
return
assert got in winners
if len(winners) == 1:
assert got == winners[0]
assert math.isclose(score, float(top), rel_tol=1e-12)
# The backward candidate set equals the forward one.
back = candidates(x, vocab, model, alphabet)
fwd = chan.get(x, {})
assert set(back) == {w for w in fwd if w in vocab}
for w, p in back.items():
assert math.isclose(p, float(fwd[w]), rel_tol=1e-12)
def test_examples_of_the_page():
m = toy_model()
w, s = correct("sortd", WORDS, m)
assert w == "sorted" and math.isclose(s, 5 / 79 * 6 / 9, rel_tol=1e-12)
w, s = correct("tme", WORDS, m)
assert w == "time" and math.isclose(s, 1 / 79 * 3 / 4, rel_tol=1e-12)
c = candidates("tme", WORDS, m, sorted({ch for w in WORDS for ch in w}))
assert math.isclose(c["the"], 1 / 9, rel_tol=1e-12) and math.isclose(c["time"], 3 / 4, rel_tol=1e-12)
assert correct("sorted", WORDS, m) == ("sorted", None)
assert correct("qqq", WORDS, m) == (None, 0.0)
def test_toy_model_against_brute_force():
m = toy_model()
alphabet = sorted({ch for w in WORDS for ch in w})
chan = forward_channel(WORDS, DELS, INS, SUBS, TRANS, m.chars, alphabet)
typed = sorted(x for x in chan if x not in WORDS)
rng = random.Random(1)
noise = ["".join(rng.choice(alphabet) for _ in range(rng.randint(1, 6))) for _ in range(300)]
words = sorted(WORDS)
for _ in range(300): # a word with one random edit, most of which the tables give probability 0
w = rng.choice(words)
j = rng.randrange(len(w))
noise.append(w[:j] + rng.choice(alphabet) + w[j + 1 :])
for x in typed + noise + ["sortd", "tme", "lsit", "postng", "arry", "zzzz"]:
if x not in WORDS:
check(x, WORDS, m, chan, alphabet)
assert len(typed) > 50
@pytest.mark.parametrize("seed", range(6))
def test_random_models_against_brute_force(seed):
rng = random.Random(seed)
alphabet = ["a", "b", "c"]
vocab = Counter()
while len(vocab) < 12:
w = "".join(rng.choice(alphabet) for _ in range(rng.randint(1, 4)))
vocab[w] = rng.randint(1, 5)
ctx = alphabet + [BOUNDARY]
dels = {(p, c): rng.randint(0, 4) for p in ctx for c in alphabet}
ins = {(p, c): rng.randint(0, 4) for p in ctx for c in alphabet}
subs = {(c, e): rng.randint(0, 4) for c in alphabet for e in alphabet if c != e}
trans = {(c, d): rng.randint(0, 4) for c in alphabet for d in alphabet if c != d}
chars = char_counts([w for w, n in vocab.items() for _ in range(n)])
m = ErrorModel(dels, ins, subs, trans, chars)
chan = forward_channel(vocab, dels, ins, subs, trans, chars, alphabet)
typed = sorted(x for x in chan if x not in vocab)
for x in typed:
check(x, vocab, m, chan, alphabet)
History
Kernighan, Church and Gale wrote the program correct at Bell Labs and described it at COLING 1990. It took typos flagged by the Unix spell program and ranked the words one edit away by a prior times a channel probability from four confusion matrices of deletions, insertions, substitutions and reversals. The method is the noisy channel model of Shannon applied to spelling, the same model that speech recognition and machine translation used at the time. Brill and Moore generalized the error model to string-to-string edits in 2000. The method is now a standard textbook example, as in Appendix D of Jurafsky and Martin.
References
- Mark D. Kernighan, Kenneth W. Church and William A. Gale, A spelling correction program based on a noisy channel model, Proceedings of the 13th International Conference on Computational Linguistics (COLING 1990), volume 2, 205-210, the candidates that differ from the typo by one insertion, deletion, substitution or reversal, the scoring by prior times channel, the four confusion matrices, and their estimation by iteration from equal starting values
- Daniel Jurafsky and James H. Martin, Speech and Language Processing, 3rd edition draft, Appendix D: Spelling Correction and the Noisy Channel, https://web.stanford.edu/~jurafsky/slp3/D.pdf, Equation D.6 (the channel probability of each edit type from the del, ins, sub and trans matrices and the letter counts), the acress example with its candidates and scores (Figures D.3 to D.5), and the section on the Brill and Moore error model
- Eric Brill and Robert C. Moore, An improved error model for noisy channel spelling correction, Proceedings of the 38th Annual Meeting of the Association for Computational Linguistics (ACL 2000), 286-293, the partition model, in which a word is split into parts and each part is rewritten as a string of any length, with probabilities that depend on the position in the word
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 01YMRN Edit this page History Report an error Markdown