#!/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 ...") 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()