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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//! Ranking evaluation metrics for Named Entity Disambiguation (NED).
//!
//! Integrates with `rank-eval` crate for standardized IR metrics:
//! - NDCG@k (Normalized Discounted Cumulative Gain)
//! - MRR (Mean Reciprocal Rank)
//! - Precision@k, Recall@k
//! - MAP (Mean Average Precision)
//!
//! # Use Cases
//!
//! 1. **Entity Linking**: Evaluate ranked candidate KB entities for each mention
//! 2. **Cross-doc Coref**: Score ranked cluster candidates
//! 3. **Entity Retrieval**: Evaluate search results over entity indices
//!
//! # Example
//!
//! ```rust,ignore
//! use anno_eval::eval::ranking::{NedMetrics, CandidateRanking};
//!
//! // Gold entity for a mention
//! let gold_kb_id = "Q76"; // Barack Obama in Wikidata
//!
//! // Ranked candidates from NED system (best first)
//! let candidates = vec![
//! ("Q76", 0.95), // Correct: Barack Obama
//! ("Q15180901", 0.8), // Wrong: Barack Obama Sr.
//! ("Q45780", 0.6), // Wrong: Some other entity
//! ];
//!
//! let ranking = CandidateRanking::new(candidates, gold_kb_id);
//! let metrics = NedMetrics::compute(&ranking, 5);
//!
//! println!("MRR: {:.3}", metrics.mrr); // 1.0 (correct at rank 1)
//! println!("P@1: {:.3}", metrics.precision_at_1); // 1.0
//! println!("Hits@5: {:.3}", metrics.hits_at_5); // 1.0
//! ```
use std::collections::HashSet;
/// Metrics for Named Entity Disambiguation evaluation.
#[derive(Debug, Clone, Default)]
pub struct NedMetrics {
/// Mean Reciprocal Rank: 1/rank of first correct candidate
pub mrr: f64,
/// Precision at k=1 (accuracy of top prediction)
pub precision_at_1: f64,
/// Precision at k=5
pub precision_at_5: f64,
/// Recall at k=5
pub recall_at_5: f64,
/// Hits@5: 1.0 if correct in top 5, else 0.0
pub hits_at_5: f64,
/// NDCG@5 (Normalized Discounted Cumulative Gain)
pub ndcg_at_5: f64,
/// NDCG@10
pub ndcg_at_10: f64,
}
/// Represents a ranked list of KB candidates for entity disambiguation.
#[derive(Debug, Clone)]
pub struct CandidateRanking {
/// Ranked candidates (kb_id, score) - highest score first
pub candidates: Vec<(String, f64)>,
/// Gold KB ID(s) for this mention
pub gold_ids: HashSet<String>,
}
impl CandidateRanking {
/// Create a new ranking with single gold entity.
pub fn new<I, S>(candidates: I, gold_id: &str) -> Self
where
I: IntoIterator<Item = (S, f64)>,
S: Into<String>,
{
let mut gold_ids = HashSet::new();
gold_ids.insert(gold_id.to_string());
Self {
candidates: candidates
.into_iter()
.map(|(s, score)| (s.into(), score))
.collect(),
gold_ids,
}
}
/// Create a new ranking with multiple gold entities (for aliases).
pub fn with_multiple_gold<I, S, G>(candidates: I, gold_ids: G) -> Self
where
I: IntoIterator<Item = (S, f64)>,
S: Into<String>,
G: IntoIterator<Item = String>,
{
Self {
candidates: candidates
.into_iter()
.map(|(s, score)| (s.into(), score))
.collect(),
gold_ids: gold_ids.into_iter().collect(),
}
}
/// Check if a candidate is correct (matches any gold ID).
pub fn is_correct(&self, candidate_id: &str) -> bool {
self.gold_ids.contains(candidate_id)
}
}
impl NedMetrics {
/// Compute all NED metrics for a single ranking.
pub fn compute(ranking: &CandidateRanking, _max_k: usize) -> Self {
// Simple fallback implementation
let mut mrr = 0.0;
for (i, (id, _)) in ranking.candidates.iter().enumerate() {
if ranking.is_correct(id) {
mrr = 1.0 / (i + 1) as f64;
break;
}
}
let hits_at_5 = if ranking
.candidates
.iter()
.take(5)
.any(|(id, _)| ranking.is_correct(id))
{
1.0
} else {
0.0
};
Self {
mrr,
precision_at_1: if ranking
.candidates
.first()
.map(|(id, _)| ranking.is_correct(id))
.unwrap_or(false)
{
1.0
} else {
0.0
},
precision_at_5: 0.0, // Simplified
recall_at_5: 0.0, // Simplified
hits_at_5,
ndcg_at_5: 0.0, // Requires full computation
ndcg_at_10: 0.0,
}
}
/// Aggregate metrics across multiple rankings.
pub fn aggregate(metrics: &[Self]) -> Self {
if metrics.is_empty() {
return Self::default();
}
let n = metrics.len() as f64;
Self {
mrr: metrics.iter().map(|m| m.mrr).sum::<f64>() / n,
precision_at_1: metrics.iter().map(|m| m.precision_at_1).sum::<f64>() / n,
precision_at_5: metrics.iter().map(|m| m.precision_at_5).sum::<f64>() / n,
recall_at_5: metrics.iter().map(|m| m.recall_at_5).sum::<f64>() / n,
hits_at_5: metrics.iter().map(|m| m.hits_at_5).sum::<f64>() / n,
ndcg_at_5: metrics.iter().map(|m| m.ndcg_at_5).sum::<f64>() / n,
ndcg_at_10: metrics.iter().map(|m| m.ndcg_at_10).sum::<f64>() / n,
}
}
}
/// Evaluate a full NED system on a dataset.
///
/// Returns aggregated metrics across all mentions.
pub fn evaluate_ned(rankings: &[CandidateRanking]) -> NedMetrics {
let metrics: Vec<NedMetrics> = rankings
.iter()
.map(|r| NedMetrics::compute(r, 10))
.collect();
NedMetrics::aggregate(&metrics)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_candidate_ranking_correct_at_1() {
let ranking = CandidateRanking::new(
vec![("Q76", 0.95), ("Q15180901", 0.8), ("Q45780", 0.6)],
"Q76",
);
let metrics = NedMetrics::compute(&ranking, 10);
assert!((metrics.mrr - 1.0).abs() < 0.01);
assert!((metrics.precision_at_1 - 1.0).abs() < 0.01);
assert!((metrics.hits_at_5 - 1.0).abs() < 0.01);
}
#[test]
fn test_candidate_ranking_correct_at_3() {
let ranking = CandidateRanking::new(
vec![
("Q15180901", 0.9),
("Q45780", 0.8),
("Q76", 0.7), // Correct at position 3
],
"Q76",
);
let metrics = NedMetrics::compute(&ranking, 10);
// MRR = 1/3 = 0.333...
assert!((metrics.mrr - 1.0 / 3.0).abs() < 0.01);
assert!((metrics.precision_at_1 - 0.0).abs() < 0.01);
assert!((metrics.hits_at_5 - 1.0).abs() < 0.01);
}
#[test]
fn test_candidate_ranking_not_in_top_k() {
let ranking = CandidateRanking::new(
vec![
("Q1", 0.9),
("Q2", 0.8),
("Q3", 0.7),
("Q4", 0.6),
("Q5", 0.5),
("Q76", 0.4), // Correct at position 6
],
"Q76",
);
let metrics = NedMetrics::compute(&ranking, 10);
// Not in top 5
assert!((metrics.hits_at_5 - 0.0).abs() < 0.01);
// MRR = 1/6
assert!((metrics.mrr - 1.0 / 6.0).abs() < 0.01);
}
#[test]
fn test_aggregate_metrics() {
let metrics = vec![
NedMetrics {
mrr: 1.0,
precision_at_1: 1.0,
..Default::default()
},
NedMetrics {
mrr: 0.5,
precision_at_1: 0.0,
..Default::default()
},
];
let agg = NedMetrics::aggregate(&metrics);
assert!((agg.mrr - 0.75).abs() < 0.01);
assert!((agg.precision_at_1 - 0.5).abs() < 0.01);
}
#[test]
fn test_multiple_gold_ids() {
// Entity with multiple valid KB IDs (aliases)
let ranking = CandidateRanking::with_multiple_gold(
vec![("Q2", 0.9), ("Q1", 0.8)], // Q1 is correct
vec!["Q1".to_string(), "Q3".to_string()],
);
let metrics = NedMetrics::compute(&ranking, 10);
// Q1 is at position 2
assert!((metrics.mrr - 0.5).abs() < 0.01);
}
}