tahamajs/Sysmem2_in_AI / ComputerAssignments /CA4_visual_question_answering /src /evaluation /metrics.py
tahamajs/Sysmem2_in_AI / ComputerAssignments /CA4_visual_question_answering /src /evaluation /metrics.py
| import torch | |
| import torch.nn.functional as F | |
| from typing import List, Dict, Tuple, Optional, Any | |
| import numpy as np | |
| from collections import Counter | |
| import re | |
| from ..utils.base_classes import BaseMetric, VQAOutput | |
| class AccuracyMetric(BaseMetric): | |
| def __init__(self): | |
| self.reset() | |
| def compute( | |
| self, predictions: List[str], ground_truths: List[str], confidences: List[float] | |
| ) -> Dict[str, float]: | |
| if len(predictions) != len(ground_truths): | |
| raise ValueError("Predictions and ground truths must have same length") | |
| correct = 0 | |
| total = len(predictions) | |
| for pred, gt in zip(predictions, ground_truths): | |
| if self._normalize_answer(pred) == self._normalize_answer(gt): | |
| correct += 1 | |
| accuracy = correct / total if total > 0 else 0.0 | |
| self.correct += correct | |
| self.total += total | |
| return {"accuracy": accuracy} | |
| def _normalize_answer(self, answer: str) -> str: | |
| answer = answer.lower().strip() | |
| answer = re.sub(r"[^\w\s]", "", answer) | |
| number_words = { | |
| "0": "zero", | |
| "1": "one", | |
| "2": "two", | |
| "3": "three", | |
| "4": "four", | |
| "5": "five", | |
| "6": "six", | |
| "7": "seven", | |
| "8": "eight", | |
| "9": "nine", | |
| } | |
| for digit, word in number_words.items(): | |
| answer = answer.replace(digit, word) | |
| return answer | |
| def reset(self): | |
| self.correct = 0 | |
| self.total = 0 | |
| def get_global_accuracy(self) -> float: | |
| return self.correct / self.total if self.total > 0 else 0.0 | |
| class VQAScoreMetric(BaseMetric): | |
| def __init__(self): | |
| self.reset() | |
| def compute( | |
| self, | |
| predictions: List[str], | |
| ground_truths: List[List[str]], | |
| confidences: List[float], | |
| ) -> Dict[str, float]: | |
| if len(predictions) != len(ground_truths): | |
| raise ValueError("Predictions and ground truths must have same length") | |
| total_score = 0.0 | |
| total_questions = len(predictions) | |
| for pred, gt_list in zip(predictions, ground_truths): | |
| question_score = self._compute_question_score(pred, gt_list) | |
| total_score += question_score | |
| vqa_score = total_score / total_questions if total_questions > 0 else 0.0 | |
| self.total_score += total_score | |
| self.total_questions += total_questions | |
| return {"vqa_score": vqa_score} | |
| def _compute_question_score( | |
| self, prediction: str, ground_truths: List[str] | |
| ) -> float: | |
| prediction = self._normalize_answer(prediction) | |
| correct_count = 0 | |
| for gt in ground_truths: | |
| if prediction == self._normalize_answer(gt): | |
| correct_count += 1 | |
| return correct_count / len(ground_truths) if ground_truths else 0.0 | |
| def _normalize_answer(self, answer: str) -> str: | |
| answer = answer.lower().strip() | |
| answer = re.sub(r"[^\w\s]", "", answer) | |
| number_words = { | |
| "0": "zero", | |
| "1": "one", | |
| "2": "two", | |
| "3": "three", | |
| "4": "four", | |
| "5": "five", | |
| "6": "six", | |
| "7": "seven", | |
| "8": "eight", | |
| "9": "nine", | |
| } | |
| for digit, word in number_words.items(): | |
| answer = answer.replace(digit, word) | |
| return answer | |
| def reset(self): | |
| self.total_score = 0.0 | |
| self.total_questions = 0 | |
| def get_global_vqa_score(self) -> float: | |
| return ( | |
| self.total_score / self.total_questions if self.total_questions > 0 else 0.0 | |
| ) | |
| class BLEUMetric(BaseMetric): | |
| def __init__(self, n_gram: int = 4): | |
| self.n_gram = n_gram | |
| self.reset() | |
| def compute( | |
| self, predictions: List[str], ground_truths: List[str], confidences: List[float] | |
| ) -> Dict[str, float]: | |
| if len(predictions) != len(ground_truths): | |
| raise ValueError("Predictions and ground truths must have same length") | |
| total_bleu = 0.0 | |
| total_samples = len(predictions) | |
| for pred, gt in zip(predictions, ground_truths): | |
| bleu_score = self._compute_bleu(pred, gt) | |
| total_bleu += bleu_score | |
| avg_bleu = total_bleu / total_samples if total_samples > 0 else 0.0 | |
| self.total_bleu += total_bleu | |
| self.total_samples += total_samples | |
| return {"bleu": avg_bleu} | |
| def _compute_bleu(self, prediction: str, ground_truth: str) -> float: | |
| pred_tokens = prediction.lower().split() | |
| gt_tokens = ground_truth.lower().split() | |
| if len(pred_tokens) == 0: | |
| return 0.0 | |
| precisions = [] | |
| for n in range(1, self.n_gram + 1): | |
| pred_ngrams = self._get_ngrams(pred_tokens, n) | |
| gt_ngrams = self._get_ngrams(gt_tokens, n) | |
| if len(pred_ngrams) == 0: | |
| precisions.append(0.0) | |
| continue | |
| common_ngrams = 0 | |
| for ngram in pred_ngrams: | |
| if ngram in gt_ngrams: | |
| common_ngrams += 1 | |
| precision = common_ngrams / len(pred_ngrams) | |
| precisions.append(precision) | |
| if all(p > 0 for p in precisions): | |
| bleu = np.exp(np.mean(np.log(precisions))) | |
| else: | |
| bleu = 0.0 | |
| if len(pred_tokens) < len(gt_tokens): | |
| bleu *= np.exp(1 - len(gt_tokens) / len(pred_tokens)) | |
| return bleu | |
| def _get_ngrams(self, tokens: List[str], n: int) -> List[Tuple[str, ...]]: | |
| ngrams = [] | |
| for i in range(len(tokens) - n + 1): | |
| ngrams.append(tuple(tokens[i : i + n])) | |
| return ngrams | |
| def reset(self): | |
| self.total_bleu = 0.0 | |
| self.total_samples = 0 | |
| def get_global_bleu(self) -> float: | |
| return self.total_bleu / self.total_samples if self.total_samples > 0 else 0.0 | |
| class ROUGEMetric(BaseMetric): | |
| def __init__(self, rouge_type: str = "rouge-l"): | |
| self.rouge_type = rouge_type | |
| self.reset() | |
| def compute( | |
| self, predictions: List[str], ground_truths: List[str], confidences: List[float] | |
| ) -> Dict[str, float]: | |
| if len(predictions) != len(ground_truths): | |
| raise ValueError("Predictions and ground truths must have same length") | |
| total_rouge = 0.0 | |
| total_samples = len(predictions) | |
| for pred, gt in zip(predictions, ground_truths): | |
| rouge_score = self._compute_rouge(pred, gt) | |
| total_rouge += rouge_score | |
| avg_rouge = total_rouge / total_samples if total_samples > 0 else 0.0 | |
| self.total_rouge += total_rouge | |
| self.total_samples += total_samples | |
| return {"rouge": avg_rouge} | |
| def _compute_rouge(self, prediction: str, ground_truth: str) -> float: | |
| pred_tokens = prediction.lower().split() | |
| gt_tokens = ground_truth.lower().split() | |
| if len(pred_tokens) == 0 or len(gt_tokens) == 0: | |
| return 0.0 | |
| if self.rouge_type == "rouge-l": | |
| return self._compute_rouge_l(pred_tokens, gt_tokens) | |
| else: | |
| return self._compute_rouge_1(pred_tokens, gt_tokens) | |
| def _compute_rouge_l(self, pred_tokens: List[str], gt_tokens: List[str]) -> float: | |
| lcs_length = self._lcs_length(pred_tokens, gt_tokens) | |
| precision = lcs_length / len(pred_tokens) if len(pred_tokens) > 0 else 0.0 | |
| recall = lcs_length / len(gt_tokens) if len(gt_tokens) > 0 else 0.0 | |
| if precision + recall > 0: | |
| f1 = 2 * precision * recall / (precision + recall) | |
| else: | |
| f1 = 0.0 | |
| return f1 | |
| def _compute_rouge_1(self, pred_tokens: List[str], gt_tokens: List[str]) -> float: | |
| pred_set = set(pred_tokens) | |
| gt_set = set(gt_tokens) | |
| overlap = len(pred_set.intersection(gt_set)) | |
| precision = overlap / len(pred_set) if len(pred_set) > 0 else 0.0 | |
| recall = overlap / len(gt_set) if len(gt_set) > 0 else 0.0 | |
| if precision + recall > 0: | |
| f1 = 2 * precision * recall / (precision + recall) | |
| else: | |
| f1 = 0.0 | |
| return f1 | |
| def _lcs_length(self, seq1: List[str], seq2: List[str]) -> int: | |
| m, n = len(seq1), len(seq2) | |
| dp = [[0] * (n + 1) for _ in range(m + 1)] | |
| for i in range(1, m + 1): | |
| for j in range(1, n + 1): | |
| if seq1[i - 1] == seq2[j - 1]: | |
| dp[i][j] = dp[i - 1][j - 1] + 1 | |
| else: | |
| dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) | |
| return dp[m][n] | |
| def reset(self): | |
| self.total_rouge = 0.0 | |
| self.total_samples = 0 | |
| def get_global_rouge(self) -> float: | |
| return self.total_rouge / self.total_samples if self.total_samples > 0 else 0.0 | |
| class F1Metric(BaseMetric): | |
| def __init__(self): | |
| self.reset() | |
| def compute( | |
| self, predictions: List[str], ground_truths: List[str], confidences: List[float] | |
| ) -> Dict[str, float]: | |
| if len(predictions) != len(ground_truths): | |
| raise ValueError("Predictions and ground truths must have same length") | |
| total_f1 = 0.0 | |
| total_samples = len(predictions) | |
| for pred, gt in zip(predictions, ground_truths): | |
| f1_score = self._compute_f1(pred, gt) | |
| total_f1 += f1_score | |
| avg_f1 = total_f1 / total_samples if total_samples > 0 else 0.0 | |
| self.total_f1 += total_f1 | |
| self.total_samples += total_samples | |
| return {"f1": avg_f1} | |
| def _compute_f1(self, prediction: str, ground_truth: str) -> float: | |
| pred_tokens = set(prediction.lower().split()) | |
| gt_tokens = set(ground_truth.lower().split()) | |
| if len(pred_tokens) == 0 and len(gt_tokens) == 0: | |
| return 1.0 | |
| if len(pred_tokens) == 0 or len(gt_tokens) == 0: | |
| return 0.0 | |
| overlap = len(pred_tokens.intersection(gt_tokens)) | |
| precision = overlap / len(pred_tokens) | |
| recall = overlap / len(gt_tokens) | |
| if precision + recall > 0: | |
| f1 = 2 * precision * recall / (precision + recall) | |
| else: | |
| f1 = 0.0 | |
| return f1 | |
| def reset(self): | |
| self.total_f1 = 0.0 | |
| self.total_samples = 0 | |
| def get_global_f1(self) -> float: | |
| return self.total_f1 / self.total_samples if self.total_samples > 0 else 0.0 | |
| class VQAEvaluator: | |
| def __init__(self, metrics: List[str] = None): | |
| if metrics is None: | |
| metrics = ["accuracy", "vqa_score", "bleu", "rouge", "f1"] | |
| self.metrics = {} | |
| if "accuracy" in metrics: | |
| self.metrics["accuracy"] = AccuracyMetric() | |
| if "vqa_score" in metrics: | |
| self.metrics["vqa_score"] = VQAScoreMetric() | |
| if "bleu" in metrics: | |
| self.metrics["bleu"] = BLEUMetric() | |
| if "rouge" in metrics: | |
| self.metrics["rouge"] = ROUGEMetric() | |
| if "f1" in metrics: | |
| self.metrics["f1"] = F1Metric() | |
| def evaluate( | |
| self, | |
| predictions: List[str], | |
| ground_truths: List[str], | |
| confidences: List[float] = None, | |
| ) -> Dict[str, float]: | |
| if confidences is None: | |
| confidences = [1.0] * len(predictions) | |
| results = {} | |
| for metric_name, metric in self.metrics.items(): | |
| if metric_name == "vqa_score": | |
| gt_list = [[gt] for gt in ground_truths] | |
| metric_results = metric.compute(predictions, gt_list, confidences) | |
| else: | |
| metric_results = metric.compute(predictions, ground_truths, confidences) | |
| results.update(metric_results) | |
| return results | |
| def reset(self): | |
| for metric in self.metrics.values(): | |
| metric.reset() | |
| def get_global_results(self) -> Dict[str, float]: | |
| results = {} | |
| for metric_name, metric in self.metrics.items(): | |
| if hasattr(metric, "get_global_accuracy"): | |
| results[f"global_{metric_name}"] = metric.get_global_accuracy() | |
| elif hasattr(metric, "get_global_vqa_score"): | |
| results[f"global_{metric_name}"] = metric.get_global_vqa_score() | |
| elif hasattr(metric, "get_global_bleu"): | |
| results[f"global_{metric_name}"] = metric.get_global_bleu() | |
| elif hasattr(metric, "get_global_rouge"): | |
| results[f"global_{metric_name}"] = metric.get_global_rouge() | |
| elif hasattr(metric, "get_global_f1"): | |
| results[f"global_{metric_name}"] = metric.get_global_f1() | |
| return results | |
| def demonstrate_evaluation(): | |
| print("=== نمایش سیستم ارزیابی VQA ===") | |
| evaluator = VQAEvaluator() | |
| predictions = ["red", "three", "yes", "walking", "on the ground"] | |
| ground_truths = ["red", "3", "yes", "walking", "on the ground"] | |
| confidences = [0.9, 0.8, 0.95, 0.7, 0.85] | |
| results = evaluator.evaluate(predictions, ground_truths, confidences) | |
| print(f"\nنتایج ارزیابی:") | |
| for metric, score in results.items(): | |
| print(f" {metric}: {score:.4f}") | |
| print(f"\nارزیابی با دادههای مختلف:") | |
| predictions2 = [ | |
| "blue", | |
| "two", | |
| "no", | |
| "running", | |
| "in the air", | |
| ] | |
| results2 = evaluator.evaluate(predictions2, ground_truths, confidences) | |
| for metric, score in results2.items(): | |
| print(f" {metric}: {score:.4f}") | |
| global_results = evaluator.get_global_results() | |
| print(f"\nنتایج کلی:") | |
| for metric, score in global_results.items(): | |
| print(f" {metric}: {score:.4f}") | |
| if __name__ == "__main__": | |
| demonstrate_evaluation() | |
Xet Storage Details
- Size:
- 13.8 kB
- Xet hash:
- 922e071912de0c5df2c73f2b3337f11a0f7b535bd816d0adfa9681bc071435a2
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.