Files
cuishou-rag-v2/scripts/compare_systems.py
T
hughhuangandClaude Sonnet 4.5 607d880658 feat: 添加系统对比分析工具和 ZHT vs ZHTv2 对比报告
新增功能:
- ✅ 系统对比分析工具
- ✅ 详细的对比报告生成

新增文件:
- scripts/compare_systems.py
  - 加载两个系统的评估结果
  - 多维度对比分析:
    * 整体得分对比
    * 各指标得分对比
    * 按问题类型对比
    * 逐问题详细对比
    * 统计摘要
    * 负向用例表现
  - 自动生成对比报告
  - 支持 UTF-8 编码输出

- docs/reports/ZHT_vs_ZHTv2_Comparison.md
  - 完整的对比分析报告
  - 核心结论和推荐建议
  - 详细的指标和问题类型对比
  - 改进建议和下一步计划

ZHT vs ZHTv2 对比核心发现:
1. zhtv2-excel 整体得分提升 40.76%(0.4455 → 0.6271)
2. 所有核心指标显著提升:
   - 上下文召回率: +65.6%
   - 忠实度: +54.3%
   - 上下文精确度: +39.4%
   - 答案相关性: +17.5%
3. zhtv2-excel 在 7/10 个问题类型上更优
4. 负向用例拒绝率:两个系统均为 0(需要改进)

使用示例:
# 对比两个系统
python scripts/compare_systems.py \
  data/results/zht-excel_parallel_*.json \
  data/results/zhtv2-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:28:55 +08:00

