🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Machine Translation

Generative NLPNeural Machine Translation and EvaluationđŸŸĸ Free Lesson

Machine Translation

Machine translation (MT) automatically translates text from one language to another. Modern NMT uses encoder-decoder transformers with attention.

Seq2Seq Architecture

The encoder processes the source sentence, and the decoder generates the target sentence token by token.

python
from transformers import (
    AutoModelForSeq2SeqLM,
    AutoTokenizer,
    Seq2SeqTrainingArguments,
    Seq2SeqTrainer,
)

# MarianMT for translation
model_name = "Helsinki-NLP/opus-mt-en-fr"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)

def translate(text):
    inputs = tokenizer(text, return_tensors="pt", padding=True)
    translated = model.generate(**inputs)
    return tokenizer.decode(translated[0], skip_special_tokens=True)

print(translate("Hello, how are you?"))
# "Bonjour, comment allez-vous?"

BLEU Score

BLEU (Bilingual Evaluation Understudy) measures translation quality by comparing n-gram overlap with reference translations.

Where:

  • p_n: Modified n-gram precision
  • w_n: Weight for n-gram (typically 1/N)
  • c: Candidate translation length
  • r: Reference translation length
python
from nltk.translate.bleu_score import (
    corpus_bleu,
    SmoothingFunction,
    sentence_bleu
)

# Single sentence BLEU
reference = [['the', 'cat', 'is', 'on', 'the', 'mat']]
candidate = ['the', 'cat', 'sat', 'on', 'the', 'mat']

# Smoothed BLEU (handles zero counts)
smooth = SmoothingFunction().method1
score = sentence_bleu(reference, candidate, smoothing_function=smooth)
print(f"BLEU: {score:.4f}")  # 0.7143

# Corpus BLEU
references = [
    [['the', 'cat', 'is', 'on', 'the', 'mat']],
    [['there', 'is', 'a', 'cat', 'on', 'the', 'mat']]
]
candidates = [
    ['the', 'cat', 'is', 'on', 'the', 'mat'],
    ['there', 'is', 'a', 'cat', 'on', 'the', 'mat']
]

corpus_score = corpus_bleu(references, candidates)
print(f"Corpus BLEU: {corpus_score:.4f}")

Translation Evaluation Metrics

MetricTypeMeasuresRange
BLEUPrecisionN-gram overlap0-100
METEORBalancePrecision + recall + alignment0-1
TERErrorEdit distance / reference length0-∞
CHRFCharacterCharacter n-gram F10-100
COMETNeuralLearned metric-1 to 1
BERTScoreSemanticEmbedding similarity0-1
python
import sacrebleu

# BLEU with sacrebleu
references = ["Le chat est sur le tapis."]
candidate = "Le chat est sur le tapis."

bleu = sacrebleu.corpus_bleu([candidate], [references])
print(f"BLEU: {bleu.score:.2f}")
print(f"Signature: {bleu}")

# chrF (character n-gram F-score)
chrf = sacrebleu.corpus_chrf([candidate], [references])
print(f"chrF: {chrf.score:.2f}")

# TER (Translation Edit Rate)
ter = sacrebleu.corpus_ter([candidate], [references])
print(f"TER: {ter.score:.2f}")

Beam Search for Translation

python
def translate_with_beam(source_text, model, tokenizer, num_beams=5):
    inputs = tokenizer(source_text, return_tensors="pt", padding=True)

    outputs = model.generate(
        **inputs,
        num_beams=num_beams,
        max_length=128,
        length_penalty=0.6,
        early_stopping=True,
        no_repeat_ngram_size=3
    )

    return tokenizer.decode(outputs[0], skip_special_tokens=True)

# Compare beam sizes
for beams in [1, 3, 5, 10]:
    result = translate_with_beam("Hello world!", model, tokenizer, num_beams=beams)
    print(f"Beams={beams}: {result}")

Quality Estimation

Quality estimation (QE) predicts translation quality without references.

python
from transformers import AutoModelForSequenceClassification

class TranslationQE:
    def __init__(self, model_name="Unbabel/wmt22-comet-da"):
        self.model = AutoModelForSequenceClassification.from_pretrained(model_name)
        self.tokenizer = AutoTokenizer.from_pretrained(model_name)

    def score(self, source, translation, reference=None):
        inputs = self.tokenizer(
            source,
            translation,
            return_tensors="pt",
            truncation=True
        )
        with torch.no_grad():
            outputs = self.model(**inputs)
            score = torch.sigmoid(outputs.logits).item()
        return score

qe = TranslationQE()
score = qe.score(
    "The weather is nice today.",
    "Le temps est beau aujourd'hui."
)
print(f"Quality Score: {score:.4f}")

Back-Translation

Back-translation generates synthetic parallel data from monolingual corpora.

python
def back_translation(monolingual_data, en_to_fr_model, fr_to_en_model):
    synthetic_pairs = []
    for text in monolingual_data:
        # Translate to target language
        fr_text = translate(text, en_to_fr_model)

        # Translate back to source
        en_text = translate(fr_text, fr_to_en_model)

        # Use original as source, back-translated as target
        synthetic_pairs.append((text, en_text))

    return synthetic_pairs

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement