Statistical Machine Translation Foundations › Building a Miniature SMT System in Python

Michael BrenndoerferNovember 26, 202622 min read
Language AI HandbookAll chapters
Part 27 of 67Machine Translation and Speech Translation
Chapter 190Statistical Machine Translation Foundations › Building a Miniature SMT System in Python
Reading section 9 of 12 · Building a Miniature SMT System in Python · 22 minSection 9 of 12 · 22 min

Section 9 of 12 · 22 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

We now implement the full pipeline. To make alignment quality measurable, we generate a synthetic parallel corpus from a tiny grammar, which gives us exact gold alignments for free. The target language "Zeta" is engineered to differ from English in two ways that matter:

  • It is verb-final: object before verb (ze mika ze voso tira = "the cat the dog sees").
  • It uses postpositions: ino follows its noun rather than preceding it.

The toy lexicon assigns a single counterpart to each lexical item. The generator records which positions correspond, so we know the gold links even when a token occurs twice. Natural parallel text can add one-to-many correspondences, morphological splitting, and freer translations.

Step 1: Generate a Corpus with Gold Alignments

We define the lexicon and three sentence templates. Each template returns the English tokens, the Zeta tokens, and the gold alignment as a list of (english_index, zeta_index) pairs.

PythonIn [8]
CollapseExpand
LEXICON = {
    "the": "ze",
    "a": "un",
    "cat": "mika",
    "dog": "voso",
    "bird": "turi",
    "fish": "paku",
    "sees": "tira",
    "chases": "kavu",
    "big": "runa",
    "small": "piti",
    "is": "va",
    "in": "ino",
    ".": ".",
}


def z(word):
    return LEXICON[word]


def transitive(n1, verb, n2, det):
    """English SVO -> Zeta SOV, determiners preserved."""
    en = [det, n1, verb, det, n2, "."]
    ze = [z(det), z(n1), z(det), z(n2), z(verb), "."]
    gold = [(0, 0), (1, 1), (3, 2), (4, 3), (2, 4), (5, 5)]
    return en, ze, gold


def copular(n1, adj):
    """Adjective follows the noun; copula moves to the end."""
    en = ["the", n1, "is", adj, "."]
    ze = [z("the"), z(n1), z(adj), z("is"), "."]
    gold = [(0, 0), (1, 1), (3, 2), (2, 3), (4, 4)]
    return en, ze, gold


def locative(n1, n2):
    """Zeta uses a postposition, so 'in' moves after its noun."""
    en = ["the", n1, "is", "in", "the", n2, "."]
    ze = [z("the"), z(n1), z("the"), z(n2), z("in"), z("is"), "."]
    gold = [(0, 0), (1, 1), (4, 2), (5, 3), (3, 4), (2, 5), (6, 6)]
    return en, ze, gold

Now we enumerate every combination, which gives 88 unique sentence pairs.

PythonIn [9]
CollapseExpand
NOUNS = ["cat", "dog", "bird", "fish"]
VERBS = ["sees", "chases"]
ADJECTIVES = ["big", "small"]

corpus = []
for det in ["the", "a"]:
    for n1 in NOUNS:
        for verb in VERBS:
            for n2 in NOUNS:
                corpus.append(transitive(n1, verb, n2, det))
for n1 in NOUNS:
    for adj in ADJECTIVES:
        corpus.append(copular(n1, adj))
for n1 in NOUNS:
    for n2 in NOUNS:
        corpus.append(locative(n1, n2))

rng = random.Random(13)
rng.shuffle(corpus)
n_train = int(0.9 * len(corpus))
train, test = corpus[:n_train], corpus[n_train:]

# Guarantee every Zeta word appears in training so the phrase table can cover the test set.
seen_zeta = {w for _, ze, _ in train for w in ze}
for pair in list(test):
    if not set(pair[1]) <= seen_zeta:
        test.remove(pair)
        train.append(pair)
        seen_zeta |= set(pair[1])

train_pairs = [(en, ze) for en, ze, _ in train]
gold_train = [gold for _, _, gold in train]
ConsoleOut [10]
CollapseExpand
Total sentence pairs: 88
Training pairs:       79
Held-out pairs:       9

