| | import torch |
| | import torch.nn.functional as F |
| | import numpy as np |
| | from typing import List, Tuple, Union, Protocol, Callable |
| | from abc import ABC, abstractmethod |
| |
|
| |
|
| | class ElementSimilarity(Protocol): |
| | """Protocol for computing similarity between two elements""" |
| | def __call__(self, x: any, y: any) -> float: |
| | ... |
| |
|
| |
|
| | class SetSimilarity: |
| | """Calculate similarity metrics between two sets based on element-wise similarity""" |
| | |
| | def __init__(self, element_similarity: ElementSimilarity): |
| | self.element_similarity = element_similarity |
| | |
| | def compute_similarity_matrix(self, pred_set: List, gt_set: List) -> np.ndarray: |
| | """Compute pairwise similarity matrix between elements of two sets""" |
| | return np.array([ |
| | [self.element_similarity(pred, gt) for gt in gt_set] |
| | for pred in pred_set |
| | ]) |
| | |
| | def __call__(self, pred_set: List, gt_set: List) -> Tuple[float, float, float]: |
| | """Compute precision, recall, and F1 between two sets""" |
| | if not pred_set or not gt_set: |
| | return 0.0, 0.0, 0.0 |
| | |
| | |
| | sim_matrix = self.compute_similarity_matrix(pred_set, gt_set) |
| | |
| | pred_max_sim = np.max(sim_matrix, axis=1) |
| | precision = np.mean(pred_max_sim) |
| | |
| | |
| | match_threshold = 1 |
| | total_matches = np.sum(pred_max_sim >= match_threshold) |
| | |
| | |
| | if total_matches > len(gt_set): |
| | precision *= len(gt_set) / total_matches |
| | |
| | |
| | recall = np.mean(np.max(sim_matrix, axis=0)) |
| | |
| | |
| | f1 = 2 * precision * recall / (precision + recall) if precision + recall > 0 else 0.0 |
| | |
| | return precision, recall, f1 |
| |
|
| |
|
| | class TimestampSimilarity: |
| | """Compute similarity between two timestamps""" |
| | |
| | def __init__(self, threshold: float = 5.0): |
| | self.threshold = threshold |
| | |
| | def __call__(self, t1: float, t2: float) -> float: |
| | """Return 1 if timestamps are within threshold, 0 otherwise""" |
| | return float(abs(t1 - t2) <= self.threshold) |
| |
|
| |
|
| | class SSIMSimilarity: |
| | """Compute SSIM similarity between two images. |
| | Assumes input images are in range [0, 255].""" |
| | |
| | def __init__(self, window_size: int = 11): |
| | self.window_size = window_size |
| | self._window_cache = {} |
| | self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| | |
| | self.C1 = (0.01 * 255) ** 2 |
| | self.C2 = (0.03 * 255) ** 2 |
| | |
| | def _create_window(self, channel: int) -> torch.Tensor: |
| | """Create a 2D Gaussian window""" |
| | kernel_1d = self._gaussian_kernel() |
| | window_2d = kernel_1d.unsqueeze(1) @ kernel_1d.unsqueeze(0) |
| | return window_2d.expand(channel, 1, self.window_size, self.window_size) |
| | |
| | def _gaussian_kernel(self, sigma: float = 1.5) -> torch.Tensor: |
| | """Generate 1D Gaussian kernel""" |
| | coords = torch.arange(self.window_size, dtype=torch.float32) |
| | coords = coords - (self.window_size - 1) / 2 |
| | kernel = torch.exp(-(coords ** 2) / (2 * sigma ** 2)) |
| | return kernel / kernel.sum() |
| | |
| | def __call__(self, img1: torch.Tensor, img2: torch.Tensor) -> float: |
| | """Compute SSIM between two images in range [0, 255]""" |
| | if img1.shape != img2.shape: |
| | raise ValueError("Images must have the same shape") |
| | |
| | |
| | img1 = img1.to(self.device) |
| | img2 = img2.to(self.device) |
| | |
| | if img1.dim() == 3: |
| | img1 = img1.unsqueeze(0) |
| | img2 = img2.unsqueeze(0) |
| | |
| | channel = img1.size(1) |
| | if channel not in self._window_cache: |
| | self._window_cache[channel] = self._create_window(channel).to(self.device) |
| | window = self._window_cache[channel] |
| | |
| | |
| | mu1 = F.conv2d(img1, window, padding=self.window_size//2, groups=channel) |
| | mu2 = F.conv2d(img2, window, padding=self.window_size//2, groups=channel) |
| | mu1_sq, mu2_sq = mu1 ** 2, mu2 ** 2 |
| | mu1_mu2 = mu1 * mu2 |
| | |
| | |
| | sigma1_sq = F.conv2d(img1 ** 2, window, padding=self.window_size//2, groups=channel) - mu1_sq |
| | sigma2_sq = F.conv2d(img2 ** 2, window, padding=self.window_size//2, groups=channel) - mu2_sq |
| | sigma12 = F.conv2d(img1 * img2, window, padding=self.window_size//2, groups=channel) - mu1_mu2 |
| | |
| | |
| | ssim = ((2 * mu1_mu2 + self.C1) * (2 * sigma12 + self.C2)) / \ |
| | ((mu1_sq + mu2_sq + self.C1) * (sigma1_sq + sigma2_sq + self.C2)) |
| | |
| | |
| | return float(ssim.mean()) |
| |
|
| |
|
| | class BatchEvaluator: |
| | """Evaluate similarity metrics for a batch of set pairs""" |
| | |
| | def __init__(self, set_similarity: SetSimilarity): |
| | self.set_similarity = set_similarity |
| | |
| | def __call__(self, pred_sets: List[List], gt_sets: List[List]) -> Tuple[float, float, float]: |
| | """Compute average precision, recall, and F1 across all set pairs""" |
| | if len(pred_sets) != len(gt_sets): |
| | raise ValueError("Number of predicted and ground truth sets must match") |
| | |
| | metrics = [ |
| | self.set_similarity(pred_set, gt_set) |
| | for pred_set, gt_set in zip(pred_sets, gt_sets) |
| | ] |
| | |
| | avg_precision = np.mean([p for p, _, _ in metrics]) |
| | avg_recall = np.mean([r for _, r, _ in metrics]) |
| | avg_f1 = np.mean([f for _, _, f in metrics]) |
| | |
| | return avg_precision, avg_recall, avg_f1 |
| |
|
| |
|
| | |
| | def main(): |
| | |
| | timestamp_sim = TimestampSimilarity(threshold=5.0) |
| | set_sim = SetSimilarity(timestamp_sim) |
| | |
| | |
| | gt_set = [10.0, 20.0] |
| | pred_set = [9.0, 9.5, 10.2, 10.8, 19.8] |
| | |
| | p, r, f1 = set_sim(pred_set, gt_set) |
| | print(f"Timestamp Metrics with penalty:") |
| | print(f"P: {p:.3f}, R: {r:.3f}, F1: {f1:.3f}") |
| | |
| | |
| | batch_eval = BatchEvaluator(set_sim) |
| | pred_sets = [ |
| | [9.0, 9.5, 10.2, 19.8], |
| | [15.0, 25.0, 25.2] |
| | ] |
| | gt_sets = [ |
| | [10.0, 20.0], |
| | [15.0, 25.0] |
| | ] |
| | p, r, f1 = batch_eval(pred_sets, gt_sets) |
| | print(f"\nBatch Metrics:") |
| | print(f"P: {p:.3f}, R: {r:.3f}, F1: {f1:.3f}") |
| | |
| | |
| | |
| | |
| | ssim_sim = SSIMSimilarity() |
| | set_sim_images = SetSimilarity(ssim_sim) |
| | batch_eval_images = BatchEvaluator(set_sim_images) |
| | |
| | |
| | img1 = (torch.randn(3, 64, 64) * 255).to(torch.uint8).float() |
| | img2 = (torch.randn(3, 64, 64) * 255).to(torch.uint8).float() |
| | pred_sets = [[img1, img2]] |
| | gt_sets = [[img2]] |
| | |
| | p, r, f1 = batch_eval_images(pred_sets, gt_sets) |
| | print(f"Image Metrics - P: {p:.3f}, R: {r:.3f}, F1: {f1:.3f}") |
| |
|
| |
|
| | if __name__ == "__main__": |
| | main() |