【NLP 计算句子之间的BLEU和ROUGE分数】

安装依赖

bash 复制代码
pip install nltk rouge-score

批量处理代码

python 复制代码
from nltk.translate.bleu_score import corpus_bleu, SmoothingFunction
from rouge_score import rouge_scorer
import nltk

# 下载必要的资源(第一次运行需要)
nltk.download('wordnet')  # 用于 BLEU 的 tokenizer 等
nltk.download('punkt')     # 用于 tokenize

def batch_bleu(references, candidates):
    """
    计算批量 BLEU 分数 (BLEU-4)
    
    Args:
        references: List of lists of reference sentences (每项是多个参考答案列表)
        candidates: List of candidate sentences (模型生成的句子列表)
    
    Returns:
        float: 平均 BLEU-4 分数
    """
    smoothing = SmoothingFunction()
    
    # 将每个参考句子 tokenize
    tokenized_references = [[nltk.word_tokenize(sent) for sent in ref] for ref in references]
    
    # 将每个候选句子 tokenize
    tokenized_candidates = [nltk.word_tokenize(sent) for sent in candidates]

    # 计算 corpus BLEU
    bleu_score = corpus_bleu(
        tokenized_references,
        tokenized_candidates,
        weights=(0.25, 0.25, 0.25, 0.25),
        smoothing_function=smoothing.method1
    )
    return bleu_score


def batch_rouge(references, candidates):
    """
    计算批量 ROUGE 分数 (ROUGE-1, ROUGE-2, ROUGE-L)
    
    Args:
        references: List of reference sentences (每个样本一个参考句)
        candidates: List of candidate sentences
    
    Returns:
        dict: {'rouge1': f1, 'rouge2': f1, 'rougeL': f1}
    """
    scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)
    scores = {'rouge1': [], 'rouge2': [], 'rougeL': []}

    for ref, cand in zip(references, candidates):
        score = scorer.score(ref, cand)
        scores['rouge1'].append(score['rouge1'].fmeasure)
        scores['rouge2'].append(score['rouge2'].fmeasure)
        scores['rougeL'].append(score['rougeL'].fmeasure)

    avg_scores = {k: sum(v)/len(v) for k, v in scores.items()}
    return avg_scores


def evaluate_all(references, candidates):
    """
    同时计算 BLEU 和 ROUGE 的批量评估函数
    
    Args:
        references: List of reference sentences
        candidates: List of candidate sentences
    
    Returns:
        dict: 包含 BLEU 和 ROUGE 的平均分数
    """
    bleu = batch_bleu([[ref] for ref in references], candidates)
    rouge = batch_rouge(references, candidates)
    return {
        'BLEU': round(bleu, 4),
        'ROUGE-1': round(rouge['rouge1'], 4),
        'ROUGE-2': round(rouge['rouge2'], 4),
        'ROUGE-L': round(rouge['rougeL'], 4)
    }

测试代码

python 复制代码
# 示例数据:批量输入
references = [
    "the cat is on the mat",
    "a dog is playing in the garden"
]

candidates = [
    "the cat sat on the mat",
    "a dog plays in the garden"
]

# 调用评估函数
results = evaluate_all(references, candidates)
print("Evaluation Results:", results)

输出

python 复制代码
Evaluation Results: {'BLEU': 0.1966, 'ROUGE-1': 0.8782, 'ROUGE-2': 0.6636, 'ROUGE-L': 0.8782}
相关推荐
阿里云大数据AI技术11 分钟前
Hologres CLI 与 Skills 担当 Agent-Ready 基础设施,共建数仓智能新生态
人工智能·agent
Terrence Shen14 分钟前
大模型部署工具对比
人工智能·深度学习·计算机视觉
视觉&物联智能37 分钟前
【杂谈】-企业人工智能超越实验:安全拓展的实践路径
人工智能·安全·aigc·agent·agi
ting945200039 分钟前
Kirki 深度技术解析:WordPress 自定义控件开发与可视化配置底层原理
人工智能·架构
掘金一周40 分钟前
想换一辆电车,JYM有什么推荐 | 沸点周刊 5.21
前端·人工智能·后端
创世宇图40 分钟前
【AI入门知识点】LLM 原理是什么?为什么 ChatGPT 看起来像“会思考”?
人工智能·ai·llm·token
不爱吃糖的程序媛1 小时前
2026年Electron 鸿蒙PC环境搭建指南
人工智能·华为·harmonyos
码途漫谈1 小时前
让 AI 编程不断线:9Router 的本地模型路由与 Token 节流术
人工智能·ai·开源·ai编程
nashane1 小时前
HarmonyOS 6学习:长截图功能开发中的滚动拼接与权限处理实战
人工智能·华为·harmonyos
zhojiew1 小时前
在本地PostgreSQL使用pgvector构建生成式 AI 应用的实践
数据库·人工智能·postgresql