Example pair
  English: the cat is in the fish .
  Zeta:    ze mika ze paku ino va .
  gold:    [(0, 0), (1, 1), (4, 2), (5, 3), (3, 4), (2, 5), (6, 6)]

The corpus splits into 79 training pairs and 9 held-out pairs. The gold alignment for the first training pair is a set of index pairs such as (0, 0) and (1, 1), which we can compare directly against what the aligner predicts. The vocabulary-coverage check just above the split is a small but important piece of experimental hygiene: if a held-out sentence contains a Zeta word that never appeared in training, the phrase table cannot possibly translate it, and the resulting failure would say nothing about the decoder.

Step 2: Train IBM Model 1 with EM

We write the model as three small functions: one to build vocabularies, one to initialize uniformly, and one to run a single EM iteration. Keeping the E-step and M-step together emphasizes that the only thing that changes between iterations is the tt table.

PythonIn [11]
CollapseExpand
NULL = "<NULL>"


def build_vocab(pairs):
    src = {NULL}
    tgt = set()
    for s, t in pairs:
        src.update(s)
        tgt.update(t)
    return sorted(src), sorted(tgt)


def uniform_table(src_vocab, tgt_vocab):
    u = 1.0 / len(tgt_vocab)
    return {e: {f: u for f in tgt_vocab} for e in src_vocab}


def em_step(t_table, bitext, src_vocab, tgt_vocab):
    """One E-step plus M-step of IBM Model 1. Returns a new t table."""
    count = {e: defaultdict(float) for e in src_vocab}
    total = defaultdict(float)
    for src, tgt in bitext:
        src_ext = [NULL] + list(src)
        for f in tgt:
            denom = sum(t_table[e][f] for e in src_ext)
            for e in src_ext:
                mass = t_table[e][f] / denom
                count[e][f] += mass
                total[e] += mass
    new_table = {}
    for e in src_vocab:
        if total[e] > 0:
            new_table[e] = {f: count[e][f] / total[e] for f in tgt_vocab}
        else:
            new_table[e] = t_table[e].copy()
    return new_table

For each generated token, the E-step normalizes over the extended conditioning sentence. The M-step divides expected counts by their conditioning row's total when it is positive. A row with zero total contributes nothing to the expected complete-data objective, so any normalized row for that type is a valid M-step choice. The toy keeps the preceding normalized row in that case. Its vocabulary comes from the training corpus, and initialization is positive.

Next, Viterbi decoding: for each target word, pick the source word with the highest t(f∣e)t(f\mid e). This is the maximum-posterior alignment under Model 1.

PythonIn [12]
CollapseExpand
def viterbi_align(src, tgt, t_table):
    """For each target position, pick the best source position. i = -1 means NULL."""
    src_ext = [NULL] + list(src)
    links = []
    for j, f in enumerate(tgt):
        best_i = max(range(len(src_ext)), key=lambda i: t_table[src_ext[i]][f])
        links.append((best_i - 1, j))
    return links


def align_reverse(src, tgt, rev_table):
    """For each source position, pick the best target position under t(source|target)."""
    tgt_ext = [NULL] + list(tgt)
    links = []
    for i, e in enumerate(src):
        best_j = max(
            range(len(tgt_ext)), key=lambda j: rev_table[tgt_ext[j]][e]
        )
        links.append((i, best_j - 1))
    return links


def alignment_f1(predicted, gold, filter_null=True):
    tp = fp = fn = 0
    for pred, gold_links in zip(predicted, gold):
        p = (
            {(i, j) for i, j in pred if (i >= 0 and j >= 0)}
            if filter_null
            else set(pred)
        )
        g = set(gold_links)
        tp += len(p & g)
        fp += len(p - g)
        fn += len(g - p)
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn) if tp + fn else 0.0
    f1 = (
        2 * precision * recall / (precision + recall)
        if precision + recall
        else 0.0
    )
    return precision, recall, f1

Now the training loop. We record alignment F1 against gold before each parameter update, so iteration kk reports the quality of the model produced by kk previous updates.

PythonIn [13]
CollapseExpand
src_vocab, tgt_vocab = build_vocab(train_pairs)
t_table = uniform_table(src_vocab, tgt_vocab)

N_ITER = 10
alignment_history = []
for it in range(N_ITER):
    preds = [viterbi_align(en, ze, t_table) for en, ze in train_pairs]
    precision, recall, f1 = alignment_f1(preds, gold_train)
    alignment_history.append((it, precision, recall, f1))
    t_table = em_step(t_table, train_pairs, src_vocab, tgt_vocab)
ConsoleOut [14]
CollapseExpand
iter  precision   recall      F1
   0      0.000    0.000   0.000
   1      0.650    0.631   0.641
   2      0.776    0.648   0.706
   3      0.776    0.648   0.706
   4      0.776    0.648   0.706
   5      0.776    0.648   0.706
   6      0.776    0.648   0.706
   7      0.776    0.648   0.706
   8      0.776    0.648   0.706
   9      0.776    0.648   0.706

All three scores begin at zero because the uniform table gives each target word a tie and the decoder chooses the first position, NULL. After two updates the F1 reaches about 0.706 and stays there in the recorded curve. Model 1 assigns identical lexical scores to repeated occurrences of "the", so it has no positional information to disambiguate those links.

VisualizationOut [15]
CollapseExpand
Precision, recall and F1 start at zero. After two updates the curves level off near 0.776, 0.648 and 0.706 respectively.
Training alignment precision, recall, and F1 measured before each EM update on the English–Zeta corpus. F1 goes from zero to about 0.706 after two updates and stays there for the remaining recorded iterations.

Step 3: Train the Reverse Direction and Symmetrize

In this pipeline, we train a reverse model, t(English∣Zeta)t(\text{English} \mid \text{Zeta}), and combine both directions before extracting phrases. The extractor accepts any valid set of source–target links in its coordinate convention, including links from a single direction.

PythonIn [16]
CollapseExpand
rev_table = {NULL: {f: 1.0 / len(src_vocab) for f in src_vocab}}
rev_table.update(uniform_table(tgt_vocab, src_vocab))
for _ in range(N_ITER):
    rev_table = em_step(
        rev_table,
        [(ze, en) for en, ze in train_pairs],
        [NULL] + tgt_vocab,
        src_vocab,
    )

pred_ef = [viterbi_align(en, ze, t_table) for en, ze in train_pairs]
pred_fe = [align_reverse(en, ze, rev_table) for en, ze in train_pairs]

The grow-diag-final-and heuristic starts at the intersection. It considers all eight neighboring cells and adds a union link if either endpoint is unaligned. In the final pass it can add a remaining union link only if both endpoints are unaligned.

PythonIn [17]
CollapseExpand
NEIGHBOURS = [
    (-1, -1),
    (-1, 0),
    (-1, 1),
    (0, -1),
    (0, 1),
    (1, -1),
    (1, 0),
    (1, 1),
]


def grow_diag_final_and(a_ef, a_fe):
    inter = a_ef & a_fe
    union = a_ef | a_fe
    links = set(inter)
    aligned_src = {i for i, _ in inter}
    aligned_tgt = {j for _, j in inter}

    def grow_once():
        added = False
        for i, j in sorted(union - links):
            if i in aligned_src and j in aligned_tgt:
                continue
            if any((i + di, j + dj) in links for di, dj in NEIGHBOURS):
                links.add((i, j))
                aligned_src.add(i)
                aligned_tgt.add(j)
                added = True
        return added

    while grow_once():
        pass

    for i, j in sorted(union - links):
        if i not in aligned_src and j not in aligned_tgt:
            links.add((i, j))
            aligned_src.add(i)
            aligned_tgt.add(j)
    return links

Now compare the five candidate alignments against gold on the training set.

PythonIn [18]
CollapseExpand
variant_names = [
    "English to Zeta",
    "Zeta to English",
    "Intersection",
    "Union",
    "Grow-diag-final-and",
]
variant_links = {name: [] for name in variant_names}
sym_alignments = []

