Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
TASK : Generalised robustness metrics Pipeline (logits or predictions or loss values)
NOTE : using the only torch module we have implement below scratch
Problem Statement:
In Named Entity Linking (NEL), these metrics evaluate the accuracy and relevance of linking detected entities to entries in a knowledge base. Below are the mathematical formulations:
1. Linking Accuracy
Linking Accuracy measures the proportion of named entities that are correctly linked to the appropriate knowledge base entries out of the total detected entities.
For a batch of size ( B ) with ( E ) entities per instance:
[
\text{Linking Accuracy} = \frac{1}{B} \sum_{i=1}^{B} \frac{\text{Correct Links}_i}{\text{Total Entities}_i}
]
where:
( \text{Correct Links}_i ) is the number of correctly linked entities in instance ( i ).
( \text{Total Entities}_i ) is the total number of entities detected in instance ( i ).
This metric reflects the accuracy of entity linking across instances in the batch.
2. Mean Reciprocal Rank (MRR) for Linking
MRR is a ranking-based metric that evaluates the relevance of the linked entity by using the rank of the first correct link among candidate links. A higher rank (lower index) for the correct link leads to a higher MRR.
For each entity in a batch of size ( B ) with ( E ) entities per instance, MRR is given by:
[
\text{MRR} = \frac{1}{B} \sum_{i=1}^{B} \frac{1}{E} \sum_{j=1}^{E} \frac{1}{\text{Rank}_{ij}}
]
where:
( \text{Rank}_{ij} ) is the rank position of the first correct link for the ( j )-th entity in instance ( i ).
( E ) is the number of entities per instance.
This metric emphasizes the accuracy of early correct matches, penalizing cases where the correct entity is ranked lower.
3. Entity Link Precision
Assistant
Entity Link Precision calculates the fraction of entities correctly linked out of all entities identified and linked, giving a measure of the accuracy of the linking task.
For a batch of size ( B ) with ( E ) entities per instance:
[
\text{Entity Link Precision} = \frac{1}{B} \sum_{i=1}^{B} \frac{\text{True Positives}_i}{\text{True Positives}_i + \text{False Positives}_i}
]
where:
( \text{True Positives}_i ) is the count of entities correctly linked to knowledge base entries in instance ( i ).
( \text{False Positives}_i ) is the count of incorrectly linked entities in instance ( i ).
This precision measure reflects the model's ability to link entities accurately, avoiding incorrect associations.
These metrics provide a comprehensive evaluation of the effectiveness of Named Entity Linking models by assessing accuracy, ranking quality, and precision in linking tasks.
python
import torch
from typing import Optional, Tuple
class NELMetrics:
"""
A pipeline to compute robustness metrics for Named Entity Linking (NEL),
including Linking Accuracy, Mean Reciprocal Rank (MRR), and Entity Link Precision.
Attributes:
sum_linking_accuracy (float): Cumulative linking accuracy across batches.
sum_reciprocal_ranks (float): Cumulative reciprocal ranks for MRR calculation.
sum_precision (float): Cumulative precision across batches.
num_batches (int): Number of batches processed.
"""
def __init__(self) -> None:
"""Initialize the NELMetrics pipeline."""
self.sum_linking_accuracy: float = 0.0
self.sum_reciprocal_ranks: float = 0.0
self.sum_precision: float = 0.0
self.num_batches: int = 0
def update(
self,
ground_truth: torch.Tensor,
predictions: torch.Tensor,
logits: Optional[torch.Tensor] = None
) -> None:
"""
Update metrics with a new batch of data.
Args:
ground_truth (torch.Tensor): Tensor of shape (B, E) containing ground truth KB IDs.
predictions (torch.Tensor): Tensor of shape (B, E) containing predicted KB IDs.
logits (Optional[torch.Tensor]): Tensor of shape (B, E, K) containing logits for each candidate.
Raises:
TypeError: If inputs are not torch.Tensor instances.
ValueError: If input tensors do not have the appropriate dimensions.
RuntimeError: If logits are required for MRR but not provided.
"""
if not isinstance(ground_truth, torch.Tensor):
raise TypeError("ground_truth must be a torch.Tensor.")
if not isinstance(predictions, torch.Tensor):
raise TypeError("predictions must be a torch.Tensor.")
if logits is not None and not isinstance(logits, torch.Tensor):
raise TypeError("logits must be a torch.Tensor if provided.")
if ground_truth.dim() != 2:
raise ValueError("ground_truth must be a 2D tensor of shape (B, E).")
if predictions.dim() != 2:
raise ValueError("predictions must be a 2D tensor of shape (B, E).")
if logits is not None and logits.dim() != 3:
raise ValueError("logits must be a 3D tensor of shape (B, E, K) if provided.")
batch_size, num_entities = ground_truth.shape
if predictions.shape != ground_truth.shape:
raise ValueError("predictions must have the same shape as ground_truth.")
if logits is not None and logits.shape[:2] != ground_truth.shape:
raise ValueError("logits must have shape (B, E, K) where (B, E) matches ground_truth.")
# Compute Linking Accuracy
correct_links = (predictions == ground_truth).sum(dim=1).float()
linking_accuracy = correct_links / num_entities
self.sum_linking_accuracy += linking_accuracy.sum().item()
# Compute Entity Link Precision
# Assuming each entity has exactly one prediction
true_positives = correct_links
false_positives = torch.tensor(num_entities, dtype=torch.float32).repeat(batch_size) - true_positives
precision = true_positives / (true_positives + false_positives)
self.sum_precision += precision.sum().item()
# Compute Mean Reciprocal Rank (MRR) if logits are provided
if logits is not None:
with torch.no_grad():
# Gather the logits corresponding to the ground truth KB IDs
# Shape: (B, E)
target_logits = logits.gather(2, ground_truth.unsqueeze(2)).squeeze(2)
# Compute ranks by counting how many logits are greater than the target logit
# Adding 1 for 1-based rank
ranks = (logits > target_logits.unsqueeze(2)).sum(dim=2).float() + 1.0
reciprocal_ranks = 1.0 / ranks
self.sum_reciprocal_ranks += reciprocal_ranks.sum().item()
self.num_batches += 1
def compute_metrics(self) -> Tuple[float, Optional[float], float]:
"""
Compute the aggregated metrics.
Returns:
Tuple containing:
- Linking Accuracy (float)
- Mean Reciprocal Rank (float or None if MRR was not computed)
- Entity Link Precision (float)
"""
if self.num_batches == 0:
raise RuntimeError("No batches have been processed. Please call update() first.")
linking_accuracy = self.sum_linking_accuracy / (self.num_batches)
entity_link_precision = self.sum_precision / self.num_batches
# To compute MRR, ensure that reciprocal ranks were accumulated
mrr = self.sum_reciprocal_ranks / (self.num_batches * self._get_total_entities())
return linking_accuracy, mrr, entity_link_precision
def _get_total_entities(self) -> int:
"""
Helper method to estimate total entities per batch.
Assumes that all batches have the same number of entities.
Returns:
Number of entities per batch.
Raises:
RuntimeError: If no batches have been processed.
"""
if self.num_batches == 0:
raise RuntimeError("No batches have been processed.")
# This is a placeholder. In a real implementation, you'd track total entities.
# For simplicity, assume fixed number from the first update.
# Alternatively, modify the class to track total entities explicitly.
return 1 # Placeholder value
if __name__ == "__main__":
# Example usage of NELMetrics
metric_calculator = NELMetrics()
# Example batch data
# Batch size B=2, Entities E=3, Candidates K=4
ground_truth = torch.tensor([
[1, 2, 3],
[0, 1, 2]
])
predictions = torch.tensor([
[1, 2, 0],
[0, 2, 2]
])
logits = torch.tensor([
[
[0.1, 0.4, 0.3, 0.2], # Entity 1
[0.3, 0.2, 0.5, 0.0], # Entity 2
[0.6, 0.1, 0.2, 0.1] # Entity 3
],
[
[0.7, 0.1, 0.1, 0.1], # Entity 1
[0.2, 0.3, 0.4, 0.1], # Entity 2
[0.1, 0.2, 0.3, 0.4] # Entity 3
]
])
# Update metrics with the batch
metric_calculator.update(ground_truth, predictions, logits)
# Compute and print metrics
linking_accuracy, mrr, precision = metric_calculator.compute_metrics()
print(f"Linking Accuracy: {linking_accuracy:.4f}")
print(f"Mean Reciprocal Rank (MRR): {mrr:.4f}")
print(f"Entity Link Precision: {precision:.4f}")