Encoder-Decoder Framework › Evaluating Translation: BLEU Score

Michael BrenndoerferMay 15, 20255 min read
Language AI HandbookAll chapters
Part 12 of 67Sequence-to-Sequence
Chapter 83Encoder-Decoder Framework › Evaluating Translation: BLEU Score
Reading section 11 of 16 · Evaluating Translation: BLEU Score · 5 minSection 11 of 16 · 5 min

Book contents

Section 11 of 16 · 5 min read

Encoder-Decoder Framework › Evaluating Translation: BLEU ScoreOne section · Sections in this chapter11 / 16 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Evaluating sequence generation is harder than evaluating classification. You cannot just compare logits to labels because there are multiple valid translations of any source sentence. The Bilingual Evaluation Understudy (BLEU) score is the most widely used automatic metric for machine translation.

Why Automatic Evaluation Matters

Before BLEU was proposed by Papineni et al. in 2002, evaluating machine translation required human judges to rate translation quality on a scale, an expensive and slow process. Progress in the field was measured by periodic evaluation campaigns that could take months to organize. BLEU made it possible to evaluate a system in seconds, allowing rapid iteration and system comparison. The impact on research productivity was clear: researchers could now run ablation studies and hyperparameter sweeps with automatic evaluation, dramatically accelerating progress.

The core challenge BLEU addresses is that translation quality cannot be measured by exact string match. "The cat sat on the mat" and "A cat was sitting on the mat" might both be valid translations of the same French sentence, but exact match would give the second translation a score of zero against the first as a reference. BLEU instead measures n-gram overlap, which captures the intuition that good translations share many words and phrases with human reference translations, even if the exact wording differs.

BLEU Formula

BLEU measures the n-gram overlap between the generated translation and one or more reference translations. It computes the modified precision for n-grams of orders 1 through 4, then combines them geometrically and applies a brevity penalty to discourage overly short translations.

The modified n-gram precision pnp_n captures how many of the candidate's n-grams appear in the reference, clipped so the model cannot cheat by repeating common words. Formally:

pn=∑n-gram∈candidatemin⁡ ⁣(countcand(n-gram),  max⁡refcountref(n-gram))∑n-gram∈candidatecountcand(n-gram)p_n = \frac{\displaystyle\sum_{\text{n-gram} \in \text{candidate}} \min\!\bigl(\text{count}_{\text{cand}}(\text{n-gram}),\; \max_{\text{ref}} \text{count}_{\text{ref}}(\text{n-gram})\bigr)}{\displaystyle\sum_{\text{n-gram} \in \text{candidate}} \text{count}_{\text{cand}}(\text{n-gram})}

where:

  • The numerator counts how many candidate n-grams appear in the references, capped by the maximum count in any single reference
  • The denominator counts all n-grams in the candidate translation
  • The clipping prevents the model from inflating its score by repeating high-frequency words

The brevity penalty BPBP discourages short outputs:

BP={1if c>re1−r/cif c≤rBP = \begin{cases} 1 & \text{if } c > r \\ e^{1 - r/c} & \text{if } c \leq r \end{cases}

where:

  • cc is the total length of all candidate translations
  • rr is the reference length that best matches each candidate

The final BLEU score combines these components:

BLEU=BP⋅exp⁡ ⁣(∑n=1Nwnlog⁡pn)\text{BLEU} = BP \cdot \exp\!\left(\sum_{n=1}^{N} w_n \log p_n\right)

where:

  • N=4N = 4 uses n-grams of orders 1 through 4
  • wn=1/N=0.25w_n = 1/N = 0.25 gives uniform weights across n-gram orders
  • The exponential of the weighted sum equals the geometric mean of the individual precisions

BLEU scores range from 0 to 1. In practice:

  • BLEU above 0.6 indicates excellent, near-human quality
  • BLEU between 0.4 and 0.6 indicates good, understandable translations
  • BLEU between 0.2 and 0.4 indicates decent but significant errors
  • BLEU below 0.2 indicates poor quality

Limitations of BLEU

While BLEU is practical and widely used, it has well-known limitations worth understanding. First, BLEU is not a good metric for individual sentences: it was designed for corpus-level evaluation where it averages over thousands of examples, and single-sentence BLEU scores are noisy and unreliable. Second, BLEU can reward systems that match the surface form of a reference without capturing the meaning, and it can penalize paraphrases that are semantically equivalent but lexically different. Third, BLEU does not measure fluency directly: a translation that scrambles the order of correct n-grams might get a non-trivial unigram BLEU score even though the output is barely readable.

More recent metrics like BERTScore and COMET attempt to address these limitations by measuring semantic similarity using contextual embeddings rather than surface n-gram overlap. These metrics correlate better with human judgments but are more expensive to compute. For the purposes of this chapter, BLEU is the appropriate metric because it is interpretable and directly connected to the n-gram overlap intuition.

Computing BLEU

In[14]:
Code
from collections import Counter


def compute_bleu(candidate, reference, max_n=4):
    """
    Compute sentence-level BLEU score between candidate and reference strings.
    Both inputs are strings (character-level evaluation).
    """
    cand_tokens = list(candidate)
    ref_tokens = list(reference)

    if len(cand_tokens) == 0:
        return 0.0

    # Brevity penalty
    c = len(cand_tokens)
    r = len(ref_tokens)
    bp = 1.0 if c > r else (np.exp(1 - r / c) if c > 0 else 0.0)

    # Modified n-gram precisions
    precisions = []
    for n in range(1, max_n + 1):
        cand_ngrams = Counter(
            tuple(cand_tokens[i : i + n])
            for i in range(len(cand_tokens) - n + 1)
        )
        ref_ngrams = Counter(
            tuple(ref_tokens[i : i + n]) for i in range(len(ref_tokens) - n + 1)
        )

        if not cand_ngrams:
            precisions.append(0.0)
            continue

        clipped = sum(
            min(count, ref_ngrams[ngram])
            for ngram, count in cand_ngrams.items()
        )
        total = sum(cand_ngrams.values())
        precisions.append(clipped / total if total > 0 else 0.0)

    if any(p == 0 for p in precisions):
        return 0.0

    log_avg = sum(np.log(p) for p in precisions) / max_n
    return bp * np.exp(log_avg)
Out[15]:
Console
BLEU evaluation on training set (20 sentences):
  Mean BLEU:        1.0000
  Min BLEU:         1.0000
  Max BLEU:         1.0000
  Perfect (>=0.99): 20/20

The BLEU score on the training set reflects how well the model has learned the training sequences. A mean BLEU near 1.0 indicates that the decoder is accurately reproducing the correct reversed-word sequences, confirming the model has captured the source-to-target transformation.