跳转至

471_机器翻译原理


一句话说明

机器翻译(Machine Translation)让计算机自动把一种语言的文字转换成另一种语言,Transformer架构(2017年)彻底改变了这个领域。


核心知识点

  • Seq2Seq架构:编码器(源语言)→ 上下文向量 → 解码器(目标语言)
  • 注意力机制:解码每个词时动态关注源序列不同位置,解决信息瓶颈
  • Transformer:Multi-Head Self-Attention + FFN,完全替代RNN,并行训练
  • BLEU分数:机器翻译主要评估指标(n-gram精度加权),越高越好
  • 束搜索(Beam Search):解码时保留k个候选序列,比贪心搜索更好

经典模型演进

时代代表模型核心创新
统计MTSMT(Moses)短语表+语言模型
RNN时代Seq2Seq+Attention注意力机制(Bahdanau2015)
TransformerVaswani et al.2017完全自注意力,BLEU大幅提升
预训练时代mBART、M2M-100多语言预训练
大模型时代GPT-4、DeepL超大规模数据+RLHF

代码示例

# 使用 HuggingFace 中的 Helsinki-NLP 翻译模型(Transformer架构)

from transformers import MarianMTModel, MarianTokenizer

# ---- 1. 加载中→英翻译模型 ----
# Helsinki-NLP 提供200+语言对的预训练翻译模型
model_name = 'Helsinki-NLP/opus-mt-zh-en'  # 中文→英文
tokenizer = MarianTokenizer.from_pretrained(model_name)
model = MarianMTModel.from_pretrained(model_name)

# ---- 2. 批量翻译 ----
texts = [
    "今天天气很好",
    "机器翻译是自然语言处理的重要任务",
    "深度学习改变了机器翻译的格局"
]

# 分词编码
inputs = tokenizer(
    texts,
    return_tensors='pt',
    padding=True,          # 批量需要padding到相同长度
    truncation=True,
    max_length=512
)

# ---- 3. 生成翻译(beam search)----
translated = model.generate(
    **inputs,
    num_beams=5,          # beam宽度5,质量和速度平衡
    max_length=256,
    early_stopping=True
)

# ---- 4. 解码输出 ----
results = tokenizer.batch_decode(translated, skip_special_tokens=True)
for src, tgt in zip(texts, results):
    print(f"原文: {src}")
    print(f"译文: {tgt}")
    print()

# ---- 5. Transformer 注意力可视化(概念演示)----
import torch
import matplotlib.pyplot as plt

def visualize_attention(model, tokenizer, src_text):
    """可视化编码器自注意力权重"""
    inputs = tokenizer(src_text, return_tensors='pt')
    with torch.no_grad():
        # 输出注意力权重
        outputs = model.model.encoder(
            **inputs,
            output_attentions=True  # 返回注意力权重
        )
    # outputs.attentions: tuple of (batch, heads, seq, seq)
    attn = outputs.attentions[-1][0, 0].numpy()  # 最后一层第1个head
    tokens = tokenizer.convert_ids_to_tokens(inputs['input_ids'][0])

    plt.figure(figsize=(8, 6))
    plt.imshow(attn, cmap='Blues')
    plt.xticks(range(len(tokens)), tokens, rotation=45)
    plt.yticks(range(len(tokens)), tokens)
    plt.title('Encoder Self-Attention')
    plt.tight_layout()
    plt.savefig('attention.png')
    return attn

# ---- 6. BLEU评估 ----
# pip install sacrebleu
from sacrebleu.metrics import BLEU

bleu = BLEU()
hypothesis = ["The weather is very good today"]
references = [["Today the weather is very nice"]]
score = bleu.corpus_score(hypothesis, references)
print(f"BLEU: {score.score:.2f}")

面试常问点

  1. Transformer相比RNN的优势?
  2. 并行训练(RNN需串行)、长距离依赖更好(自注意力直接连接任意位置)

  3. Beam Search为什么比贪心搜索好?

  4. 贪心每步取最大,可能错失全局最优;Beam保留k条路径,全局更优

  5. BLEU分数的局限?

  6. 只看表面n-gram重叠,不考虑语义;高分不等于流畅自然

  7. 多语言翻译模型(如M2M-100)的优势?

  8. 不需要经过英语中转(zh→de 直接翻译),低资源语言对表现更好

速查表

需求方案
中英翻译Helsinki-NLP/opus-mt-zh-en
多语言Helsinki-NLP/opus-mt-mul-en
高质量DeepL API / Google Translate API
领域定制收集领域平行语料微调 MarianMT
评估sacrebleu(BLEU、chrF、TER)