for idx, (en, ze) in enumerate(train_pairs):
    a_ef = {(i, j) for i, j in pred_ef[idx] if i >= 0}
    a_fe = {(i, j) for i, j in pred_fe[idx] if j >= 0}
    gdfa = grow_diag_final_and(a_ef, a_fe)
    sym_alignments.append(gdfa)
    for name, links in zip(
        variant_names,
        [a_ef, a_fe, a_ef & a_fe, a_ef | a_fe, gdfa],
    ):
        variant_links[name].append(sorted(links))

variant_f1 = {}
for name in variant_names:
    _, _, f1 = alignment_f1(variant_links[name], gold_train)
    variant_f1[name] = f1
ConsoleOut [19]
CollapseExpand
English to Zeta        F1 = 0.706
Zeta to English        F1 = 0.706
Intersection           F1 = 0.786
Union                  F1 = 0.641
Grow-diag-final-and    F1 = 0.706

The intersection has the highest measured F1, about 0.786. Both one-way alignments and grow-diag-final-and score about 0.706. The union scores about 0.641. These results depend on which links the directional models contribute. For instance, both directional models tie on the period's lexical probability between NULL and the observed period. The first-maximum rule chooses NULL in each direction. After filtering out NULL, the period-to-period link is absent from the union, so neither the growth pass nor the final pass can recover it.

VisualizationOut [20]
CollapseExpand
Five F1 bars show the intersection at about 0.786, both single directions and grow-diag-final-and at about 0.706, and union at about 0.641.
Alignment F1 against gold for five strategies on the synthetic training set. Intersection scores highest at about 0.786. Grow-diag-final-and and both directional models are tied at about 0.706.

Step 4: Extract and Score Phrase Pairs

Phrase extraction applies the consistency rule from earlier. The toy parameter max_len caps both the source and the target span. The pinned Moses trainer uses seven tokens as the default maximum phrase length in ordinary phrase extraction.

PythonIn [21]
CollapseExpand
def extract_phrase_pairs(src, tgt, align, max_len=3):
    pairs = []
    n = len(src)
    for i1 in range(n):
        for i2 in range(i1, min(i1 + max_len, n)):
            js = [j for i, j in align if i1 <= i <= i2]
            if not js:
                continue
            j1, j2 = min(js), max(js)
            if j2 - j1 + 1 > max_len:
                continue
            crossing = any((i1 <= i <= i2) != (j1 <= j <= j2) for i, j in align)
            if crossing:
                continue
            pairs.append((tuple(src[i1 : i2 + 1]), tuple(tgt[j1 : j2 + 1])))
    return pairs

A source span with no links is skipped. For each other source span, the target side is the smallest contiguous span containing all linked target positions. This toy omits unaligned target positions beyond that span. The crossing test rejects a link with one endpoint inside its span and the other outside its span.

Now collect all extracted pairs and build the phrase table with direct relative frequencies in log space.

PythonIn [22]
CollapseExpand
extracted = []
for idx, (en, ze) in enumerate(train_pairs):
    extracted.extend(extract_phrase_pairs(en, ze, sorted(sym_alignments[idx])))

phrase_counts = Counter(extracted)
source_totals = Counter()
for (src_phrase, tgt_phrase), count in phrase_counts.items():
    source_totals[src_phrase] += count

phrase_table = defaultdict(list)
for (src_phrase, tgt_phrase), count in phrase_counts.items():
    phrase_table[src_phrase].append(
        (tgt_phrase, math.log(count / source_totals[src_phrase]))
    )
for src_phrase in phrase_table:
    phrase_table[src_phrase].sort(key=lambda entry: -entry[1])
ConsoleOut [23]
CollapseExpand
Distinct phrase pairs extracted: 103
Distinct source phrases:        72

  the cat            -> ze mika ze (-0.69), mika (-0.94), ze mika (-2.20)
  sees the dog       -> voso tira (-0.29), tira (-1.39)
  is in the          -> ino va (0.00)
  .                  -> (no standalone entry)
  a                  -> (no standalone entry)

The table includes "voso tira" as a candidate for "sees the dog". That entry puts the object before the verb in the target. The period and "a" have no standalone entries under this alignment. Larger spans can still cover unaligned source tokens. That distinction matters when we inspect the decoder's output.

