Repository navigation
Expand file tree
/
Copy pathevaluate_batch.py
More file actions
165 lines (128 loc) · 5.01 KB
/
Copy pathevaluate_batch.py
File metadata and controls
165 lines (128 loc) · 5.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/usr/bin/env python3
"""
Batch evaluation script for all search results.
Evaluates BM25, Vector Search, and Hybrid (BM25 + Rerank) results on dev and eval datasets.
"""
from dataclasses import dataclass
from pathlib import Path
import tyro
from .evaluate import evaluate, EvalConfig
@dataclass
class BatchEvalConfig:
"""Configuration for batch evaluation."""
results_dir: Path = Path("results")
"""Directory containing result files"""
data_dir: Path = Path("data")
"""Directory containing qrels files"""
output_table: bool = True
"""Print summary table"""
eval_systems: str = "all"
"""Which systems to evaluate: 'all', 'bm25', 'vector', 'hybrid'"""
def run_batch_evaluation(config: BatchEvalConfig) -> dict:
"""
Run evaluation on all datasets.
Args:
config: Batch evaluation configuration
Returns:
Dictionary mapping dataset name to metrics
"""
print("\n" + "=" * 70)
print(" SEARCH SYSTEMS EVALUATION")
print("=" * 70)
# Define base evaluation tasks (datasets)
datasets = [
{
'name': 'Dev Set',
'qrels': config.data_dir / 'qrels.dev.tsv',
'use_map': True, # Binary relevance
'num_queries': 1000,
},
{
'name': 'TREC 2019',
'qrels': config.data_dir / 'qrels.eval.one.tsv',
'use_map': False, # Graded relevance
'num_queries': 43,
},
{
'name': 'TREC 2020',
'qrels': config.data_dir / 'qrels.eval.two.tsv',
'use_map': False, # Graded relevance
'num_queries': 54,
}
]
# Define search systems
systems = []
if config.eval_systems in ['all', 'bm25']:
systems.append({
'name': 'BM25',
'file_suffix': 'bm25',
})
if config.eval_systems in ['all', 'vector']:
systems.append({
'name': 'Vector',
'file_suffix': 'vector',
})
if config.eval_systems in ['all', 'hybrid']:
systems.append({
'name': 'Hybrid',
'file_suffix': 'hybrid',
})
all_results = {}
for system in systems:
print(f"\n{'=' * 70}")
print(f" {system['name']} SYSTEM")
print(f"{'=' * 70}")
for dataset in datasets:
# Construct result file path
if dataset['name'] == 'Dev Set':
result_file = config.results_dir / f"{system['file_suffix']}_dev.txt"
elif dataset['name'] == 'TREC 2019':
result_file = config.results_dir / f"{system['file_suffix']}_eval_one.txt"
else: # TREC 2020
result_file = config.results_dir / f"{system['file_suffix']}_eval_two.txt"
task_name = f"{system['name']} - {dataset['name']}"
print(f"\n{'-' * 70}")
print(f" {task_name} ({dataset['num_queries']} queries)")
print(f"{'-' * 70}")
if not result_file.exists():
print(f"Warning: Result file not found: {result_file}")
print("Skipping this evaluation.")
continue
try:
eval_config = EvalConfig(
qrels=dataset['qrels'],
results=result_file,
use_map=dataset['use_map'],
verbose=True
)
metrics = evaluate(eval_config)
all_results[task_name] = metrics
except FileNotFoundError as e:
print(f"Error: {e}")
print("Skipping this evaluation.")
# Print summary table
if config.output_table and all_results:
print("\n" + "=" * 95)
print(" SUMMARY TABLE")
print("=" * 95)
print(f"{'System - Dataset':<30} {'MRR@10':<10} {'Recall@100':<12} {'NDCG@10':<10} {'NDCG@100':<11} {'MAP':<10}")
print("-" * 95)
for name, metrics in all_results.items():
mrr = f"{metrics.get('mrr@10', 0.0):.4f}"
recall = f"{metrics.get('recall@100', 0.0):.4f}"
ndcg10 = f"{metrics.get('ndcg@10', 0.0):.4f}" if 'ndcg@10' in metrics else "-"
ndcg100 = f"{metrics.get('ndcg@100', 0.0):.4f}" if 'ndcg@100' in metrics else "-"
map_score = f"{metrics.get('map', 0.0):.4f}" if 'map' in metrics else "-"
print(f"{name:<30} {mrr:<10} {recall:<12} {ndcg10:<10} {ndcg100:<11} {map_score:<10}")
print("=" * 95)
print()
return all_results
def main(config: BatchEvalConfig) -> None:
"""Main batch evaluation function."""
if not config.results_dir.exists():
raise FileNotFoundError(f"Results directory not found: {config.results_dir}")
if not config.data_dir.exists():
raise FileNotFoundError(f"Data directory not found: {config.data_dir}")
run_batch_evaluation(config)
if __name__ == '__main__':
tyro.cli(main)