PIXELBANKv9.1.0
Menu

Implement the BLEU score calculation for machine translation evaluation.

BLEU measures the overlap of n-grams between a candidate translation and reference translations.

Simplified BLEU (up to bigrams):

  1. Compute modified precision for unigrams and bigrams
  2. Modified precision clips each n-gram count to the max count in any reference
  3. Compute brevity penalty: BP = exp(1 - ref_len/cand_len) if cand_len < ref_len, else 1
  4. BLEU = BP * exp(0.5 * log(p1) + 0.5 * log(p2))

Where p1 = clipped unigram matches / candidate unigrams, p2 = clipped bigram matches / candidate bigrams.

Input format:

  • Line 1: Candidate translation (space-separated words)
  • Line 2: Number of references R
  • Lines 3 to R+2: Reference translations

Output: BLEU score rounded to 4 decimal places. If any precision is 0, output 0.0.

Example:

Input:
the cat sat on the mat
1
the cat is on the mat
Output:
0.6687
Reasoning:

Candidate: the cat sat on the mat (6 words) Reference: the cat is on the mat (6 words)

Unigram precision: Candidate unigrams: the(2), cat(1), sat(1), on(1), mat(1) Clipped by ref: the(2), cat(1), sat(0), on(1), mat(1) => 5/6

Bigram precision: Candidate bigrams: (the,cat)(1), (cat,sat)(1), (sat,on)(1), (on,the)(1), (the,mat)(1) Ref bigrams: (the,cat)(1), (cat,is)(1), (is,on)(1), (on,the)(1), (the,mat)(1) Matches: (the,cat), (on,the), (the,mat) => 3/5

Brevity penalty: len(cand)=6 = len(ref)=6, so BP = 1.0

BLEU: 1.0 * exp(0.5log(5/6) + 0.5log(3/5)) = exp(0.5*(-0.1823) + 0.5*(-0.5108)) = exp(-0.3466) = 0.7072...

The exact value depends on the implementation details.

Constraints:

  • Use uniform weights (0.5, 0.5) for unigrams and bigrams
  • Clip n-gram counts to max reference count
  • Use the closest reference length for brevity penalty
  • If candidate has fewer than 2 words (no bigrams possible), output 0.0
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
BLEU Score - Medium | PixelBank