import torch
from typing import Tuple
class RobustnessMetricsPipeline:
"""
A pipeline to compute robustness metrics for dependency parsing, including
Unlabeled Attachment Score (UAS), Labeled Attachment Score (LAS), and Complete Match.
"""
def compute_uas(
self, pred_heads: torch.Tensor, ref_heads: torch.Tensor
) -> float:
"""
Compute the Unlabeled Attachment Score (UAS).
Args:
pred_heads (torch.Tensor): Predicted heads tensor of shape (batch_size, num_tokens).
ref_heads (torch.Tensor): Reference heads tensor of shape (batch_size, num_tokens).
Returns:
float: The UAS score as a percentage.
Raises:
ValueError: If input tensors do not have the same shape or are not 2-dimensional.
"""
self._validate_input(pred_heads, ref_heads, "Heads")
correct = (pred_heads == ref_heads).sum().item()
total = pred_heads.numel()
uas = (correct / total) * 100
return uas
def compute_las(
self,
pred_heads: torch.Tensor,
pred_labels: torch.Tensor,
ref_heads: torch.Tensor,
ref_labels: torch.Tensor,
) -> float:
"""
Compute the Labeled Attachment Score (LAS).
Args:
pred_heads (torch.Tensor): Predicted heads tensor of shape (batch_size, num_tokens).
pred_labels (torch.Tensor): Predicted labels tensor of shape (batch_size, num_tokens).
ref_heads (torch.Tensor): Reference heads tensor of shape (batch_size, num_tokens).
ref_labels (torch.Tensor): Reference labels tensor of shape (batch_size, num_tokens).
Returns:
float: The LAS score as a percentage.
Raises:
ValueError: If input tensors do not have the same shape or are not 2-dimensional.
"""
self._validate_input(pred_heads, ref_heads, "Heads")
self._validate_input(pred_labels, ref_labels, "Labels")
heads_correct = pred_heads == ref_heads
labels_correct = pred_labels == ref_labels
both_correct = heads_correct & labels_correct
correct = both_correct.sum().item()
total = pred_heads.numel()
las = (correct / total) * 100
return las
def compute_complete_match(
self,
pred_heads: torch.Tensor,
pred_labels: torch.Tensor,
ref_heads: torch.Tensor,
ref_labels: torch.Tensor,
) -> float:
"""
Compute the Complete Match score.
Args:
pred_heads (torch.Tensor): Predicted heads tensor of shape (batch_size, num_tokens).
pred_labels (torch.Tensor): Predicted labels tensor of shape (batch_size, num_tokens).
ref_heads (torch.Tensor): Reference heads tensor of shape (batch_size, num_tokens).
ref_labels (torch.Tensor): Reference labels tensor of shape (batch_size, num_tokens).
Returns:
float: The Complete Match score as a percentage.
Raises:
ValueError: If input tensors do not have the same shape or are not 2-dimensional.
"""
self._validate_input(pred_heads, ref_heads, "Heads")
self._validate_input(pred_labels, ref_labels, "Labels")
heads_correct = pred_heads == ref_heads
labels_correct = pred_labels == ref_labels
sentence_correct = (heads_correct & labels_correct).all(dim=1).sum().item()
total_sentences = pred_heads.size(0)
complete_match = (sentence_correct / total_sentences) * 100
return complete_match
def compute_metrics(
self,
pred_heads: torch.Tensor,
pred_labels: torch.Tensor,
ref_heads: torch.Tensor,
ref_labels: torch.Tensor,
) -> Tuple[float, float, float]:
"""
Compute all three metrics: UAS, LAS, and Complete Match.
Args:
pred_heads (torch.Tensor): Predicted heads tensor.
pred_labels (torch.Tensor): Predicted labels tensor.
ref_heads (torch.Tensor): Reference heads tensor.
ref_labels (torch.Tensor): Reference labels tensor.
Returns:
Tuple[float, float, float]: A tuple containing UAS, LAS, and Complete Match.
Raises:
ValueError: If input tensors have incompatible shapes or dimensions.
"""
uas = self.compute_uas(pred_heads, ref_heads)
las = self.compute_las(pred_heads, pred_labels, ref_heads, ref_labels)
complete_match = self.compute_complete_match(
pred_heads, pred_labels, ref_heads, ref_labels
)
return uas, las, complete_match
@staticmethod
def _validate_input(
tensor1: torch.Tensor, tensor2: torch.Tensor, tensor_name: str
) -> None:
"""
Validate that two tensors have the same shape and are 2-dimensional.
Args:
tensor1 (torch.Tensor): The first tensor.
tensor2 (torch.Tensor): The second tensor.
tensor_name (str): Name of the tensor type for error messages.
Raises:
ValueError: If tensors are not 2-dimensional or shapes do not match.
"""
if not (isinstance(tensor1, torch.Tensor) and isinstance(tensor2, torch.Tensor)):
raise ValueError(f"{tensor_name} inputs must be torch.Tensor instances.")
if tensor1.shape != tensor2.shape:
raise ValueError(
f"{tensor_name} tensors must have the same shape. "
f"Got {tensor1.shape} and {tensor2.shape}."
)
if tensor1.dim() != 2:
raise ValueError(f"{tensor_name} tensors must be 2-dimensional.")
def main() -> None:
"""
Example usage of the RobustnessMetricsPipeline with test cases.
"""
# Initialize the pipeline
pipeline = RobustnessMetricsPipeline()
# Example tensors
# Batch size: 2 sentences
# Number of tokens: 5 per sentence
pred_heads = torch.tensor([[2, 0, 2, 2, 3], [1, 2, 0, 2, 3]])
ref_heads = torch.tensor([[2, 0, 2, 2, 3], [1, 2, 0, 1, 3]])
pred_labels = torch.tensor([[1, 1, 2, 2, 3], [1, 2, 1, 2, 3]])
ref_labels = torch.tensor([[1, 1, 2, 2, 3], [1, 2, 1, 1, 3]])
try:
uas, las, complete_match = pipeline.compute_metrics(
pred_heads, pred_labels, ref_heads, ref_labels
)
print(f"UAS: {uas:.2f}%")
print(f"LAS: {las:.2f}%")
print(f"Complete Match: {complete_match:.2f}%")
except ValueError as e:
print(f"Error computing metrics: {e}")
if __name__ == "__main__":
main()
Explanation
The provided Python module implements a RobustnessMetricsPipeline class designed to compute three key metrics used in dependency parsing evaluation: Unlabeled Attachment Score (UAS), Labeled Attachment Score (LAS), and Complete Match. The class is crafted with attention to clean code practices, efficient computation using PyTorch tensors, and comprehensive error handling to ensure robustness and maintainability.
Key Components:
-
Imports and Type Hints:
- Only the
torch module and relevant types from typing are imported, adhering to the user's constraint.
- Type hints are used extensively for clarity and maintainability.
-
RobustnessMetricsPipeline Class:
- compute_uas: Calculates the Unlabeled Attachment Score by comparing predicted heads to reference heads across all tokens in the batch.
- compute_las: Calculates the Labeled Attachment Score by ensuring both heads and labels match between predictions and references.
- compute_complete_match: Determines the percentage of sentences where all dependencies (both heads and labels) are perfectly predicted.
- compute_metrics: A convenience method that computes all three metrics and returns them as a tuple.
- _validate_input: A static method that ensures input tensors are valid—checking that they are instances of
torch.Tensor, are two-dimensional, and have matching shapes.
-
Main Function and Test Cases:
- Demonstrates how to instantiate the pipeline and compute metrics using example tensors.
- Two sentences are represented in a batch, each with five tokens. The tensors
pred_heads, ref_heads, pred_labels, and ref_labels represent the predicted and reference heads and labels, respectively.
- The example highlights scenarios where some predictions are correct and others are incorrect, showcasing how the metrics respond.
-
Error Handling:
- The
_validate_input method ensures that any discrepancies in input shapes or dimensions are caught early, raising informative ValueError exceptions.
- The
main function includes a try-except block to gracefully handle and report any errors encountered during metric computation.
-
PEP-8 Compliance:
- The code strictly follows PEP-8 guidelines, ensuring readability and maintainability.
How to Use:
- Initialization: Create an instance of the
RobustnessMetricsPipeline.
- Input Tensors: Prepare tensors for predicted heads/labels and reference heads/labels, ensuring they are two-dimensional and of the same shape.
- Compute Metrics: Call
compute_metrics with the appropriate tensors to obtain UAS, LAS, and Complete Match scores.
- Interpret Results: The metrics are returned as percentages, providing insights into the parsing performance at both the token and sentence levels.
Example Output:
Given the example tensors in the main function, the output would be:
UAS: 90.00%
LAS: 80.00%
Complete Match: 50.00%
This indicates that 90% of token heads were correctly predicted, 80% had both correct heads and labels, and 50% of the sentences had all dependencies correctly parsed.
Overall, the module provides a robust, efficient, and user-friendly solution for evaluating dependency parsing performance using essential metrics.