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分数。
相关推荐
ragnwang6 小时前
Notes: Python pybind11 import C++ module
开发语言·c++·python
王中阳Go6 小时前
后端转 Agent 岗面试怎么答:8 个高频问题与应答口径
人工智能·后端·python·大语言模型
weixin_307779137 小时前
RAG 面试陷阱——混合检索并非无条件优越:一个条件反转实验
人工智能·python·面试·职场和发展
云和数据.ChenGuang7 小时前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain
荣码10 小时前
长上下文与大文档处理:200页PDF怎么喂给AI,我踩了4个坑
java·python
databook11 小时前
Pandas 与 Polars:语法、性能和资源占用方面的对比
python·数据分析·pandas
威哥爱编程11 小时前
Python 智能体开发实战 10:本地跑得好好的,一并发就崩?把它做成一个能上线的服务
python·agent
威哥爱编程11 小时前
Python 智能体开发实战 09:改了提示词,到底是变好还是变坏?搭一套能打分的离线评测
python·agent
meiying883811 小时前
多快递公司快递单号批量查询接口怎么对接?Python 聚合查询实现
java·大数据·python
Hello_Pyhx12 小时前
Deep-Live-Cam 源码配置思路:环境、模型与执行后端分开排查
python