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分数。
相关推荐
叫我:松哥几秒前
基于LSTM与ARIMA的城市空气质量分析与预测系统
人工智能·python·rnn·算法·机器学习·flask·lstm
指尖在键盘上舞动2 分钟前
RKNN 模型部署:onnx转rknn后精度下降 —— 精度调优与问题排查
python·ubuntu·rk3588·rknn·onnx·npu
CodeSheep程序羊7 分钟前
宇树科技,即将上市!
java·c语言·c++·人工智能·python·科技·硬件工程
AI玫瑰助手7 分钟前
Python函数:内置函数(len/max/min/sorted等)详解
android·开发语言·python
ziyitty12 分钟前
解决Windows下Bash调用Python输出中文乱码的问题
windows·python·bash
栈溢出了13 分钟前
torch.gather 用法笔记
pytorch·python·深度学习
杨超越luckly19 分钟前
Agent应用指南:利用GET请求获取赛力斯汽车门店位置信息
python·html·汽车·可视化·门店
花月C22 分钟前
Agent上下文三级压缩
python·prompt·ai编程
专注搞钱29 分钟前
用Python写了个SPC自动分析工具,效率提升10倍
开发语言·python
yijianace36 分钟前
Python爬虫实战:ThreadPoolExecutor多线程采集书籍信息与图片下载
开发语言·爬虫·python