Algorithm Search⌘K

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
Properties
deterministiciterative
Origin
Mark D. Kernighan, Kenneth W. Church, William A. Gale, 1990

Noisy channel spelling correction is a method that corrects a typed string xx that is not a word by choosing the word ww that maximizes P(w) P(x∣w)P(w)\, P(x \mid w). The prior P(w)P(w) comes from word counts in a corpus, and the channel P(x∣w)P(x \mid w) is the probability that a writer who meant ww typed xx. Kernighan, Church and Gale described it in 1990 for words one edit away from xx, 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 xx, a vocabulary VV with counts c(w)c(w) and total NN, and an error model. If x∈Vx \in V, keep it; correcting real words needs context and is a variant. Otherwise return

w^=arg⁡max⁡w∈VP(w) P(x∣w),P(w)=c(w)N,\hat w = \arg\max_{w \in V} P(w)\, P(x \mid w), \qquad P(w) = \frac{c(w)}{N},

with ties to the smaller word in string order. By Bayes' theorem, P(w∣x)=P(w)P(x∣w)/P(x)P(w \mid x) = P(w) P(x \mid w) / P(x), and P(x)P(x) is the same for every ww, so w^\hat w 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 ww to xx table entry divided by
delete cc after pp ("pc" typed as "p") del[p,c]\mathrm{del}[p, c] count[pc]\mathrm{count}[pc]
insert cc after pp ("p" typed as "pc") ins[p,c]\mathrm{ins}[p, c] count[p]\mathrm{count}[p]
substitute cc by ee (cc typed as ee) sub[c,e]\mathrm{sub}[c, e] count[c]\mathrm{count}[c]
swap "cd" into "dc" trans[c,d]\mathrm{trans}[c, d] count[cd]\mathrm{count}[cd]

When several edits turn ww into xx, P(x∣w)P(x \mid w) is the sum of their probabilities.

The algorithm

The candidates are found from xx by undoing each possible edit, so the vocabulary is only used for lookups:

  1. NOISY-CHANNEL-CORRECT(x, V, c, M) ▷ M: the four tables and the letter counts
  2. 1if x ∈ V then return x
  3. 2C ← empty map from words to channel probabilities
  4. 3for each position i from 0 to |x| and each letter a: ▷ a was deleted
  5. 4add del[x(i−1), a] / count[x(i−1) a] to C[x(<i) a x(≥i)]
  6. 5for each position i of x:
  7. 6add ins[x(i−1), x(i)] / count[x(i−1)] to C[x without x(i)] ▷ x(i) was inserted
  8. 7for each letter a ≠ x(i): add sub[a, x(i)] / count[a] to C[x with a at i]
  9. 8for each i with x(i) ≠ x(i+1): ▷ two letters were swapped
  10. 9add trans[x(i+1), x(i)] / count[x(i+1) x(i)] to C[x with x(i), x(i+1) swapped]
  11. 10keep in C only the words of V with a positive value
  12. 11for each w in C: score(w) ← c(w)/N · C[w]
  13. 12return the w of C with the largest score, ties to the smaller word

Here x(−1)x(-1) 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 count[t]=31\mathrm{count}[t] = 31, count[te]=9\mathrm{count}[te] = 9, count[ti]=4\mathrm{count}[ti] = 4 and count[h]=9\mathrm{count}[h] = 9.

For xx = "sortd", lines L3 to L9 find two words of the vocabulary. "sorted" lost an "e" after "t", with the channel 6/9≈0.66676/9 \approx 0.6667 and the prior 5/795/79, so the score is 0.042190.04219. "sort" got an extra "d" after "t", with the channel 1/31≈0.032261/31 \approx 0.03226 and the prior 1/791/79, so the score is 0.0004080.000408. The answer is "sorted", which both factors favour.

For xx = "tme" the two factors disagree:

candidate edit P(x∣w)P(x \mid w) P(w)P(w) score
the h typed as m 1/9=0.11111/9 = 0.1111 3/793/79 0.004219
time i deleted after t 3/4=0.753/4 = 0.75 1/791/79 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 2.8×10−92.8 \times 10^{-9} and "actress" about 2.7×10−92.7 \times 10^{-9}, 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 ww to xx: 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 ww is the sum of the probabilities of all derivations of xx from ww, which is P(x∣w)P(x \mid w), and every word with P(x∣w)>0P(x \mid w) > 0 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 VV be a finite vocabulary with counts c(w)≥1c(w) \ge 1 and total N=∑wc(w)N = \sum_w c(w), so P(w)=c(w)/NP(w) = c(w)/N. Let Σ\Sigma be the alphabet and #\# a boundary letter not in Σ\Sigma. For a string uu, write uju_j for its letter at position jj (from 0) and u−1=#u_{-1} = \#. The error model has four tables and a count table count\mathrm{count} of letters and letter pairs. A derivation of xx from ww is one of these single edits, with its weight:

  • deletion of wjw_j: x=w<jw>jx = w_{<j} w_{>j}, weight del[wj−1,wj]/count[wj−1wj]\mathrm{del}[w_{j-1}, w_j] / \mathrm{count}[w_{j-1} w_j];
  • insertion of aa before position jj: x=w<j a w≥jx = w_{<j}\, a\, w_{\ge j}, weight ins[wj−1,a]/count[wj−1]\mathrm{ins}[w_{j-1}, a] / \mathrm{count}[w_{j-1}];
  • substitution of wjw_j by e≠wje \ne w_j: weight sub[wj,e]/count[wj]\mathrm{sub}[w_j, e] / \mathrm{count}[w_j];
  • transposition of wjwj+1w_j w_{j+1} with wj≠wj+1w_j \ne w_{j+1}: weight trans[wj,wj+1]/count[wjwj+1]\mathrm{trans}[w_j, w_{j+1}] / \mathrm{count}[w_j w_{j+1}].

