Upload metrics.py with huggingface_hub
Browse files4 unmodified lines56789101112135 unmodified lines192021222324252638 unmodified lines6566676869707114 unmodified lines86878889909139 unmodified lines1311321331341351361 unmodified line1381391401411421433 unmodified lines14714814915015115215318 unmodified lines172173174175176177110 unmodified lines28828929029129229320 unmodified lines31431531631731831932032132232332432532632732832933017 unmodified lines3483493503513523533543553563573583593603613623633643653663673683693703714 unmodified linesfrom typing import Any, Dict, Generator, List, Optionalimport evaluateimport nltkimport numpyfrom editdistance import evalfrom .dataclass import InternalFieldfrom .operator import (5 unmodified linesfrom .operators import CopyFieldsfrom .stream import MultiStream, Streamnltk.download("punkt")def abstract_factory():return {}38 unmodified linestry:instance_score = self._compute([refs], [pred])except:instance_score = {"score": None}if isinstance(self.main_score, str) and self.main_score is not None:instance_score[self.main_score] = None14 unmodified linesdef _compute(self, references: List[List[str]], predictions: List[str]) -> dict:result = self.compute(references, predictions)result["score"] = result[self.main_score]return result@abstractmethod39 unmodified linesglobal_score[field] = mean([instance["score"]["instance"][field] for instance in instances])if field == self.main_score:global_score["score"] = global_score[field]for instance in instances:yield instance1 unmodified linedef _compute(self, references: List[List[str]], predictions: List[str]) -> dict:result = self.compute(references=references, predictions=predictions)result["score"] = result[self.main_score]return result@abstractmethod3 unmodified linesclass Squad(GlobalMetric):_metric = Nonereduction_map = {"mean": ["f1"]}main_score = "f1"metric = "squad"18 unmodified linesdef _compute(self, references: List[str], prediction: str) -> dict:result = self.compute(references[0], prediction)result["score"] = result[self.main_score]return result@abstractmethod110 unmodified lines_metric = Nonemain_score = "f1_macro"average = None # Report per class then aggregate by meandef prepare(self):super(F1MultiLabel, self).prepare()20 unmodified lineslen(reference) == 1 for reference in references), "Only a single reference per prediction is allowed in F1 metric"references = [reference[0] for reference in references]labels = list(set([label for reference in references for label in reference]))for label in labels:self.add_str_to_id(label)formatted_references = [self.get_one_hot_vector(reference) for reference in references]formatted_predictions = [self.get_one_hot_vector(prediction) for prediction in predictions]result = self._metric.compute(predictions=formatted_predictions, references=formatted_references, average=self.average)if isinstance(result["f1"], numpy.ndarray):from statistics import meanfinal_result = {self.main_score: mean(result["f1"])}for i, label in enumerate(labels):final_result["f1_" + label] = result["f1"][i]17 unmodified linesmain_score = "rougeL"scale = 1.0def compute(self, references, predictions):predictions = ["\n".join(nltk.sent_tokenize(prediction.strip())) for prediction in predictions]references = [["\n".join(nltk.sent_tokenize(r.strip())) for r in reference] for reference in references]return super().compute(references, predictions)# Computes chat edit distance, ignoring repeating whitespaceclass CharEditDistanceAccuracy(SingleReferenceInstanceMetric):reduction_map = {"mean": ["char_edit_dist_accuracy"]}main_score = "char_edit_dist_accuracy"def compute(self, reference, prediction: str) -> dict:formatted_prediction = " ".join(prediction.split())formatted_reference = " ".join(reference.split())max_length = max(len(formatted_reference), len(formatted_prediction))if max_length == 0:return 0edit_dist = eval(formatted_reference, formatted_prediction)return {"char_edit_dist_accuracy": (1 - edit_dist / max_length)}4 unmodified lines5678910115 unmodified lines17181920212238 unmodified lines616263646566676814 unmodified lines8384858687888939 unmodified lines1291301311321331341351 unmodified line1371381391401411421433 unmodified lines14714814915015115218 unmodified lines171172173174175176177110 unmodified lines28828929029129229329420 unmodified lines31531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435517 unmodified lines3733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084 unmodified linesfrom typing import Any, Dict, Generator, List, Optionalimport evaluateimport numpyfrom .dataclass import InternalFieldfrom .operator import (5 unmodified linesfrom .operators import CopyFieldsfrom .stream import MultiStream, Streamdef abstract_factory():return {}38 unmodified linestry:instance_score = self._compute([refs], [pred])except:instance_score = {"score": None, "score_name": self.main_score}if isinstance(self.main_score, str) and self.main_score is not None:instance_score[self.main_score] = None14 unmodified linesdef _compute(self, references: List[List[str]], predictions: List[str]) -> dict:result = self.compute(references, predictions)result["score"] = result[self.main_score]result["score_name"] = self.main_scorereturn result@abstractmethod39 unmodified linesglobal_score[field] = mean([instance["score"]["instance"][field] for instance in instances])if field == self.main_score:global_score["score"] = global_score[field]global_score["score_name"] = self.main_scorefor instance in instances:yield instance1 unmodified linedef _compute(self, references: List[List[str]], predictions: List[str]) -> dict:result = self.compute(references=references, predictions=predictions)result["score"] = result[self.main_score]result["score_name"] = self.main_scorereturn result@abstractmethod3 unmodified linesclass Squad(GlobalMetric):_metric = Nonemain_score = "f1"metric = "squad"18 unmodified linesdef _compute(self, references: List[str], prediction: str) -> dict:result = self.compute(references[0], prediction)result["score"] = result[self.main_score]result["score_name"] = self.main_scorereturn result@abstractmethod110 unmodified lines_metric = Nonemain_score = "f1_macro"average = None # Report per class then aggregate by meanclasses_to_ignore = ["none"]def prepare(self):super(F1MultiLabel, self).prepare()20 unmodified lineslen(reference) == 1 for reference in references), "Only a single reference per prediction is allowed in F1 metric"references = [reference[0] for reference in references]labels = [lfor l in set([label for reference in references for label in reference])if l not in self.classes_to_ignore]# if no classes are left then F1 is not defined# (e.g. only "none" in references)if len(labels) == 0:return {self.main_score: float("nan")}for label in labels:self.add_str_to_id(label)formatted_references = [self.get_one_hot_vector(reference) for reference in references]formatted_predictions = [self.get_one_hot_vector(prediction) for prediction in predictions]# There is odd behavior in scikit-learn that when passing a one-hot vector with a single# element, it is treated a class identifier. Therefore, we add labels=[1] to limit to only# to this class.if len(labels) == 1:labels_param = [1]else:labels_param = Noneresult = self._metric.compute(predictions=formatted_predictions,references=formatted_references,average=self.average,labels=labels_param,)if isinstance(result["f1"], numpy.ndarray):from statistics import meanassert len(result["f1"]) == len(labels), f'F1 result ({result["f1"]}) has more entries than labels ({labels})'final_result = {self.main_score: mean(result["f1"])}for i, label in enumerate(labels):final_result["f1_" + label] = result["f1"][i]17 unmodified linesmain_score = "rougeL"scale = 1.0def prepare(self):super().prepare()import nltknltk.download("punkt")self.sent_tokenize = nltk.sent_tokenizedef compute(self, references, predictions):predictions = ["\n".join(self.sent_tokenize(prediction.strip())) for prediction in predictions]references = [["\n".join(self.sent_tokenize(r.strip())) for r in reference] for reference in references]return super().compute(references, predictions)# Computes chat edit distance, ignoring whitespaceclass CharEditDistanceAccuracy(SingleReferenceInstanceMetric):reduction_map = {"mean": ["char_edit_dist_accuracy"]}main_score = "char_edit_dist_accuracy"def prepare(self):import editdistanceself.eval = editdistance.evaldef compute(self, reference, prediction: str) -> dict:formatted_prediction = "".join(prediction.split())formatted_reference = "".join(reference.split())max_length = max(len(formatted_reference), len(formatted_prediction))if max_length == 0:return 0edit_dist = self.eval(formatted_reference, formatted_prediction)return {"char_edit_dist_accuracy": (1 - edit_dist / max_length)}
metrics.py+51-14