The learned alignments can also change which candidates the extractor finds. For “the cat,” extraction with the gold links gives only “ze mika.” The learned links give “ze mika,” “mika,” and “ze mika ze.” The decoder uses the phrase translation score, language model, distortion, and phrase count to rank candidates.

The phrase table is not uniformly ambiguous. The distribution of candidate counts shows how often the decoder must choose among alternatives.

PythonIn [24]
CollapseExpand
import numpy as np
from book_plot_style import PALETTE

translation_counts = np.array(
    [len(options) for options in phrase_table.values()], dtype=int
)
max_translations = (
    int(translation_counts.max()) if translation_counts.size else 0
)
count_bins = np.arange(0.5, max_translations + 1.5, 1.0)
hist_color = PALETTE["primary"]
VisualizationOut [25]
CollapseExpand
Histogram of the number of candidate translations per source phrase.
Distribution of the number of candidate target translations per source phrase in the extracted phrase table. Most source phrases have one candidate. A few have as many as three. The decoder combines phrase scores with language model and reordering scores when choosing among candidates.

Step 5: Build the Language Model

A bigram model with add-α\alpha smoothing scores partial hypotheses and full sentences. For α>0\alpha>0, each row is normalized over the training vocabulary, including both boundary tokens. A query with a word or context outside that vocabulary raises an error. The toy decoder's phrase table emits training tokens, so it needs no unknown-token mapping.

PythonIn [26]
CollapseExpand
class BigramLM:
    def __init__(self, sentences, alpha=0.1):
        self.alpha = alpha
        self.counts = defaultdict(Counter)
        self.totals = Counter()
        self.vocab = {"<s>", "</s>"}
        for sentence in sentences:
            tokens = ["<s>"] + list(sentence) + ["</s>"]
            self.vocab.update(tokens)
            for prev, word in zip(tokens, tokens[1:]):
                self.counts[prev][word] += 1
                self.totals[prev] += 1
        self.v_size = len(self.vocab)

    def prob(self, prev, word):
        if prev not in self.vocab or word not in self.vocab:
            raise ValueError(
                "BigramLM expects tokens from its training vocabulary."
            )
        numerator = self.counts[prev][word] + self.alpha
        denominator = self.totals[prev] + self.alpha * self.v_size
        return numerator / denominator

    def logprob(self, tokens):
        padded = ["<s>"] + list(tokens) + ["</s>"]
        return sum(
            math.log(self.prob(a, b)) for a, b in zip(padded, padded[1:])
        )


lm = BigramLM([ze for _, ze in train_pairs])
ConsoleOut [27]
CollapseExpand
Language model vocabulary size: 15
  ze mika ze voso tira .       log P = -6.126
  ze mika tira ze voso .       log P = -16.596
  ze voso ze mika tira .       log P = -6.126

The bigram model prefers both verb-final strings to the English-order string and scores the two verb-final strings equally, at about −6.126. It learns a local word-order preference from target text.

Note that the LM is not scoring whether the sentence is a correct translation. It is scoring whether the sentence looks like Zeta. "ze voso ze mika tira ." is perfectly fluent Zeta; it just means the dog sees the cat rather than the other way around. Nothing in the LM can detect that error, and this is precisely the division of labor the noisy channel sets up: the LM supplies fluency, and the translation model has to supply adequacy. Neither is sufficient alone.

Step 6: The Decoder

The toy decoder gives negative total jump distance a weight of 0.20.2, so a larger jump lowers the score. The weight stored under phrase_penalty is applied to the positive number of phrases used. With the fixture weight of 0.20.2, adding a phrase raises the score by 0.20.2 when the other feature totals stay fixed.

PythonIn [28]
CollapseExpand
@dataclass
class Hypothesis:
    lm: float
    tm: float
    distortion: float
    phrases: int
    words: tuple
    last_src_end: int
    last_word: str
    score: float = 0.0


WEIGHTS = {"lm": 0.5, "tm": 1.0, "distortion": 0.2, "phrase_penalty": 0.2}


def score_hypothesis(hyp, weights):
    return (
        weights["lm"] * hyp.lm
        + weights["tm"] * hyp.tm
        + weights["distortion"] * hyp.distortion
        + weights["phrase_penalty"] * hyp.phrases
    )


