Upload metrics.py with huggingface_hub
Browse files12349 unmodified lines1415161718193 unmodified lines2324252627282931 unmodified lines61626364656612 unmodified lines798081828384858 unmodified lines94959697989931 unmodified lines131132133134135136137203 unmodified lines34134234334434534634763 unmodified lines41141241341441541641755 unmodified lines47347447547647747833 unmodified lines5125135145155165175185195206 unmodified lines52752852953053153253353424 unmodified lines5595605615625635645 unmodified lines57057157257357457557657778 unmodified lines65665765865966066166266366466517 unmodified lines68368468568668768868969069169269369469569669769869970070170270370427 unmodified lines732733734735736737738739740741742743744745746747748749750117 unmodified lines86886987087187287387487587687787887988088188288388488588688788888989089189289389415 unmodified lines91091191291391491591691791891992092192292392492592692792892993093193293393493593693793893936 unmodified lines97697797897998098198212 unmodified lines9959969979989991000100111 unmodified lines101310141015101610171018101910201021102219 unmodified lines10421043104410451046104727 unmodified lines107510761077107810791080142 unmodified lines122312241225import loggingimport reimport stringimport uuid9 unmodified linesfrom .artifact import Artifactfrom .dataclass import InternalField, OptionalFieldfrom .operator import (MultiStreamOperator,SingleStreamOperator,3 unmodified linesfrom .operators import CopyFieldsfrom .random_utils import get_seedfrom .stream import MultiStream, Stream# The default number of resamples used to estimate the confidence intervals# global and instances metrics. Use None to disable confidence interval computation by default._N_RESAMPLES_DEFAULT_FOR_INSTANCE_METRICS = 100031 unmodified lines# Use None to disable confidence interval computation.n_resamples: int = Noneconfidence_level: float = 0.95@staticmethoddef new_random_generator():12 unmodified linesand num_predictions > 1)def score_based_confidence_interval(self, score_names: List[str], instances):"""Compute confidence intervals based on existing scores, already computed on the input instances.score_names: List[str]8 unmodified linesif not self._can_compute_confidence_intervals(num_predictions=len(instances)):return resultfor score_name in score_names:scores = [instance["score"]["instance"][score_name] for instance in instances31 unmodified linesexcept Exception as e:# this happens in edge cases, for example, when the sampling creates a# sample where all strings are empty and this fails bleu.logging.info(f"Warning in {self.__class__.__name__}", e)return np.nanscores = numpy.apply_along_axis(203 unmodified linesglobal_score["score_name"] = self.main_scoreconfidence_interval = self.score_based_confidence_interval(score_names=[self.main_score], instances=instances)global_score.update(confidence_interval)63 unmodified linesglobal_score["score_name"] = self.main_scoreconfidence_interval = self.score_based_confidence_interval(score_names=[self.main_score], instances=instances)global_score.update(confidence_interval)55 unmodified linesreturn resultclass MetricPipeline(MultiStreamOperator, Metric):main_score: str = Nonepreprocess_steps: Optional[List[StreamingOperator]] = field(default_factory=list)33 unmodified linesscale: float = 1.0 # optional scaling of main resultsscaled_fields: list = Nonehf_compute_args: Dict[str, Any] = OptionalField(default_factory=dict)experiment_id: str = OptionalField(default_factory=lambda: str(uuid.uuid4()))def prepare(self):super().prepare()self.metric = evaluate.load(6 unmodified linespredictions: List[Any],additional_inputs: List[Dict],) -> dict:result = self.metric.compute(predictions=predictions, references=references, **self.hf_compute_args)if self.hf_main_score:result[self.main_score] = result[self.hf_main_score]24 unmodified lineshf_metric_fields: List[str]hf_compute_args: dict = {}def prepare(self):super().prepare()5 unmodified linespredictions: List[str],additional_inputs: List[Any],) -> List[Dict[str, Any]]:scores = self.metric.compute(predictions=predictions, references=references, **self.hf_compute_args)# convert dict of lists to a list of dicts78 unmodified linesmain_score = "f1_macro"average = None # Report per class then aggregate by meanclasses_to_ignore = ["none"]def prepare(self):super().prepare()self._metric = evaluate.load("f1", "multilabel")def add_str_to_id(self, str):if str not in self.str_to_id:17 unmodified lines) -> dict:self.str_to_id = {}self.id_to_str = {}assert all(len(reference) == 1 for reference in references), "Only a single reference per prediction is allowed in F1 multi label metric"references = [reference[0] for reference in references]for reference in references:assert isinstance(references, list), f"Each reference is expected to list of strings in F1 multi label metric. Received reference: {reference}"for prediction in predictions:assert isinstance(prediction, list), f"Each prediction is expected to list of strings in F1 multi label metric. Received prediction: {prediction}"labels = [lblfor lbl in {label for reference in references for label in reference}27 unmodified linesaverage=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]else:final_result = {self.main_score: result["f1"]}return final_resultclass F1MicroMultiLabel(F1MultiLabel):main_score = "f1_micro"117 unmodified linesclass CustomF1(GlobalMetric):main_score = "f1_micro"classes = Nonezero_division = 0.0@abstractmethoddef get_element_group(self, element):pass@abstractmethoddef get_element_representation(self, element):passdef group_elements(self, elements_list):return {k: Counter([self.get_element_representation(value)for value in elements_listif self.get_element_group(value) == k])for k in {self.get_element_group(e) for e in elements_list}}def calculate_groups_ratio(self, actual_group, total_group):15 unmodified linesexcept ZeroDivisionError:return self.zero_divisiondef compute(self,references: List[Any],predictions: List[Any],additional_inputs: List[Dict],) -> dict:# in case reference are List[List[List[Any]]] and predictions are List[List[Any]]:if isinstance(references[0], list) and isinstance(references[0][0], list):references = [element[0] for element in references]assert len(references) == len(predictions), (f"references size ({len(references)})"f" doesn't mach predictions sise ({len(references)}).")if self.classes is None:classes = {self.get_element_group(e) for sublist in references for e in sublist}else:classes = self.classesgroups_statistics = {}for references_batch, predictions_batch in zip(references, predictions):grouped_references = self.group_elements(references_batch)grouped_predictions = self.group_elements(predictions_batch)all_groups = set(grouped_references.keys()).union(grouped_predictions.keys())36 unmodified linesrn_total + rn,rd_total + rd,)if group in classes:f1_result[f"f1_{group}"] = self.f1(pn, pd, rn, rd)recall_result[f"recall_{group}"] = self.recall(pn, pd, rn, rd)precision_result[f"precision_{group}"] = self.precision(pn, pd, rn, rd)12 unmodified linesexcept ZeroDivisionError:result["f1_macro"] = self.zero_divisionresult["recall_macro"] = self.zero_divisionresult["micro_macro"] = self.zero_divisionamount_of_predictions = pd_totalif amount_of_predictions == 0:11 unmodified linesclass NER(CustomF1):def get_element_group(self, element):return element[1]def get_element_representation(self, element):return str(element)19 unmodified linesclass TokenOverlap(InstanceMetric):reduction_map = {"mean": ["f1", "precision", "recall"]}main_score = "f1"def compute(self, references: List[Any], prediction: Any, additional_inputs: List[Dict]27 unmodified linesmain_score = "f1"reduction_map = {"mean": ["f1", "precision", "recall"]}hf_metric_fields = ["f1", "precision", "recall"]model_name: strdef prepare(self):142 unmodified lines]scores.append(self.eval([q_references], [q_predictions]))return {self.main_score: mean(scores) if len(scores) > 0 else np.nan}1239 unmodified lines131415161718193 unmodified lines23242526272829303131 unmodified lines6364656667686912 unmodified lines828384858687888 unmodified lines97989910010110210310410510631 unmodified lines138139140141142143144203 unmodified lines34834935035135235335463 unmodified lines41841942042142242342455 unmodified lines48048148248348448548648748848949049149249349449549649749849950050150233 unmodified lines5365375385395405415425435445455465475485495505515525535545555565575585595605615625635646 unmodified lines57157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560624 unmodified lines6316326336346356366375 unmodified lines64364464564664764864965065165265365465565665765865966066166266366466578 unmodified lines74474574674774874975075175275375417 unmodified lines77277377477577677777877978078127 unmodified lines809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868117 unmodified lines986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102115 unmodified lines103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108236 unmodified lines111911201121112211231124112512 unmodified lines113811391140114111421143114411 unmodified lines115611571158115911601161116211631164116519 unmodified lines118511861187118811891190119127 unmodified lines1219122012211222122312241225142 unmodified lines136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532import reimport stringimport uuid9 unmodified linesfrom .artifact import Artifactfrom .dataclass import InternalField, OptionalFieldfrom .logging_utils import get_loggerfrom .operator import (MultiStreamOperator,SingleStreamOperator,3 unmodified linesfrom .operators import CopyFieldsfrom .random_utils import get_seedfrom .stream import MultiStream, Streamfrom .type_utils import isoftypelogger = get_logger()# The default number of resamples used to estimate the confidence intervals# global and instances metrics. Use None to disable confidence interval computation by default._N_RESAMPLES_DEFAULT_FOR_INSTANCE_METRICS = 100031 unmodified lines# Use None to disable confidence interval computation.n_resamples: int = Noneconfidence_level: float = 0.95ci_scores: List[str] = None@staticmethoddef new_random_generator():12 unmodified linesand num_predictions > 1)def score_based_confidence_interval(self, instances):"""Compute confidence intervals based on existing scores, already computed on the input instances.score_names: List[str]8 unmodified linesif not self._can_compute_confidence_intervals(num_predictions=len(instances)):return resultscore_names = (self.ci_scores if self.ci_scores is not None else [self.main_score])for score_name in score_names:scores = [instance["score"]["instance"][score_name] for instance in instances31 unmodified linesexcept Exception as e:# this happens in edge cases, for example, when the sampling creates a# sample where all strings are empty and this fails bleu.logger.info(f"Warning in {self.__class__.__name__}", e)return np.nanscores = numpy.apply_along_axis(203 unmodified linesglobal_score["score_name"] = self.main_scoreconfidence_interval = self.score_based_confidence_interval(instances=instances)global_score.update(confidence_interval)63 unmodified linesglobal_score["score_name"] = self.main_scoreconfidence_interval = self.score_based_confidence_interval(instances=instances)global_score.update(confidence_interval)55 unmodified linesreturn resultclass StringContainment(InstanceMetric):reduction_map = {"mean": ["string_containment"]}main_score = "string_containment"def compute(self, references: List[Any], prediction: Any, additional_inputs: List[Dict]) -> dict:result = {self.main_score: float(any(str(reference) in prediction for reference in references))}result["score"] = result[self.main_score]result["score_name"] = self.main_scorereturn resultclass MetricPipeline(MultiStreamOperator, Metric):main_score: str = Nonepreprocess_steps: Optional[List[StreamingOperator]] = field(default_factory=list)33 unmodified linesscale: float = 1.0 # optional scaling of main resultsscaled_fields: list = None# This are fixed arguments passed to compute methodhf_compute_args: Dict[str, Any] = OptionalField(default_factory=dict)# These are additional input fields passed to HF compute method (a list with one value per instance)hf_additional_input_fields: List = OptionalField(default_factory=list)# These are additional input fields that are passed as one valuehf_additional_input_fields_pass_one_value: List = OptionalField(default_factory=list)experiment_id: str = OptionalField(default_factory=lambda: str(uuid.uuid4()))def verify(self):assert (self.hf_additional_input_fields is Noneor isoftype(self.hf_additional_input_fields, List[str])), f"Argument hf_additional_input_fields should be either None or List[str]. It is now: {self.hf_additional_input_fields}."assert (self.hf_additional_input_fields_pass_one_value is Noneor isoftype(self.hf_additional_input_fields_pass_one_value, List[str])), f"Argument hf_additional_input_fields_pass_one_value should be either None or List[str]. It is now: {self.hf_additional_input_fields_pass_one_value}."return super().verify()def prepare(self):super().prepare()self.metric = evaluate.load(6 unmodified linespredictions: List[Any],additional_inputs: List[Dict],) -> dict:passed_additional_inputs = {}for additional_input_field in self.hf_additional_input_fields:assert (additional_input_field in additional_inputs[0]), f"'{additional_input_field}' field required by {__class__.__name__} is not in passed in additional inputs: {additional_inputs[0]}"passed_additional_inputs[additional_input_field] = [additional_input[additional_input_field]for additional_input in additional_inputs]for additional_input_field in self.hf_additional_input_fields_pass_one_value:assert (additional_input_field in additional_inputs[0]), f"'{additional_input_field}' field required by {__class__.__name__} is not in passed in additional inputs: {additional_inputs[0]}"values = {additional_input[additional_input_field]for additional_input in additional_inputs}assert (len(values) == 1), f"Values of '{additional_input_field}' field required by {__class__.__name__} should all be the same, but have multiple values {values}"passed_additional_inputs[additional_input_field] = next(iter(values))# add check that all required fields in self.metrics are in passed_additional_inputs print(passed_additional_inputs)result = self.metric.compute(predictions=predictions,references=references,**passed_additional_inputs,**self.hf_compute_args,)if self.hf_main_score:result[self.main_score] = result[self.hf_main_score]24 unmodified lineshf_metric_fields: List[str]hf_compute_args: dict = {}hf_additional_input_fields: List = OptionalField(default_factory=list)def prepare(self):super().prepare()5 unmodified linespredictions: List[str],additional_inputs: List[Any],) -> List[Dict[str, Any]]:passed_additional_inputs = {}passed_additional_inputs = {}for additional_input_field in self.hf_additional_input_fields:assert (additional_input_field in additional_inputs[0]), f"'{additional_input_field}' field required by {__class__.__name__} is not in passed in additional inputs: {additional_inputs[0]}"passed_additional_inputs[additional_input_field] = [additional_input[additional_input_field]for additional_input in additional_inputs]# add check that all required fields in self.metrics are in passed_additional_inputsscores = self.metric.compute(predictions=predictions,references=references,**passed_additional_inputs,**self.hf_compute_args,)# convert dict of lists to a list of dicts78 unmodified linesmain_score = "f1_macro"average = None # Report per class then aggregate by meanclasses_to_ignore = ["none"]metric = "f1"def prepare(self):super().prepare()self._metric = evaluate.load(self.metric, "multilabel")def add_str_to_id(self, str):if str not in self.str_to_id:17 unmodified lines) -> dict:self.str_to_id = {}self.id_to_str = {}self._validate_references_and_prediction(references, predictions)references = [reference[0] for reference in references]labels = [lblfor lbl in {label for reference in references for label in reference}27 unmodified linesaverage=self.average,labels=labels_param,)if isinstance(result[self.metric], numpy.ndarray):from statistics import meanassert (len(result[self.metric]) == len(labels)), f"F1 result ({result[self.metric]}) has more entries than labels ({labels})"final_result = {self.main_score: mean(result[self.metric])}for i, label in enumerate(labels):final_result[self.metric + "_" + label] = result[self.metric][i]else:final_result = {self.main_score: result[self.metric]}return final_resultdef _validate_references_and_prediction(self, references, predictions):for reference in references:if not len(reference) == 1:raise ValueError(f"Only a single reference per prediction is allowed in F1 multi label metric. Received reference: {reference}")if not isoftype(reference[0], List[str]):raise ValueError(f"Each reference is expected to be a list of strings in F1 multi label metric. Received reference: '{reference[0]}'")for prediction in predictions:if not isoftype(prediction, List[str]):raise ValueError(f"Each prediction is expected to be a list of strings in F1 multi label metric. Received prediction: '{prediction}'")class PrecisionMacroMultiLabel(F1MultiLabel):main_score = "precision_macro"metric = "precision"average = "macro"class PrecisionMicroMultiLabel(F1MultiLabel):main_score = "precision_micro"metric = "precision"average = "micro"class RecallMacroMultiLabel(F1MultiLabel):main_score = "recall_macro"metric = "recall"average = "macro"class RecallMicroMultiLabel(F1MultiLabel):main_score = "recall_micro"metric = "recall"average = "micro"class F1MicroMultiLabel(F1MultiLabel):main_score = "f1_micro"117 unmodified linesclass CustomF1(GlobalMetric):main_score = "f1_micro"groups = Nonezero_division = 0.0@abstractmethoddef get_element_group(self, element, additional_input):pass@abstractmethoddef get_element_representation(self, element, additional_input):passdef should_ignore_element(self, element, additional_input):return Falsedef group_elements(self, elements_list, additional_input):if not isinstance(elements_list, list):elements_list = [elements_list]return {k: Counter([self.get_element_representation(value, additional_input)for value in elements_listif self.get_element_group(value, additional_input) == k])for k in {self.get_element_group(e, additional_input)for e in elements_listif not self.should_ignore_element(e, additional_input)}}def calculate_groups_ratio(self, actual_group, total_group):15 unmodified linesexcept ZeroDivisionError:return self.zero_divisiondef get_groups(self, elements, additional_inputs):groups = set()for sublist, additional_input in zip(elements, additional_inputs):for e in sublist:if self.should_ignore_element(e, additional_input):continuegroups.add(self.get_element_group(e, additional_input))return groupsdef compute(self,references: List[List[Any]],predictions: List[Any],additional_inputs: List[Dict],) -> dict:# in case reference are List[List[List[Any]]] and predictions are List[List[Any]]:if (isinstance(references[0], list)and len(references[0]) > 0and isinstance(references[0][0], list)):references = [element[0] for element in references]assert len(references) == len(predictions), (f"references size ({len(references)})"f" doesn't mach predictions sise ({len(references)}).")if self.groups is None:groups = self.get_groups(references, additional_inputs)else:groups = self.groupsgroups_statistics = {}for references_batch, predictions_batch, additional_input in zip(references, predictions, additional_inputs):grouped_references = self.group_elements(references_batch, additional_input)grouped_predictions = self.group_elements(predictions_batch, additional_input)all_groups = set(grouped_references.keys()).union(grouped_predictions.keys())36 unmodified linesrn_total + rn,rd_total + rd,)if group in groups:f1_result[f"f1_{group}"] = self.f1(pn, pd, rn, rd)recall_result[f"recall_{group}"] = self.recall(pn, pd, rn, rd)precision_result[f"precision_{group}"] = self.precision(pn, pd, rn, rd)12 unmodified linesexcept ZeroDivisionError:result["f1_macro"] = self.zero_divisionresult["recall_macro"] = self.zero_divisionresult["precision_macro"] = self.zero_divisionamount_of_predictions = pd_totalif amount_of_predictions == 0:11 unmodified linesclass NER(CustomF1):def get_element_group(self, element, additional_input):return element[1]def get_element_representation(self, element, additional_input):return str(element)19 unmodified linesclass TokenOverlap(InstanceMetric):reduction_map = {"mean": ["f1", "precision", "recall"]}main_score = "f1"ci_scores = ["f1", "precision", "recall"]def compute(self, references: List[Any], prediction: Any, additional_inputs: List[Dict]27 unmodified linesmain_score = "f1"reduction_map = {"mean": ["f1", "precision", "recall"]}hf_metric_fields = ["f1", "precision", "recall"]ci_scores = ["f1", "precision", "recall"]model_name: strdef prepare(self):142 unmodified lines]scores.append(self.eval([q_references], [q_predictions]))return {self.main_score: mean(scores) if len(scores) > 0 else np.nan}class RetrievalMetric(InstanceMetric):def compute(self, references: List[Any], prediction: Any, additional_inputs: Dict) -> dict:# digest inputpred_ids: List[Any] = predictionref_ids: List[Any] = list(dict.fromkeys(references))# relevance_at_k: 1-based dictionary of indicators (0/1), telling whether# the doc id retrieved at position k (assuming it is 1-based, so k starts# from 1) is in the gold doc ids or not.# For example, assuming that in the retrieved docs we have correct predictions# at positions 2, 4 and 5 (1-based), the dict will look like:# {1: 0, 2: 1, 3: 0, 4: 1, 5: 1, ...}relevance_at_k = {k + 1: 1 if doc_id in ref_ids else 0 for k, doc_id in enumerate(pred_ids)}# relevance_sum_at_k: 1-based dictionary of counts, where the value at k determines# how many gold doc ids have been observed up to index k.relevance_sum_at_k = {}for k, value in relevance_at_k.items():relevance_sum_at_k[k] = relevance_sum_at_k.get(k - 1, 0) + value# precision_at_k: the precision of the top k retrieved documents. For example,# assuming that only 1 out of the first 4 retrieved documents is correct, the# value at 4 will be 1/4.precision_at_k = {k: value / k for k, value in relevance_sum_at_k.items()}# recall_at_k: the recall of the top k retrieved documents. For example,# assuming that only 2 out of the 3 gold documents are in the top 5 results,# the value at 5 will be 2/3.n_refs = len(ref_ids)recall_at_k = {k: value / n_refs if n_refs > 0 else 0for k, value in relevance_sum_at_k.items()}# rank - the 1-based index of the first hit of a gold doc id. So 1# means first position.rank = 0for k, relevance in relevance_at_k.items():if relevance == 1:rank = kbreak# match_at_k: whether we have a match at the top k retrieved documentsmatch_at_k = {k: 1.0 if value > 0 else 0.0 for k, value in relevance_sum_at_k.items()}return self._compute(relevance_at_k,relevance_sum_at_k,precision_at_k,recall_at_k,match_at_k,rank,)@abstractmethoddef _compute(self,relevance_at_k,relevance_sum_at_k,precision_at_k,recall_at_k,match_at_k,rank,) -> dict:passclass MRR(RetrievalMetric):reduction_map = {"mean": ["mrr"]}main_score = "mrr"def _compute(self,relevance_at_k,relevance_sum_at_k,precision_at_k,recall_at_k,match_at_k,rank,) -> dict:return {self.main_score: 1 / rank if rank > 0 else 0}class MAP(RetrievalMetric):reduction_map = {"mean": ["map"]}main_score = "map"def _compute(self,relevance_at_k,relevance_sum_at_k,precision_at_k,recall_at_k,match_at_k,rank,) -> dict:result = 0if len(relevance_at_k) > 0:total = sum(relevance_at_k.values())if total > 0:dot = sum(relevance_at_k[k] * precision_at_k[k] for k in relevance_at_k)result = dot / totalreturn {self.main_score: result}class RetrievalAtK(RetrievalMetric):k_list: List[int]main_score: str = Nonereduction_map: Dict[str, List[str]] = Nonedef prepare(self):super().prepare()self.main_score = self.score_name("match", self.k_list[0])self.ci_scores = [self.score_name(measure, k)for measure in ["precision", "recall", "match"]for k in self.k_list]self.reduction_map = {"mean": self.ci_scores}@staticmethoddef score_name(measure: str, k: int):return f"{measure}_at_{k}"def _compute(self,relevance_at_k,relevance_sum_at_k,precision_at_k,recall_at_k,match_at_k,rank,) -> dict:result = {}for measure_array, measure_name in [(precision_at_k, "precision"),(recall_at_k, "recall"),(match_at_k, "match"),]:max_k = max(measure_array.keys())for k in self.k_list:result[self.score_name(measure_name, k)] = measure_array[min(k, max_k)]return resultclass KPA(CustomF1):def get_element_group(self, element, additional_input):return additional_input["keypoint"]def get_element_representation(self, element, additional_input):return additional_input["keypoint"]def should_ignore_element(self, element, additional_input):return element == "none"
metrics.py+356-49