265 lines
8.8 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
系统对比分析工具
"""
import sys
import os
# 设置 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')
import json
from pathlib import Path
from typing import Dict, List, Tuple
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 format_diff(score1: float, score2: float, decimals: int = 4) -> str:
"""格式化差异"""
diff = score2 - score1
sign = "+" if diff > 0 else ""
return f"{sign}{diff:.{decimals}f}"
def compare_systems(result1: Dict, result2: Dict) -> None:
"""对比两个系统的评估结果"""
# 提取系统名称和数据
system1_name = list(result1['results'].keys())[0]
system2_name = list(result2['results'].keys())[0]
data1 = result1['results'][system1_name]
data2 = result2['results'][system2_name]
print("=" * 100)
print(f"系统对比分析报告: {system1_name} vs {system2_name}")
print("=" * 100)
print()
# 1. 整体对比
print("📊 1. 整体得分对比")
print("-" * 100)
overall1 = data1.get('overall_score', 0)
overall2 = data2.get('overall_score', 0)
print(f"{'系统':<20} {'整体得分':<15} {'差异':<15} {'表现':<20}")
print("-" * 100)
print(f"{system1_name:<20} {format_score(overall1):<15} {'-':<15} {'基准':<20}")
print(f"{system2_name:<20} {format_score(overall2):<15} {format_diff(overall1, overall2):<15} {'✅ 更优' if overall2 > overall1 else '❌ 较差'}")
print()
improvement = ((overall2 - overall1) / overall1 * 100) if overall1 > 0 else 0
print(f"整体提升: {improvement:+.2f}%")
print()
# 2. 各指标对比(正向用例)
print("📈 2. 各指标得分对比(正向用例)")
print("-" * 100)
print(f"{'指标':<20} {system1_name:<20} {system2_name:<20} {'差异':<15} {'改进':<15}")
print("-" * 100)
metrics = ['context_precision', 'context_recall', 'faithfulness', 'answer_relevance']
metric_names = {
'context_precision': '上下文精确度',
'context_recall': '上下文召回率',
'faithfulness': '忠实度',
'answer_relevance': '答案相关性'
}
for metric in metrics:
score1 = data1['positive_cases'][metric]['mean']
score2 = data2['positive_cases'][metric]['mean']
diff = score2 - score1
diff_pct = (diff / score1 * 100) if score1 > 0 else 0
print(f"{metric_names[metric]:<20} {format_score(score1):<20} {format_score(score2):<20} {format_diff(score1, score2):<15} {diff_pct:+.1f}%")
print()
# 3. 按问题类型对比
print("🔍 3. 按问题类型对比")
print("-" * 100)
print(f"{'问题类型':<20} {system1_name:<20} {system2_name:<20} {'差异':<15} {'优胜者':<15}")
print("-" * 100)
analysis1 = result1.get('analysis_by_question_type', {})
analysis2 = result2.get('analysis_by_question_type', {})
for qtype in analysis1.keys():
score1 = analysis1[qtype][system1_name]
score2 = analysis2[qtype][system2_name]
diff = score2 - score1
winner = system2_name if score2 > score1 else system1_name
print(f"{qtype:<20} {format_score(score1):<20} {format_score(score2):<20} {format_diff(score1, score2):<15} {winner:<15}")
print()
# 4. 逐问题详细对比
print("📝 4. 逐问题详细对比")
print("-" * 100)
for metric in metrics:
print(f"\n【{metric_names[metric]}】")
print(f"{'问题ID':<10} {system1_name:<15} {system2_name:<15} {'差异':<15} {'优胜者':<15}")
print("-" * 100)
per_q1 = data1['positive_cases'][metric]['per_question']
per_q2 = data2['positive_cases'][metric]['per_question']
for qid in sorted(per_q1.keys()):
score1 = per_q1[qid]
score2 = per_q2[qid]
diff = score2 - score1
winner = system2_name if score2 > score1 else (system1_name if score1 > score2 else "平局")
print(f"{qid:<10} {format_score(score1):<15} {format_score(score2):<15} {format_diff(score1, score2):<15} {winner:<15}")
print()
# 5. 统计信息
print("📊 5. 统计摘要")
print("-" * 100)
# 计算各指标的提升
print("\n指标提升情况:")
for metric in metrics:
score1 = data1['positive_cases'][metric]['mean']
score2 = data2['positive_cases'][metric]['mean']
improvement = ((score2 - score1) / score1 * 100) if score1 > 0 else 0
status = "✅ 显著提升" if improvement > 20 else ("⚠️ 小幅提升" if improvement > 0 else "❌ 下降")
print(f" {metric_names[metric]}: {improvement:+.1f}% {status}")
print()
# 找出最大提升和最大下降的问题
print("问题级别分析:")
max_improvement = {'q': None, 'metric': None, 'value': -999}
max_decline = {'q': None, 'metric': None, 'value': 999}
for metric in metrics:
per_q1 = data1['positive_cases'][metric]['per_question']
per_q2 = data2['positive_cases'][metric]['per_question']
for qid in per_q1.keys():
diff = per_q2[qid] - per_q1[qid]
if diff > max_improvement['value']:
max_improvement = {'q': qid, 'metric': metric_names[metric], 'value': diff}
if diff < max_decline['value']:
max_decline = {'q': qid, 'metric': metric_names[metric], 'value': diff}
print(f" 最大提升: {max_improvement['q']} ({max_improvement['metric']}) {format_diff(0, max_improvement['value'])}")
print(f" 最大下降: {max_decline['q']} ({max_decline['metric']}) {format_diff(0, max_decline['value'])}")
print()
# 6. 负向用例对比
print("⚠️ 6. 负向用例表现(拒绝率)")
print("-" * 100)
rejection1 = data1['negative_cases']['rejection_rate']['value']
rejection2 = data2['negative_cases']['rejection_rate']['value']
print(f"{'系统':<20} {'拒绝率':<15} {'说明':<40}")
print("-" * 100)
print(f"{system1_name:<20} {format_score(rejection1):<15} {'拒绝负向用例的比例':<40}")
print(f"{system2_name:<20} {format_score(rejection2):<15} {'拒绝负向用例的比例':<40}")
print()
if rejection1 == 0 and rejection2 == 0:
print("⚠️ 注意:两个系统都未能拒绝任何负向用例,这可能表明:")
elif rejection2 > rejection1:
print(f"✅ {system2_name} 在负向用例拒绝率上优于 {system1_name}")
else:
print(f"❌ {system2_name} 在负向用例拒绝率上不如 {system1_name}")
print()
# 7. 总结和建议
print("=" * 100)
print("💡 总结与建议")
print("=" * 100)
print()
if overall2 > overall1:
print(f"✅ {system2_name} 整体表现优于 {system1_name}")
print(f" - 整体得分提升: {improvement:.2f}%")
print(f" - 建议优先采用 {system2_name}")
else:
print(f"❌ {system2_name} 整体表现不如 {system1_name}")
print(f" - 整体得分下降: {improvement:.2f}%")
print(f" - 需要进一步分析 {system2_name} 的问题")
print()
# 找出优势领域
print(f"{system2_name} 的优势领域:")
advantages = []
for qtype in analysis1.keys():
if analysis2[qtype][system2_name] > analysis1[qtype][system1_name]:
advantages.append(qtype)
if advantages:
for adv in advantages:
print(f" ✅ {adv}")
else:
print(f" ⚠️ 无明显优势领域")
print()
# 找出劣势领域
print(f"{system2_name} 的劣势领域:")
disadvantages = []
for qtype in analysis1.keys():
if analysis2[qtype][system2_name] < analysis1[qtype][system1_name]:
disadvantages.append(qtype)
if disadvantages:
for dis in disadvantages:
print(f" ❌ {dis}")
else:
print(f" ✅ 无明显劣势领域")
print()
print("=" * 100)
def main():
"""主函数"""
if len(sys.argv) != 3:
print("用法: python compare_systems.py <result1.json> <result2.json>")
print("\n示例:")
print(" python compare_systems.py \\")
print(" data/results/zht-excel_parallel_*.json \\")
print(" data/results/zhtv2-excel_parallel_*.json")
sys.exit(1)
file1 = sys.argv[1]
file2 = sys.argv[2]
# 加载结果
result1 = load_result(file1)
result2 = load_result(file2)
# 对比分析
compare_systems(result1, result2)
if __name__ == '__main__':
main()