A weight with a zero numerator or denominator is 00. The channel is P(x∣w)=∑P(x \mid w) = \sum of the weights of all derivations of xx from ww, and P(x∣w)=0P(x \mid w) = 0 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 x∉Vx \notin V, lines L2 to L10 compute the map CC with C[w]=P(x∣w)C[w] = P(x \mid w) for every w∈Vw \in V with P(x∣w)>0P(x \mid w) > 0, and with no other keys.

Proof. Lines L3 to L9 enumerate tuples, and each tuple names one string ww and one weight. We match these tuples one to one with the derivations of xx from strings ww, with the same weight.

  • A deletion of wjw_j gives x=w<jw>jx = w_{<j} w_{>j}, so x<j=w<jx_{<j} = w_{<j}, the letter before is xj−1=wj−1x_{j-1} = w_{j-1} (or #\# for j=0j = 0), and w=x<j wj x≥jw = x_{<j}\, w_j\, x_{\ge j}. This is the tuple (i,a)=(j,wj)(i, a) = (j, w_j) of lines L3 and L4, with the weight del[xi−1,a]/count[xi−1a]\mathrm{del}[x_{i-1}, a] / \mathrm{count}[x_{i-1} a]. Conversely each tuple (i,a)(i, a) of line L4 is the deletion of position ii from w=x<i a x≥iw = x_{<i}\, a\, x_{\ge i}.
  • An insertion of aa before position jj of ww gives xj=ax_j = a and xj−1=wj−1x_{j-1} = w_{j-1}, so w=xw = x without xjx_j. This is the tuple i=ji = j of line L6, and conversely.
  • A substitution of wjw_j by ee gives xj=ex_j = e, so ww is xx with a=wj≠xja = w_j \ne x_j at position jj. This is the tuple (j,a)(j, a) of line L7, with the weight sub[a,xj]/count[a]\mathrm{sub}[a, x_j] / \mathrm{count}[a], and conversely.
  • A transposition at jj gives xj=wj+1x_j = w_{j+1} and xj+1=wjx_{j+1} = w_j with xj≠xj+1x_j \ne x_{j+1}. This is the tuple i=ji = j of lines L8 and L9, with the weight trans[xi+1,xi]/count[xi+1xi]\mathrm{trans}[x_{i+1}, x_i] / \mathrm{count}[x_{i+1} x_i], 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 C[w]C[w] is the sum over all derivations of xx from ww, which is P(x∣w)P(x \mid w). Line L10 keeps a key only if w∈Vw \in V and a positive weight was added. □\square

Theorem 2 (output). For x∉Vx \notin V, the procedure returns a word w∗∈Vw^\ast \in V that maximizes P(w)P(x∣w)P(w) P(x \mid w) over all of VV, the smallest such word in string order, with the score P(w∗)P(x∣w∗)P(w^\ast) P(x \mid w^\ast); if every word has the score 00, it returns no word. For x∈Vx \in V it returns xx unchanged.

Proof. Line L1 handles x∈Vx \in V. Otherwise, by Lemma 1, the words outside CC have P(x∣w)=0P(x \mid w) = 0 and score 00, and the words in CC have the score c(w)/N⋅C[w]>0c(w)/N \cdot C[w] > 0 of line L11. Line L12 scans the words of CC 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. □\square

Lemma 3 (Bayes). For a fixed xx with P(x)>0P(x) > 0, the argmax of P(w∣x)P(w \mid x) is the argmax of P(w)P(x∣w)P(w) P(x \mid w).

Proof. P(w∣x)=P(w)P(x∣w)/P(x)P(w \mid x) = P(w) P(x \mid w) / P(x) by Bayes' theorem, and P(x)P(x) does not depend on ww. □\square

Cost. For ∣x∣=n|x| = n and ∣Σ∣=σ|\Sigma| = \sigma, lines L3 to L9 form at most (n+1)σ+n+n(σ−1)+(n−1)=O(nσ)(n + 1)\sigma + n + n(\sigma - 1) + (n - 1) = O(n\sigma) strings of length at most n+1n + 1. With a hash table for VV and for the tables, each string costs O(n)O(n) expected time to build and look up, so a correction costs O(n2σ)O(n^2 \sigma) expected time and O(nσ)O(n\sigma) extra space. The work does not depend on ∣V∣|V|.

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 ∣x∣=n|x| = n and an alphabet of ss letters, lines L3 to L9 build O(ns)O(ns) strings of length at most n+1n + 1. Each costs O(n)O(n) to build and to look up in hash tables for VV and for the confusion tables, so a correction takes O(n2s)O(n^2 s) expected time and O(ns)O(ns) 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 (s+1)2(s + 1)^2 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 P(w)P(w) by the probability of ww 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 xx itself to the candidates with a probability of no error.
  • Generic edits. Brill and Moore's partition model splits ww 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 sub[x,w]\mathrm{sub}[x, w] or sub[w,x]\mathrm{sub}[w, x]. 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 xx 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 xx by two edits of the same kind, as "acres" reaches "acress" by two insertions, ins[e,s]\mathrm{ins}[e, s] and ins[s,s]\mathrm{ins}[s, s]. 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.

irtoy.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example