def decode(sentence, table, lm, weights, max_phrase_len=3, beam=40, n_best=3):
    n = len(sentence)
    full = (1 << n) - 1
    start = Hypothesis(
        lm=0.0,
        tm=0.0,
        distortion=0.0,
        phrases=0,
        words=(),
        last_src_end=-1,
        last_word="<s>",
    )
    active = {(0, -1): start}
    finished = []

    for _ in range(n + 1):
        nxt = {}
        for (mask, last_end), hyp in active.items():
            if mask == full:
                finished.append(hyp)
                continue
            for i in range(n):
                if (mask >> i) & 1:
                    continue
                for length in range(1, max_phrase_len + 1):
                    if i + length > n:
                        break
                    span = ((1 << length) - 1) << i
                    if mask & span:
                        break
                    src_phrase = tuple(sentence[i : i + length])
                    for tgt_phrase, logp in table.get(src_phrase, ())[:n_best]:
                        previous = (hyp.last_word,) + tgt_phrase[:-1]
                        lm_gain = sum(
                            math.log(lm.prob(a, b))
                            for a, b in zip(previous, tgt_phrase)
                        )
                        cand = Hypothesis(
                            lm=hyp.lm + lm_gain,
                            tm=hyp.tm + logp,
                            distortion=hyp.distortion - abs(i - last_end - 1),
                            phrases=hyp.phrases + 1,
                            words=hyp.words + tgt_phrase,
                            last_src_end=i + length - 1,
                            last_word=tgt_phrase[-1],
                        )
                        cand.score = score_hypothesis(cand, weights)
                        key = (mask | span, i + length - 1)
                        if key not in nxt or cand.score > nxt[key].score:
                            nxt[key] = cand
        if not nxt:
            break
        active = dict(sorted(nxt.items(), key=lambda kv: -kv[1].score)[:beam])

    finished.extend(h for (mask, _), h in active.items() if mask == full)
    if not finished:
        return [], float("-inf")

    best_hyp, best_score = None, float("-inf")
    for hyp in finished:
        total = hyp.score + weights["lm"] * math.log(
            lm.prob(hyp.last_word, "</s>")
        )
        if total > best_score:
            best_score, best_hyp = total, hyp
    return list(best_hyp.words), best_score

Three behaviors to notice in that code:

  • The coverage mask prevents any source word from being translated twice, so the search space is a subset of permutations of phrase segmentations.
  • Approximate recombination uses the dictionary key (mask, last_end). This keeps the higher-scoring prefix for each coverage mask and last input span end. Two such prefixes can end in different target words and score the same continuation differently under the bigram model. Keeping the higher score so far can therefore discard the better completion.
  • Pruning is a global sort by score, then a truncation to beam. The code scores the partial hypotheses without a future cost estimate. A finite beam can discard a partial hypothesis that would have scored well after completion.

The decoder keeps at most n_best options for each source phrase, ranked by phrase score. This saves search work when a phrase has many candidates. A lower-ranked option can still lead to a better complete translation once the other score terms enter. The worked table has at most three options per phrase, so n_best=3 keeps them all. Moses User Manual, §3.1.6

Let's run it on the held-out set.

PythonIn [29]
CollapseExpand
hypotheses = []
references = []
for en, ze, _ in test:
    output, _score = decode(en, phrase_table, lm, WEIGHTS)
    hypotheses.append(output)
    references.append(ze)
ConsoleOut [30]
CollapseExpand
Exact matches: 0/9
Matches after ignoring only the final reference period: 9/9

EN : the bird sees the cat .
SYS: ze turi ze mika tira
REF: ze turi ze mika tira .

EN : the fish is in the dog .
SYS: ze paku ze voso ino va
REF: ze paku ze voso ino va .

EN : the fish chases the cat .
SYS: ze paku ze mika kavu
REF: ze paku ze mika kavu .

EN : the bird sees the bird .
SYS: ze turi ze turi tira
REF: ze turi ze turi tira .

EN : the fish chases the dog .
SYS: ze paku ze voso kavu
REF: ze paku ze voso kavu .

