修复问题: - 修复 Answer Correctness 结果合并逻辑 - 正确处理 positive_cases 和 negative_cases 数据结构 - 重新计算统计信息 改进: - 使用 .get() 方法安全访问字典键 - 更新 mean, max, min, median, std 统计信息 - 添加更详细的错误处理 验证: - 成功合并 coze-excel 的 answer_correctness 结果 - 所有 5 个指标现在都包含在结果中 - answer_correctness 均值: 0.2797 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
439 lines
14 KiB
Python
439 lines
14 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
单独评估 answer_correctness 指标
|
||
|
||
用于在快速评估后补充评估 answer_correctness 指标
|
||
"""
|
||
import sys
|
||
import os
|
||
import asyncio
|
||
import argparse
|
||
import json
|
||
from pathlib import Path
|
||
from datetime import datetime
|
||
|
||
# 设置 Windows 控制台编码为 UTF-8
|
||
if sys.platform == 'win32':
|
||
import io
|
||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
|
||
|
||
# 添加项目根目录到 Python 路径
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
|
||
async def evaluate_answer_correctness(
|
||
system: str,
|
||
test_set_path: str,
|
||
enable_parallel: bool = True,
|
||
enable_logging: bool = True
|
||
):
|
||
"""
|
||
单独评估 answer_correctness 指标
|
||
|
||
Args:
|
||
system: 系统名称
|
||
test_set_path: 测试集路径
|
||
enable_parallel: 是否启用并行评估
|
||
enable_logging: 是否启用详细日志
|
||
"""
|
||
from src.transformers.data_converter import DataConverter
|
||
from src.evaluators.configurable_evaluator import ConfigurableRAGAsEvaluator
|
||
from src.utils.evaluation_logger import EvaluationLogger
|
||
|
||
print()
|
||
print("=" * 80)
|
||
print(f"评估系统: {system.upper()}")
|
||
print(f"评估指标: Answer Correctness(答案正确性)")
|
||
print("=" * 80)
|
||
print()
|
||
|
||
# 只启用 answer_correctness 指标
|
||
enabled_metrics = {'answer_correctness'}
|
||
|
||
# 创建日志记录器
|
||
logger = EvaluationLogger(system_name=system) if enable_logging else None
|
||
|
||
if logger:
|
||
print(f"日志文件: {logger.get_log_file_path()}")
|
||
print()
|
||
|
||
start_time = datetime.now()
|
||
print(f"开始时间: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
||
print(f"并行模式: {'启用' if enable_parallel else '禁用'}")
|
||
print()
|
||
|
||
try:
|
||
# 创建数据转换器
|
||
converter = DataConverter(test_set_path)
|
||
|
||
# 加载并转换数据
|
||
print("[1/3] 加载并转换数据...")
|
||
positive_cases, negative_cases = converter.merge_data_for_system(system)
|
||
|
||
print(f" - 正向用例: {len(positive_cases)}")
|
||
print(f" - 负向用例: {len(negative_cases)}")
|
||
print()
|
||
|
||
# 创建可配置评估器(只启用 answer_correctness)
|
||
print("[配置] 初始化评估器...")
|
||
evaluator = ConfigurableRAGAsEvaluator(
|
||
logger=logger,
|
||
enable_parallel=enable_parallel,
|
||
enabled_metrics=enabled_metrics,
|
||
show_progress=True
|
||
)
|
||
print()
|
||
|
||
# 评估正向用例
|
||
print(f"[2/3] 评估正向用例...")
|
||
positive_results = await evaluator.evaluate_batch(positive_cases)
|
||
print()
|
||
|
||
# 评估负向用例
|
||
print(f"[3/3] 评估负向用例...")
|
||
negative_results = await evaluator.evaluate_batch(negative_cases)
|
||
print()
|
||
|
||
end_time = datetime.now()
|
||
duration = (end_time - start_time).total_seconds()
|
||
|
||
print()
|
||
print("=" * 80)
|
||
print("✅ 评估完成!")
|
||
print("=" * 80)
|
||
print(f"结束时间: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
||
print(f"总耗时: {duration:.2f} 秒 ({duration/60:.1f} 分钟)")
|
||
print()
|
||
|
||
# 构建结果
|
||
result = {
|
||
'system': system,
|
||
'timestamp': end_time.isoformat(),
|
||
'metric': 'answer_correctness',
|
||
'positive_cases': {
|
||
'count': len(positive_cases),
|
||
'results': positive_results
|
||
},
|
||
'negative_cases': {
|
||
'count': len(negative_cases),
|
||
'results': negative_results
|
||
},
|
||
'evaluation_mode': 'parallel' if enable_parallel else 'sequential',
|
||
'evaluation_duration_seconds': duration
|
||
}
|
||
|
||
# 保存结果
|
||
print("=" * 80)
|
||
print("保存评估结果")
|
||
print("=" * 80)
|
||
|
||
# 生成文件名
|
||
mode_suffix = 'parallel' if enable_parallel else 'sequential'
|
||
timestamp = end_time.strftime("%Y%m%d_%H%M%S")
|
||
output_path = f'data/results/{system}_answer_correctness_{mode_suffix}_{timestamp}.json'
|
||
|
||
# 确保输出目录存在
|
||
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
||
|
||
# 保存结果
|
||
with open(output_path, 'w', encoding='utf-8') as f:
|
||
json.dump(result, f, ensure_ascii=False, indent=2)
|
||
|
||
print()
|
||
print("✅ 所有任务完成!")
|
||
print()
|
||
print(f"结果文件: {output_path}")
|
||
if logger:
|
||
print(f"日志文件: {logger.get_log_file_path()}")
|
||
print()
|
||
|
||
return 0
|
||
|
||
except Exception as e:
|
||
print()
|
||
print("=" * 80)
|
||
print("❌ 评估失败")
|
||
print("=" * 80)
|
||
print(f"错误类型: {type(e).__name__}")
|
||
print(f"错误信息: {e}")
|
||
print()
|
||
import traceback
|
||
traceback.print_exc()
|
||
return 1
|
||
|
||
|
||
async def merge_answer_correctness(
|
||
original_result_path: str,
|
||
correctness_result_path: str,
|
||
output_path: str = None
|
||
):
|
||
"""
|
||
将 answer_correctness 结果合并到原始评估结果中
|
||
|
||
Args:
|
||
original_result_path: 原始评估结果文件路径
|
||
correctness_result_path: answer_correctness 评估结果文件路径
|
||
output_path: 输出文件路径(如果不提供,覆盖原文件)
|
||
"""
|
||
print()
|
||
print("=" * 80)
|
||
print("合并 Answer Correctness 结果")
|
||
print("=" * 80)
|
||
print()
|
||
|
||
# 读取原始结果
|
||
print(f"[1/3] 读取原始评估结果: {original_result_path}")
|
||
with open(original_result_path, 'r', encoding='utf-8') as f:
|
||
original_data = json.load(f)
|
||
|
||
print(f" - 系统数量: {len(original_data.get('results', {}))}")
|
||
print()
|
||
|
||
# 读取 answer_correctness 结果
|
||
print(f"[2/3] 读取 Answer Correctness 结果: {correctness_result_path}")
|
||
with open(correctness_result_path, 'r', encoding='utf-8') as f:
|
||
correctness_data = json.load(f)
|
||
|
||
print(f" - 正向用例: {correctness_data.get('positive_cases', {}).get('count', 0)}")
|
||
print(f" - 负向用例: {correctness_data.get('negative_cases', {}).get('count', 0)}")
|
||
print()
|
||
|
||
# 合并结果
|
||
print("[3/3] 合并结果...")
|
||
|
||
# 获取系统名称
|
||
system = correctness_data['system']
|
||
|
||
# 检查原始结果中是否包含该系统
|
||
if system not in original_data.get('results', {}):
|
||
print(f"❌ 错误: 原始结果中未找到系统 '{system}'")
|
||
return 1
|
||
|
||
# 创建问题ID到 answer_correctness 结果的映射
|
||
correctness_map = {}
|
||
|
||
# 从 positive_cases 中提取
|
||
positive_cases = correctness_data.get('positive_cases', {})
|
||
if 'results' in positive_cases:
|
||
for result in positive_cases['results']:
|
||
qid = result['question_id']
|
||
correctness_map[qid] = result['scores']['answer_correctness']
|
||
|
||
# 从 negative_cases 中提取
|
||
negative_cases = correctness_data.get('negative_cases', {})
|
||
if 'results' in negative_cases:
|
||
for result in negative_cases['results']:
|
||
qid = result['question_id']
|
||
correctness_map[qid] = result['scores']['answer_correctness']
|
||
|
||
# 更新原始结果中的 answer_correctness 统计
|
||
original_system_data = original_data['results'][system]
|
||
|
||
# 更新正向用例的 answer_correctness 指标
|
||
if 'positive_cases' in original_system_data and 'answer_correctness' in original_system_data['positive_cases']:
|
||
# 更新 per_question 数据
|
||
per_question = original_system_data['positive_cases']['answer_correctness']['per_question']
|
||
updated_count = 0
|
||
for qid in correctness_map:
|
||
if qid in per_question:
|
||
per_question[qid] = correctness_map[qid]
|
||
updated_count += 1
|
||
|
||
# 重新计算统计信息
|
||
scores = list(per_question.values())
|
||
if scores:
|
||
original_system_data['positive_cases']['answer_correctness']['mean'] = sum(scores) / len(scores)
|
||
original_system_data['positive_cases']['answer_correctness']['max'] = max(scores)
|
||
original_system_data['positive_cases']['answer_correctness']['min'] = min(scores)
|
||
original_system_data['positive_cases']['answer_correctness']['median'] = sorted(scores)[len(scores) // 2]
|
||
|
||
# 计算标准差
|
||
if len(scores) > 1:
|
||
mean = original_system_data['positive_cases']['answer_correctness']['mean']
|
||
variance = sum((x - mean) ** 2 for x in scores) / len(scores)
|
||
original_system_data['positive_cases']['answer_correctness']['std'] = variance ** 0.5
|
||
else:
|
||
original_system_data['positive_cases']['answer_correctness']['std'] = 0.0
|
||
|
||
print(f" - 更新了 {updated_count} 个问题的 answer_correctness 得分")
|
||
print()
|
||
|
||
# 更新元数据
|
||
if 'metadata' in original_data:
|
||
original_data['metadata']['answer_correctness_merged'] = True
|
||
original_data['metadata']['answer_correctness_timestamp'] = correctness_data['timestamp']
|
||
original_data['metadata']['answer_correctness_duration'] = correctness_data.get('evaluation_duration_seconds', 0)
|
||
|
||
# 更新指标列表
|
||
metrics_used = original_data['metadata'].get('metrics_used', [])
|
||
if 'answer_correctness' not in metrics_used:
|
||
metrics_used.append('answer_correctness')
|
||
original_data['metadata']['metrics_used'] = metrics_used
|
||
|
||
# 移除禁用列表中的 answer_correctness
|
||
metrics_disabled = original_data['metadata'].get('metrics_disabled', [])
|
||
if 'answer_correctness' in metrics_disabled:
|
||
metrics_disabled.remove('answer_correctness')
|
||
original_data['metadata']['metrics_disabled'] = metrics_disabled
|
||
|
||
# 保存合并后的结果
|
||
if output_path is None:
|
||
output_path = original_result_path
|
||
|
||
# 确保输出目录存在
|
||
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
||
|
||
# 保存结果
|
||
with open(output_path, 'w', encoding='utf-8') as f:
|
||
json.dump(original_data, f, ensure_ascii=False, indent=2)
|
||
|
||
print("=" * 80)
|
||
print("✅ 合并完成!")
|
||
print("=" * 80)
|
||
print(f"输出文件: {output_path}")
|
||
print()
|
||
|
||
return 0
|
||
|
||
|
||
def main():
|
||
"""主函数"""
|
||
parser = argparse.ArgumentParser(
|
||
description='单独评估 answer_correctness 指标',
|
||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||
epilog="""
|
||
使用场景:
|
||
1. 先快速评估(禁用 answer_correctness):
|
||
python scripts/evaluate_with_config.py --system zht-excel --disable answer_correctness
|
||
|
||
2. 再单独评估 answer_correctness:
|
||
python scripts/evaluate_answer_correctness.py --system zht-excel
|
||
|
||
3. 合并结果(可选):
|
||
python scripts/evaluate_answer_correctness.py \\
|
||
--merge data/results/zht-excel_parallel_*.json \\
|
||
--correctness data/results/zht-excel_answer_correctness_*.json \\
|
||
--output data/results/zht-excel_full_result.json
|
||
|
||
示例:
|
||
# 评估单个系统的 answer_correctness
|
||
python scripts/evaluate_answer_correctness.py --system zht-excel
|
||
|
||
# 评估并禁用日志
|
||
python scripts/evaluate_answer_correctness.py --system zht-excel --no-logging
|
||
|
||
# 合并结果
|
||
python scripts/evaluate_answer_correctness.py \\
|
||
--merge original.json \\
|
||
--correctness correctness.json \\
|
||
--output merged.json
|
||
"""
|
||
)
|
||
|
||
# 操作模式
|
||
group = parser.add_mutually_exclusive_group(required=True)
|
||
|
||
group.add_argument(
|
||
'--system',
|
||
type=str,
|
||
help='系统名称(用于评估模式)'
|
||
)
|
||
|
||
group.add_argument(
|
||
'--merge',
|
||
type=str,
|
||
dest='original_result',
|
||
help='原始评估结果文件路径(用于合并模式)'
|
||
)
|
||
|
||
# 合并模式的参数
|
||
parser.add_argument(
|
||
'--correctness',
|
||
type=str,
|
||
dest='correctness_result',
|
||
help='answer_correctness 评估结果文件路径(合并模式必需)'
|
||
)
|
||
|
||
parser.add_argument(
|
||
'--output',
|
||
type=str,
|
||
help='输出文件路径(合并模式可选,默认覆盖原文件)'
|
||
)
|
||
|
||
# 评估模式的参数
|
||
parser.add_argument(
|
||
'--test-set',
|
||
type=str,
|
||
default='data/test_sets/ragas_test_cases_v3.1.json',
|
||
help='测试集路径(默认: data/test_sets/ragas_test_cases_v3.1.json)'
|
||
)
|
||
|
||
parser.add_argument(
|
||
'--no-parallel',
|
||
action='store_true',
|
||
help='禁用并行评估(使用串行模式)'
|
||
)
|
||
|
||
parser.add_argument(
|
||
'--no-logging',
|
||
action='store_true',
|
||
help='禁用详细日志记录(默认启用)'
|
||
)
|
||
|
||
args = parser.parse_args()
|
||
|
||
# 显示配置
|
||
print()
|
||
print("=" * 80)
|
||
print("Answer Correctness 评估工具")
|
||
print("=" * 80)
|
||
|
||
if args.system:
|
||
# 评估模式
|
||
print(f"模式: 评估")
|
||
print(f"系统: {args.system}")
|
||
print(f"并行: {'启用' if not args.no_parallel else '禁用'}")
|
||
print(f"日志: {'启用' if not args.no_logging else '禁用'}")
|
||
print("=" * 80)
|
||
|
||
exit_code = asyncio.run(evaluate_answer_correctness(
|
||
system=args.system,
|
||
test_set_path=args.test_set,
|
||
enable_parallel=not args.no_parallel,
|
||
enable_logging=not args.no_logging
|
||
))
|
||
else:
|
||
# 合并模式
|
||
if not args.correctness_result:
|
||
parser.error("--merge 模式需要 --correctness 参数")
|
||
|
||
print(f"模式: 合并")
|
||
print(f"原始结果: {args.original_result}")
|
||
print(f"Answer Correctness 结果: {args.correctness_result}")
|
||
print(f"输出文件: {args.output or '覆盖原文件'}")
|
||
print("=" * 80)
|
||
|
||
exit_code = asyncio.run(merge_answer_correctness(
|
||
original_result_path=args.original_result,
|
||
correctness_result_path=args.correctness_result,
|
||
output_path=args.output
|
||
))
|
||
|
||
return exit_code
|
||
|
||
|
||
if __name__ == '__main__':
|
||
try:
|
||
exit_code = main()
|
||
sys.exit(exit_code)
|
||
except KeyboardInterrupt:
|
||
print("\n\n⚠️ 评估被用户中断")
|
||
sys.exit(1)
|
||
except Exception as e:
|
||
print(f"\n\n❌ 未预期的错误: {e}")
|
||
import traceback
|
||
traceback.print_exc()
|
||
sys.exit(1)
|