BLEU和ROUGE评价指标原理和计算方式

BLEU和ROUGE是常用的文本生成评价指标,主要用于评估机器翻译和文本摘要等任务的生成质量。下面详细介绍这两个指标的定义、计算方法及其特点。

1. BLEU (Bilingual Evaluation Understudy)

定义:

BLEU是一种自动评估生成文本与参考文本相似性的指标,主要用于机器翻译。它通过计算n-gram的重叠程度来判断生成文本的质量。

计算步骤:
  1. 选择n-gram

    • 选择要计算的n-gram的大小,常用的有1-gram、2-gram等。
  2. 计算n-gram重叠

    • 对生成文本和参考文本进行n-gram切分,并计算它们之间的重叠个数。
    • 例如,若参考文本为"the cat sits"和生成文本为"the cat sits on the mat",那么对于1-gram:
      • 参考文本的1-gram: ["the", "cat", "sits"]
      • 生成文本的1-gram: ["the", "cat", "sits", "on", "the", "mat"]
      • 重叠1-gram: ["the", "cat", "sits"]
  3. 计算精确率

    • 对于每个n-gram,计算精确率(precision),即生成文本中的n-gram与参考文本中出现的n-gram的比例。
  4. 计算BP(惩罚因子)

若生成文本长度短于参考文本长度,则需要惩罚。BP的计算方式为:

计算BLEU分数

  • 最终的BLEU分数为n-gram精确率的几何平均值乘以BP。

  • python 复制代码
    def n_grams(tokens, n):
        return [tuple(tokens[i:i+n]) for i in range(len(tokens)-n+1)]
    
    def calculate_bleu(reference, candidate, n=2):
        reference_tokens = reference.split()
        candidate_tokens = candidate.split()
        
        # 计算n-grams
        ref_ngrams = n_grams(reference_tokens, n)
        cand_ngrams = n_grams(candidate_tokens, n)
        
        # 统计重叠的n-grams
        overlap_count = sum(1 for ng in cand_ngrams if ng in ref_ngrams)
        
        # 计算精确率
        precision = overlap_count / len(cand_ngrams) if cand_ngrams else 0
        
        # 计算惩罚因子
        if len(candidate_tokens) > len(reference_tokens):
            bp = 1
        else:
            bp = (1 - len(reference_tokens) / len(candidate_tokens)) if len(candidate_tokens) > 0 else 0
    
        # 计算BLEU分数
        bleu_score = precision * bp
        return bleu_score
    
    # 示例使用
    reference = "the cat sits on the mat"
    candidate = "the cat is on the mat"
    
    bleu_score = calculate_bleu(reference, candidate, n=2)
    print(f"BLEU Score: {bleu_score}")

ROUGE (Recall-Oriented Understudy for Gisting Evaluation)

定义:

ROUGE是一组用于自动评估文本生成质量的指标,主要用于文本摘要。它通过计算生成文本与参考文本之间的重叠情况,尤其关注召回率。

主要变体:
  • ROUGE-N:计算n-gram的重叠,类似于BLEU,但更关注召回率。
  • ROUGE-L:计算最长公共子序列(LCS)的长度,用于评估文本生成的连贯性。
  • ROUGE-W:计算加权最长公共子序列,更强调较长的连续n-gram。
计算步骤(以ROUGE-N为例):
  1. 选择n-gram:选择n-gram的大小。

  2. 计算n-gram重叠

    • 类似于BLEU,统计生成文本和参考文本之间的n-gram重叠个数。
  3. 计算召回率

    • 计算生成文本的n-gram在参考文本中出现的比例。
  4. 计算F1分数

    • 综合精确率和召回率,计算F1分数。
相关推荐
数据智能老司机3 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机4 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机4 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机4 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i4 小时前
drf初步梳理
python·django
每日AI新事件4 小时前
python的异步函数
python
这里有鱼汤5 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook14 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室15 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三16 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试