【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}
相关推荐
IT_Octopus7 分钟前
【零基础入门 LLM 开发 · Day 13】:LangChain 的对话记忆——Message 对象版
人工智能·python·langchain
2603_9651481128 分钟前
社区与学习资源:从入门到精通的API选品学习路径
数据库·人工智能·python·学习·数据挖掘
LiuPig刘皮哥29 分钟前
2026年开源3D陪玩对比:xiaoke.ai、AIRI、Open-LLM-VTuber、Amica 有什么、没有什么
人工智能·3d·开源
西柚小萌新35 分钟前
【岗位面试】--成都博维数孪 - 工业 AI 解决方案顾问
人工智能·面试·职场和发展
Luminbox紫创测控44 分钟前
车载LiDAR强光测试的实验设计方法与数据分析
人工智能·数据挖掘·数据分析·车载系统·安全性测试·太阳光模拟器
建筑工程企业管理系统2 小时前
工程进度统计管理系统自动化汇总数据,解决施工企业手工对账误差难题
大数据·人工智能·自动化
唠点键盘之外的2 小时前
27 存量系统接大模型:旁挂一个 AI 微服务,老架构一行不改
人工智能·微服务·架构
kaixin_啊啊2 小时前
【用于更准确 G×E 基因组预测的大规模作物数据集与基于深度学习的多模态融合框架】论文学习
人工智能·深度学习·学习
GOWIN革文品牌咨询3 小时前
工业测量品牌系统化搭建指南:从内容架构到长期治理的全流程
大数据·人工智能·架构
拿本唠嗑AI研究3 小时前
本体工程实战指南:从建模到可维护的完整落地路径
java·人工智能·python·jena·ontology