EN : the bird is in the fish .
SYS: ze turi ze paku ino va
REF: ze turi ze paku ino va .

All nine hypotheses match the reference words in order, and all nine omit the final period. Some extracted multiword spans cover the period's source position while emitting no punctuation, and the coverage mask records only that the position was consumed. It cannot check whether each consumed token produced a corresponding output, so the strict exact-match count is zero.

Step 7: Score with BLEU

This toy BLEU uses one reference per hypothesis, paired by position in equally long lists. It clips each hypothesis's nn-gram counts against that reference and uses that reference's length in the corpus brevity penalty. The original BLEU definition allows multiple references. The toy defaults to orders one through four.

PythonIn [31]
CollapseExpand
def ngram_counts(tokens, n):
    return Counter(tuple(tokens[i : i + n]) for i in range(len(tokens) - n + 1))


def corpus_bleu(hyps, refs, max_n=4):
    matches = [0] * max_n
    totals = [0] * max_n
    hyp_len = ref_len = 0
    for hyp, ref in zip(hyps, refs):
        hyp_len += len(hyp)
        ref_len += len(ref)
        for n in range(1, max_n + 1):
            hyp_counts = ngram_counts(hyp, n)
            ref_counts = ngram_counts(ref, n)
            matches[n - 1] += sum(
                min(c, ref_counts[g]) for g, c in hyp_counts.items()
            )
            totals[n - 1] += max(len(hyp) - n + 1, 0)
    precisions = [(matches[i] + 1) / (totals[i] + 1) for i in range(max_n)]
    if hyp_len == 0:
        return 0.0
    if hyp_len > ref_len:
        brevity = 1.0
    else:
        brevity = math.exp(1 - ref_len / hyp_len)
    return brevity * math.exp(sum(math.log(p) for p in precisions) / max_n)


bleu = corpus_bleu(hypotheses, references)
ConsoleOut [32]
CollapseExpand
Corpus BLEU: 0.826

Per-sentence unigram precision:
  1.000  ze turi ze mika tira
  1.000  ze paku ze voso ino va
  1.000  ze paku ze mika kavu
  1.000  ze turi ze turi tira
  1.000  ze paku ze voso kavu
  1.000  ze turi ze paku ino va
  1.000  ze turi ze paku kavu
  1.000  un mika un voso kavu
  1.000  un mika un voso tira

This pedagogical variant adds one to the matched and total counts at each order. That keeps the precision positive in this fixture when an order has no matches. The original unsmoothed corpus BLEU of Papineni et al. (2002) uses modified nn-gram precisions without this add-one step.

The smoothed corpus BLEU is about 0.826 and strict exact match is zero. Each hypothesis matches its reference up to the missing final period. All four clipped precisions equal one, so the brevity penalty accounts for the entire drop from one. Exact match makes the deletion visible alongside the overlap score.

Step 8: Inspect the Learned Lexicon

Finally, a direct look at the t(f∣e)t(f\mid e) matrix that EM produced. Each row is an English word, each column a Zeta word, and the gold links are overlaid.

PythonIn [33]
CollapseExpand
target_example = ["the", "cat", "sees", "the", "dog", "."]
example = next(
    ((en, ze, gold) for en, ze, gold in train if en == target_example),
    train[0],
)
example_en, example_ze, example_gold = example
lexical_matrix = np.array(
    [[t_table[e][f] for f in example_ze] for e in example_en]
)
VisualizationOut [34]
CollapseExpand
Heatmap of lexical translation probabilities with gold alignment links marked as circles.
IBM Model 1 lexical translation probabilities for an English-Zeta sentence pair. Each row is an English source word and each column a Zeta target word. Open circles mark the gold alignment. Repeated determiners share lexical scores across positions. The strong cell at the intersection of “sees” and “tira” shows that Model 1 can learn the verb correspondence without representing the verb’s change in position.

Both English “the” rows give the two Zeta “ze” columns the same lexical score. The gold links distinguish the occurrences, but the model's lexical features cannot tell them apart. The “sees” row scores “tira” highly at the fifth Zeta position, before the period. This shows a lexical correspondence despite the shift from the third English position.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy