当前位置: 首页 > news >正文

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

安装依赖

pip install nltk rouge-score

批量处理代码

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')     # 用于 tokenizedef 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()# 将每个参考句子 tokenizetokenized_references = [[nltk.word_tokenize(sent) for sent in ref] for ref in references]# 将每个候选句子 tokenizetokenized_candidates = [nltk.word_tokenize(sent) for sent in candidates]# 计算 corpus BLEUbleu_score = corpus_bleu(tokenized_references,tokenized_candidates,weights=(0.25, 0.25, 0.25, 0.25),smoothing_function=smoothing.method1)return bleu_scoredef batch_rouge(references, candidates):"""计算批量 ROUGE 分数 (ROUGE-1, ROUGE-2, ROUGE-L)Args:references: List of reference sentences (每个样本一个参考句)candidates: List of candidate sentencesReturns: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_scoresdef evaluate_all(references, candidates):"""同时计算 BLEU 和 ROUGE 的批量评估函数Args:references: List of reference sentencescandidates: List of candidate sentencesReturns: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)}

测试代码

# 示例数据:批量输入
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)

输出

Evaluation Results: {'BLEU': 0.1966, 'ROUGE-1': 0.8782, 'ROUGE-2': 0.6636, 'ROUGE-L': 0.8782}
http://www.xdnf.cn/news/448957.html

相关文章:

  • 代理IP与VPN的区别,如何根据需求选择?
  • Vector和list
  • FastAPI + OpenAI 模型 的 GitHub 项目结构模板
  • OPC UA + ABP vNext 企业级实战:高可用数据采集框架指南
  • 基于OAuth2+SpringSecurity+Jwt实现身份认证和权限管理后端服务
  • 自注意力机制(Self-Attention)前向传播手撕
  • 记录一次git提交失败解决方案
  • 某智能家电龙头,社招 校招全面应用 AI 面试的创新实践
  • 企业应收账款管理体系构建指南
  • CN 第二章 应用层-单选题
  • day 16 Numpy数组与Shap值的深入理解
  • 让 Cursor 教我写 MCP Client
  • 生成本地package
  • 什么是生产管理三大核心计划机制,需求、物料、生产计划的区分与实施方法
  • MySQL 学习(九)bin log 与 redo log 的区别有哪些,为什么快速恢复使用 redo log 而不用 bin log?
  • Hadoop集群故障节点隔离操作指南
  • 【行为型之策略模式】游戏开发实战——Unity灵活算法架构的核心实现策略
  • AE FC77X77XXFC78X78XXFC79X MFC质量流量计 Mass Flow Controllers user manual
  • 电流检测放大器的优质选择XBLW-INA180/INA181
  • 半成品的开源双系统VLA模型,OpenHelix-发表于2025.5.6
  • MySQL库级管理:数据库管理与存储引擎剖析
  • 2002-2024年地级市新质生产力词频统计数据(46个关键词词频)
  • 【大模型面试每日一题】Day 18:大模型中KV Cache的作用是什么?如何通过Window Attention优化其内存占用?
  • Java并发编程:深入浅出掌握多线程艺术
  • Docker 介绍与使用
  • 【idea】调试篇 idea调试技巧合集
  • QFileDialog文件选择框
  • 解决 PicGo 上传 GitHub图床及Marp中Github图片编译常见难题指南
  • acwing 3653. 好坑的电子地图 最短路 dijkstra算法
  • 如何用Redis实现分布式锁?RedLock算法的核心思想?Redisson的看门狗机制原理?