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分数。
相关推荐
m0_613856293 小时前
mysql如何利用事务隔离级别解决特定业务冲突_mysql隔离方案选型
jvm·数据库·python
我的xiaodoujiao4 小时前
API 接口自动化测试详细图文教程学习系列16--项目实战演练3
python·学习·测试工具·pytest
ID_180079054734 小时前
Python 实现亚马逊商品详情 API 数据准确性校验(极简可用 + JSON 参考)
java·python·json
时空系4 小时前
第10篇:继承扩展——面向对象编程进阶 python中文编程
开发语言·python·ai编程
CHANG_THE_WORLD5 小时前
python 批量终止进程exe
开发语言·python
liann1196 小时前
3.2_红队攻击框架--MITRE ATT&CK‌
python·网络协议·安全·网络安全·系统安全·信息与通信
云天AI实战派6 小时前
AI 智能体问题排查指南:ChatGPT、API 调用到 Agent 上线失灵的全流程修复手册
大数据·人工智能·python·chatgpt·aigc
我的xiaodoujiao6 小时前
API 接口自动化测试详细图文教程学习系列15--项目实战演练2
python·学习·测试工具·pytest
多思考少编码7 小时前
PAT甲级真题1001 - 1005题详细题解(C++)(个人题解)
c++·python·最短路·pat·算法竞赛
ZhengEnCi7 小时前
M5-markconv自定义CSS样式指南 📝
前端·css·python