Files
cuishou-rag-v2/scripts/batch_compare_systems.py
hughhuangandClaude Sonnet 4.5 77f7483012 feat: 添加批量系统对比分析工具和所有 Excel 系统综合报告
新增功能:
- ✅ 批量系统对比分析工具
- ✅ 所有 Excel 类型系统综合对比报告

新增文件:
- scripts/batch_compare_systems.py
  - 支持同时对比多个系统(2-8个)
  - 多维度对比分析:
    * 整体得分排名
    * 各指标得分排名
    * 综合指标对比表
    * 各系统优劣势分析
    * 按问题类型对比
    * 雷达图数据
    * 综合建议和推荐
  - 自动生成排名和评级
  - 支持性能差距分析

- docs/reports/All_Excel_Systems_Comparison.md
  - 完整的4系统综合对比报告
  - 详细的排名和评级
  - 各指标详细分析
  - 各系统优劣势分析
  - 按问题类型详细对比
  - 生产环境推荐建议

4个Excel系统综合排名:
1. 🥇 zhtv2-excel (0.6271) - ⭐⭐⭐⭐ 良好
2. 🥈 kbs-excel (0.6188) - ⭐⭐⭐⭐ 良好
3. 🥉 zht-excel (0.4455) - ⭐⭐ 较差
4. coze-excel (0.2645) - ⭐ 差

核心发现:
1. zhtv2-excel 整体最优:
   - 检索能力最强(精确度和召回率双第1)
   - 答案相关性最佳(0.8337)
   - 整体最均衡,无明显短板

2. kbs-excel 忠实度最高:
   - 忠实度 0.9609(第1名)
   - 金融催收场景的黄金标准
   - 整体得分仅落后 zhtv2-excel 1.3%

3. zht-excel 表现中等偏下:
   - 简单检索完全失败(0.0000)
   - 召回能力不足(0.4292)
   - 仅在数值/统计类问题上有优势

4. coze-excel 表现最差:
   - 召回能力严重不足(0.1800)
   - 幻觉问题严重(0.2929)
   - 大量问题类型完全无法处理

生产环境推荐:
- 🏆 首选:zhtv2-excel(综合性能最强)
- 🥈 备选:kbs-excel(金融场景首选)

使用示例:
# 批量对比所有系统
python scripts/batch_compare_systems.py \
  data/results/*excel*parallel*.json

# 对比特定系统
python scripts/batch_compare_systems.py \
  data/results/zht-excel_parallel_*.json \
  data/results/zhtv2-excel_parallel_*.json \
  data/results/kbs-excel_parallel_*.json

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-08 09:39:37 +08:00

286 lines
9.4 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
批量系统对比分析工具
支持同时对比多个系统的评估结果
"""
import sys
import os
import json
from pathlib import Path
from typing import Dict, List, Tuple
# 设置 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')
def load_result(file_path: str) -> Dict:
"""加载评估结果"""
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
def format_score(score: float, decimals: int = 4) -> str:
"""格式化分数"""
return f"{score:.{decimals}f}"
def compare_multiple_systems(result_files: List[str]) -> None:
"""对比多个系统的评估结果"""
print("=" * 120)
print(f"多系统对比分析报告(共 {len(result_files)} 个系统)")
print("=" * 120)
print()
# 加载所有结果
results = []
system_names = []
for file_path in result_files:
result = load_result(file_path)
system_name = list(result['results'].keys())[0]
results.append(result)
system_names.append(system_name)
# 提取数据
systems_data = {}
for i, system_name in enumerate(system_names):
systems_data[system_name] = results[i]['results'][system_name]
# 1. 整体得分排名
print("📊 1. 整体得分排名")
print("-" * 120)
print(f"{'排名':<6} {'系统':<20} {'整体得分':<15} {'相对于最佳':<20} {'相对于最差':<20}")
print("-" * 120)
# 按整体得分排序
sorted_systems = sorted(systems_data.items(), key=lambda x: x[1]['overall_score'], reverse=True)
best_score = sorted_systems[0][1]['overall_score']
worst_score = sorted_systems[-1][1]['overall_score']
for rank, (system_name, data) in enumerate(sorted_systems, 1):
score = data['overall_score']
diff_from_best = score - best_score
diff_from_worst = score - worst_score
rank_str = f"第{rank}名"
diff_best_str = f"{diff_from_best:+.4f}" if diff_from_best != 0 else "基准"
diff_worst_str = f"{diff_from_worst:+.4f}"
medal = "🥇" if rank == 1 else ("🥈" if rank == 2 else ("🥉" if rank == 3 else ""))
print(f"{rank_str:<6} {system_name:<20} {format_score(score):<15} {diff_best_str:<20} {diff_worst_str:<20} {medal}")
print()
# 计算提升幅度
print(f"性能差距:")
print(f" 最高分与最低分差距: {best_score - worst_score:.4f} ({((best_score - worst_score) / worst_score * 100):.1f}%)")
print()
# 2. 各指标排名
print("📈 2. 各指标得分排名")
print("-" * 120)
metrics = ['context_precision', 'context_recall', 'faithfulness', 'answer_relevance']
metric_names = {
'context_precision': '上下文精确度',
'context_recall': '上下文召回率',
'faithfulness': '忠实度',
'answer_relevance': '答案相关性'
}
for metric in metrics:
print(f"\n【{metric_names[metric]}】")
print(f"{'排名':<6} {'系统':<20} {'得分':<15} {'相对于最佳':<20}")
print("-" * 120)
# 按该指标排序
metric_scores = []
for system_name in system_names:
score = systems_data[system_name]['positive_cases'][metric]['mean']
metric_scores.append((system_name, score))
metric_scores.sort(key=lambda x: x[1], reverse=True)
best_metric_score = metric_scores[0][1]
for rank, (system_name, score) in enumerate(metric_scores, 1):
diff = score - best_metric_score
diff_str = "基准" if diff == 0 else f"{diff:+.4f}"
medal = "🥇" if rank == 1 else ("🥈" if rank == 2 else ("🥉" if rank == 3 else ""))
print(f"第{rank}名 {system_name:<20} {format_score(score):<15} {diff_str:<20} {medal}")
print()
# 3. 综合指标对比表
print("📊 3. 综合指标对比表")
print("-" * 120)
print(f"{'系统':<20}", end="")
for metric in metrics:
print(f"{metric_names[metric]:<15}", end="")
print(f"{'整体得分':<15}")
print("-" * 120)
# 按整体得分排序显示
for system_name, _ in sorted_systems:
print(f"{system_name:<20}", end="")
for metric in metrics:
score = systems_data[system_name]['positive_cases'][metric]['mean']
print(f"{format_score(score):<15}", end="")
print(f"{format_score(systems_data[system_name]['overall_score']):<15}")
print()
# 4. 各系统优势分析
print("🎯 4. 各系统优势与劣势分析")
print("-" * 120)
for system_name in system_names:
print(f"\n【{system_name}】")
print("-" * 120)
overall = systems_data[system_name]['overall_score']
# 计算各指标相对平均水平的偏差
avg_scores = {}
for metric in metrics:
total = sum([systems_data[s]['positive_cases'][metric]['mean'] for s in system_names])
avg_scores[metric] = total / len(system_names)
print(f"整体得分: {format_score(overall)}")
print(f"\n各指标表现(相对于平均):")
for metric in metrics:
score = systems_data[system_name]['positive_cases'][metric]['mean']
avg = avg_scores[metric]
diff = score - avg
diff_pct = (diff / avg * 100) if avg > 0 else 0
status = "✅ 显著高于平均" if diff_pct > 10 else ("⚠️ 显著低于平均" if diff_pct < -10 else "➡️ 接近平均")
print(f" {metric_names[metric]}: {format_score(score)} ({diff_pct:+.1f}%) {status}")
print()
# 5. 按问题类型对比
print("🔍 5. 按问题类型对比")
print("-" * 120)
# 获取问题类型
first_result = results[0]
question_types = list(first_result.get('analysis_by_question_type', {}).keys())
if question_types:
for qtype in question_types:
print(f"\n【{qtype}】")
print(f"{'排名':<6} {'系统':<20} {'得分':<15}")
print("-" * 120)
# 获取该类型的所有系统得分
type_scores = []
for system_name in system_names:
result = next((r for r in results if system_name in r['results']), None)
if result:
score = result['analysis_by_question_type'][qtype].get(system_name, 0)
type_scores.append((system_name, score))
type_scores.sort(key=lambda x: x[1], reverse=True)
for rank, (system_name, score) in enumerate(type_scores, 1):
medal = "🥇" if rank == 1 else ("🥈" if rank == 2 else ("🥉" if rank == 3 else ""))
print(f"第{rank}名 {system_name:<20} {format_score(score):<15} {medal}")
print()
# 6. 雷达图数据(用于可视化)
print("📊 6. 雷达图数据(可用于可视化)")
print("-" * 120)
print()
print("各系统在四个核心指标上的得分:")
print()
print("系统 | 上下文精确度 | 上下文召回率 | 忠实度 | 答案相关性")
print("-" * 100)
for system_name, _ in sorted_systems:
line = f"{system_name}"
for metric in metrics:
score = systems_data[system_name]['positive_cases'][metric]['mean']
line += f" | {format_score(score)}"
print(line)
print()
# 7. 综合建议
print("=" * 120)
print("💡 综合建议")
print("=" * 120)
print()
# 找出最佳系统
best_system = sorted_systems[0][0]
worst_system = sorted_systems[-1][0]
print(f"✅ 最佳系统: {best_system}")
print(f" 整体得分: {format_score(sorted_systems[0][1]['overall_score'])}")
print()
print(f"⚠️ 最差系统: {worst_system}")
print(f" 整体得分: {format_score(sorted_systems[-1][1]['overall_score'])}")
print(f" 落后最佳: {((sorted_systems[0][1]['overall_score'] - sorted_systems[-1][1]['overall_score']) / sorted_systems[0][1]['overall_score'] * 100):.1f}%")
print()
# 各系统推荐
print("📋 各系统推荐度排名:")
for rank, (system_name, data) in enumerate(sorted_systems, 1):
score = data['overall_score']
# 根据得分给出评级
if score >= 0.7:
rating = "⭐⭐⭐⭐⭐ 优秀"
elif score >= 0.6:
rating = "⭐⭐⭐⭐ 良好"
elif score >= 0.5:
rating = "⭐⭐⭐ 中等"
elif score >= 0.4:
rating = "⭐⭐ 较差"
else:
rating = "⭐ 差"
medal = "🥇" if rank == 1 else ("🥈" if rank == 2 else ("🥉" if rank == 3 else ""))
print(f" {rank}. {system_name:<20} {format_score(score):<10} {rating} {medal}")
print()
print("=" * 120)
def main():
"""主函数"""
if len(sys.argv) < 2:
print("用法: python batch_compare_systems.py <result1.json> <result2.json> ...")
print("\n示例:")
print(" python batch_compare_systems.py \\")
print(" data/results/*excel*parallel*.json")
sys.exit(1)
result_files = sys.argv[1:]
# 验证文件存在
for file_path in result_files:
if not os.path.exists(file_path):
print(f"❌ 文件不存在: {file_path}")
sys.exit(1)
# 批量对比分析
compare_multiple_systems(result_files)
if __name__ == '__main__':
main()