Upload metrics.py with huggingface_hub
Browse files123425 unmodified lines3031323334353638 unmodified lines757677787980254 unmodified lines33533633733833934044 unmodified lines38538638738838939068 unmodified lines459460461462463464465258 unmodified lines724725726727728729107 unmodified lines8378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778787 unmodified lines886887888889890891892893894895896108 unmodified lines100510061007100810091010101175 unmodified lines1087108810891090109110925 unmodified lines1098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112028 unmodified lines11491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117521 unmodified lines11971198119912001201120221 unmodified lines122412251226122712281229123036 unmodified lines1267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128934 unmodified lines13241325132613271328132931 unmodified lines1361136213631364136513664 unmodified lines13711372137313741375137613771378137913806 unmodified lines1387138813891390139113923 unmodified lines1396139713981399140014011402140314045 unmodified lines14101411141214131414141514161417141814191420142126 unmodified lines14481449145014511452145321 unmodified lines14751476147714781479148021 unmodified lines15021503150415051506150748 unmodified lines1556155715581559156015616 unmodified lines15681569157015711572157315741575157615771578157915801581158215831584158586 unmodified lines16721673167416751676167724 unmodified lines170217031704170517061707128 unmodified lines183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186014 unmodified lines18751876187718781879188018811882188358 unmodified lines194219431944194519461947194819 unmodified lines196819691970197119721973197419751976216 unmodified lines21932194219521962197219812 unmodified lines22112212221322142215221610 unmodified lines22272228222922302231223224 unmodified lines2257225822592260226122622263226422652266141 unmodified lines240824092410241124122413674 unmodified lines30883089309030913092309330941 unmodified line30963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831294 unmodified lines313431353136import itertoolsimport reimport stringimport uuid25 unmodified linesfrom .random_utils import get_seedfrom .settings_utils import get_settingsfrom .stream import MultiStream, Streamfrom .type_utils import isoftype, to_float_or_defaultlogger = get_logger()settings = get_settings()38 unmodified linesdef main_score(self):passdef consume_stream(self, stream: Stream):references = []predictions = []254 unmodified linesn_resamples: int = OptionalField(default_factory=lambda: settings.num_resamples_for_global_metrics)process_single_instances = Truedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:44 unmodified linesinstance_score[self.main_score] = no_score_valueinstance["score"]["instance"].update(instance_score)result = self._compute(references, predictions, task_data)68 unmodified linesinstance["task_data"] if "task_data" in instance else {}for instance in stream]# compute the metric over all refs and predsinstance_scores = self.compute(references=references,258 unmodified linesfor instance in stream:refs, pred = instance["references"], instance["prediction"]task_data = instance["task_data"] if "task_data" in instance else {}instance_score = self.compute(107 unmodified linespassclass Squad(GlobalMetric):_metric = Nonemain_score = "f1"metric = "squad"def prepare(self):super().prepare()self._metric = evaluate.load(self.metric)def compute(self,references: List[List[str]],predictions: List[str],task_data: List[Dict],) -> dict:ids = [str(uuid.uuid4()).replace("-", "") for _ in range(len(predictions))]formatted_predictions = [{"prediction_text": prediction, "id": ids[i]}for i, prediction in enumerate(predictions)]formatted_references = [{"answers": {"answer_start": [-1], "text": reference}, "id": ids[i]}for i, reference in enumerate(references)]return self._metric.compute(predictions=formatted_predictions,references=formatted_references,)class Accuracy(InstanceMetric):reduction_map = {"mean": ["accuracy"]}main_score = "accuracy"ci_scores = ["accuracy"]def compute(self, references: List[Any], prediction: Any, task_data: List[Dict]) -> dict:7 unmodified linesreturn resultclass StringContainment(InstanceMetric):reduction_map = {"mean": ["string_containment"]}main_score = "string_containment"ci_scores = ["string_containment"]def compute(self, references: List[Any], prediction: Any, task_data: List[Dict]) -> dict:108 unmodified linespassed_task_data[additional_input_field] = next(iter(values))# add check that all required fields in self.metrics are in passed_task_data print(passed_task_data)result = self.metric.compute(predictions=predictions,references=references,75 unmodified linesaverage = None # Report per class then aggregate by meanmetric = "f1"def prepare(self):super().prepare()self._metric = evaluate.load(self.metric)5 unmodified linesself.id_to_str[id] = strreturn self.str_to_id[str]def _labels_match_average_format(self, references: List[List[str]], predictions: List[str]):return Truedef compute(self,references: List[List[str]],predictions: List[str],task_data: List[Dict],) -> dict:assert all(len(reference) == 1 for reference in references), "Only a single reference per prediction is allowed in F1 metric"if not self._labels_match_average_format(references, predictions):return {self.main_score: np.nan}self.str_to_id = {}self.id_to_str = {}formatted_references = [28 unmodified linesclass F1Binary(F1):process_single_instances = Falsemain_score = "f1_binary"average = "binary"pos_classes = {"1", "1.0", "yes", "true"}def get_str_id(self, str):if str.lower() in self.pos_classes:return 1return 0# References and predictions must include up to 2 unique values, one of them in pos_classesdef _labels_match_average_format(self, references: List[List[str]], predictions: List[str]):classes = set(predictions + list(itertools.chain(*references)))n_classes = len(classes)if n_classes > 2:return Falseif n_classes == 2 and len(set(classes).difference(self.pos_classes)) == 0:return Falsereturn Trueclass RecallBinary(F1Binary):21 unmodified linesaverage = None # Report per class then aggregate by meanmetric = "f1"def prepare(self):super().prepare()self._metric = evaluate.load(self.metric, "multilabel")21 unmodified linesself.str_to_id = {}self.id_to_str = {}self._validate_references_and_prediction(references, predictions)references = [reference[0] for reference in references]labels = list({label for reference in references for label in reference})36 unmodified linesfinal_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"34 unmodified linesmain_score = "rougeL"scale = 1.0use_aggregator: bool = Truerouge_types: List[str] = ["rouge1", "rouge2", "rougeL", "rougeLsum"]31 unmodified linesreduction_map = {"mean": ["char_edit_dist_accuracy"]}main_score = "char_edit_dist_accuracy"ci_scores = ["char_edit_dist_accuracy"]_requirements_list: List[str] = ["editdistance"]4 unmodified linesself.eval = editdistance.evaldef compute(self, references, prediction: str, task_data: List[Dict]) -> dict:assert (len(references) == 1), f"Expected only one reference , but received: {references}"formatted_prediction = "".join(prediction.split())formatted_reference = "".join(references[0].split())max_length = max(len(formatted_reference), len(formatted_prediction))6 unmodified linesclass Wer(HuggingfaceMetric):hf_metric_name = "wer"main_score = "wer"_requirements_list: List[str] = ["jiwer"]3 unmodified linespredictions: List[str],task_data: List[Dict],) -> dict:assert all(len(reference) == 1 for reference in references), "Only single reference per prediction is allowed in wer metric"formatted_references = [reference[0] for reference in references]result = self.metric.compute(predictions=predictions, references=formatted_references5 unmodified lineshf_metric_name = "spearmanr"main_score = "spearmanr"process_single_instances = Falseclass KendallTauMetric(GlobalMetric):main_score = "kendalltau_b"variant = "b"process_single_instances = False_requirements_list: List[str] = ["scipy"]26 unmodified linesmain_score = "matthews_correlation"str_to_id: dict = InternalField(default_factory=dict)def get_str_id(self, str):if str not in self.str_to_id:id = len(self.str_to_id)21 unmodified linesmain_score = "roc_auc"process_single_instances = False_requirements_list: List[str] = ["sklearn"]def prepare(self):from sklearn import metrics21 unmodified linesclass CustomF1(GlobalMetric):main_score = "f1_micro"groups = Nonezero_division = 0.048 unmodified linesdef get_groups(self, elements, task_data):groups = set()for sublist, additional_input in zip(elements, task_data):for e in sublist:if self.should_ignore_element(e, additional_input):continue6 unmodified linespredictions: List[Any],task_data: 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 size ({len(references)}).")if self.groups is None:groups = self.get_groups(references, task_data)86 unmodified linesclass NER(CustomF1):def get_element_group(self, element, additional_input):return element[1]24 unmodified linesreduction_map = {"mean": ["f1", "precision", "recall"]}main_score = "f1"ci_scores = ["f1", "precision", "recall"]def compute(self, references: List[Any], prediction: Any, task_data: List[Dict]128 unmodified linesclass LlamaIndexCorrectness(InstanceMetric):"""LlamaIndex based metric class for evaluating correctness.Attributes:reduction_map (dict): A dictionary specifying the reduction method for the metric.main_score (str): The main score used for evaluation._requirements_list (List[str]): A list specifying any additional requirements for the metric.Methods:prepare(self): Initialization method for the metric.compute(self, references, predictions, additional_inputs): Method to compute the metric.Usage:metric = LlamaIndexCorrectnessMetric()scores = metric.compute(references, prediction, additional_inputs)"""model_name: str = ""main_score: str = ""reduction_map: Dict[str, List[str]] = Noneopenai_models: List[str] = ["gpt-3.5-turbo"]anthropic_models: List[14 unmodified linesReturns:Tuple[float, str]: A tuple containing the score as a float and the reasoning as a string."""score_str = eval_response.split("\n")[0]reasoning_str = "\n".join(eval_response.split("\n")[1:])score = float(score_str)reasoning = reasoning_str.lstrip("\n")return score, reasoning58 unmodified lines), f"Cannot run send data to remote APIs ({self.model_name}) when unitxt.settings.allow_passing_data_to_remote_api=False. Set UNITXT_ALLOW_PASSING_DATA_TO_REMOTE_API environment variable, if you want to allow this."query = task_data["question"]contexts = task_data["contexts"]per_reference_results = []for reference_response in references:19 unmodified linesmain_score = "perplexity"reduction_map = {"mean": ["perplexity"]}perplexity_prompt: strbatch_size: int = 32model_name: str216 unmodified linesreturn shifted_logits, shifted_labelsclass NDCG(GlobalMetric):"""Normalized Discounted Cumulative Gain: measures the quality of ranking with respect to ground truth ranking scores.12 unmodified linesmain_score = "nDCG"_requirements_list: List[str] = ["sklearn"]def prepare(self):from sklearn.metrics import ndcg_score10 unmodified linesfrom collections import defaultdictquery_to_predictions_and_references = defaultdict(lambda: [[], []])for reference, pred, inputs_dict in zip(references, predictions, task_data):query = inputs_dict.get("query")query_to_predictions_and_references[query][0].append(pred)24 unmodified linesclass RetrievalMetric(InstanceMetric):def compute(self, references: List[Any], prediction: Any, task_data: 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 starts141 unmodified linesclass KPA(CustomF1):def get_element_group(self, element, additional_input):return additional_input["keypoint"]674 unmodified linesclass BinaryMaxF1(F1Binary):main_score = "max_f1_binary"def compute(self,1 unmodified linepredictions: List[List[str]],task_data: List[Dict],) -> dict:assert all(len(reference) == 1 for reference in references), "Only a single reference per prediction is allowed in F1 metric"classes = set(itertools.chain(*references))n_clases = len(classes)assert len(classes) <= 2, "References of BinaryMaxF1 must be binary"pos_classes = classes.intersection(self.pos_classes)neg_classes = classes.difference(self.pos_classes)n_pos_classes = len(pos_classes)if n_clases == 2:assert (n_pos_classes == 1), "Only one positive class is allowed in BinaryMaxF1"pos_class = next(iter(pos_classes)) if n_pos_classes > 0 else "1.0"neg_class = next(iter(neg_classes)) if len(neg_classes) > 0 else "0.0"float_predictions = []for prediction in predictions:try:float_predictions.append(float(prediction))except Exception:float_predictions.append(0)best_thr = -1best_f1 = -1for thr in set(float_predictions):new_predictions = [pos_class if float_prediction >= thr else neg_classfor float_prediction in float_predictions]f1 = super().compute(references, new_predictions, task_data)[4 unmodified linesbest_thr = thrreturn {self.main_score: best_f1, "best_thr_maxf1": best_thr}12325 unmodified lines2930313233343538 unmodified lines7475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159254 unmodified lines41441541641741841942042144 unmodified lines46646746846947047147268 unmodified lines541542543544545546547258 unmodified lines806807808809810811812813107 unmodified lines9219229239249259269279289299309319329337 unmodified lines941942943944945946947948949950951952953954955956957958959960961962963964965966967968108 unmodified lines107710781079108010811082108375 unmodified lines1159116011611162116311641165116611675 unmodified lines11731174117511761177117811791180118111821183118428 unmodified lines1213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124121 unmodified lines12631264126512661267126812691270127121 unmodified lines12931294129512961297129836 unmodified lines13351336133713381339134034 unmodified lines13751376137713781379138013811382138331 unmodified lines141514161417141814191420142114224 unmodified lines1427142814291430143114326 unmodified lines143914401441144214431444144514463 unmodified lines1450145114521453145414555 unmodified lines14611462146314641465146614671468146914701471147214731474147514761477147814791480148126 unmodified lines15081509151015111512151315141515151621 unmodified lines1538153915401541154215431544154521 unmodified lines1567156815691570157115721573157448 unmodified lines162316241625162616271628162916306 unmodified lines163716381639164016411642164386 unmodified lines1730173117321733173417351736173724 unmodified lines17621763176417651766176717681769128 unmodified lines1898189919001901190219031904190519061907190814 unmodified lines192319241925192619271928192919301931193219331934193519361937193858 unmodified lines199719981999200020012002200320042005200619 unmodified lines202620272028202920302031203220332034216 unmodified lines225122522253225422552256225722582259226022612262226322642265226622672268226922702271227212 unmodified lines2285228622872288228922902291229210 unmodified lines230323042305230623072308230924 unmodified lines2334233523362337233823392340234123422343234423452346141 unmodified lines248824892490249124922493249424952496674 unmodified lines317131723173317431753176317731783179318031811 unmodified line31833184318531863187318831893190319131923193319431954 unmodified lines320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268import reimport stringimport uuid25 unmodified linesfrom .random_utils import get_seedfrom .settings_utils import get_settingsfrom .stream import MultiStream, Streamfrom .type_utils import isoftype, parse_type_string, to_float_or_defaultlogger = get_logger()settings = get_settings()38 unmodified linesdef main_score(self):pass# Override 'prediction_type' with the expected type of predictions# and references. Example: "List[str]", "List[Dict]"", "string".# If left with default None, a warning will be displayed.# In future versions of unitxt, this will be an error.prediction_type: str = None# Standard metrics can receive multiple references per predictions (in a list)# Some metrics support only a single reference per prediction (one element in the list)single_reference_per_prediction: bool = False# Used to store the parsed prediction type and avoid# parsing on every use_parsed_prediction_type = Nonedef _validate_references_and_prediction(self, references, predictions):if not isoftype(predictions, List[Any]):raise ValueError(f"Metric {self.get_metric_name()} should receive a list of predictions {self.get_metric_name()}. Received predictions of type {type(predictions)}: {predictions}")if not isoftype(references, List[Any]):raise ValueError(f"Metric {self.get_metric_name()} should receive a list of predictions. Received references of type {type(references)}: {references}")if len(references) != len(predictions):raise ValueError(f"references size ({len(references)})"f" doesn't mach predictions size ({len(references)}).")for reference in references:self._validate_reference(reference)for prediction in predictions:self._validate_prediction(prediction)def _validate_prediction(self, prediction):if not isoftype(prediction, self.get_prediction_type()):raise ValueError(f"Each prediction is expected to be of type '{self.prediction_type}' in {self.get_metric_name()} metric. Received prediction of type {type(prediction)}: {prediction}")def _validate_reference(self, reference):if not isoftype(reference, List[Any]):raise ValueError(f"Expecting a list of references for each prediction in {self.get_metric_name()} metric. Received reference of type {type(reference)}: {reference}")if self.single_reference_per_prediction and not len(reference) == 1:raise ValueError(f"Expecting a list with a single reference per prediction in {self.get_metric_name()} metric. Received a list with multiple references: {reference}")for ref in reference:if not isoftype(ref, self.get_prediction_type()):raise ValueError(f"Each reference is expected to be of type '{self.prediction_type}' in {self.get_metric_name()} metric. Received reference of type {type(ref)}: {ref}")def get_prediction_type(self):if self.prediction_type is None:logger.warning(f"{self.get_metric_name()} metric does not set the 'prediction_type' parameter so input type checking is not performed. Set the prediction type to the expected prediction type (e.g. 'str', 'List[str]', or 'Any'). In future version of unitxt this will raise an exception.")self._parsed_prediction_type = Anytry:if self._parsed_prediction_type is not None:return self._parsed_prediction_typeself._parsed_prediction_type = parse_type_string(self.prediction_type)except ValueError:raise ValueError("Could convert prediction type '{self.prediction_type}' in {self.get_metric_name()} to known type. To enable type checking for this prediction type, open unitxt issue with this message. Alternatively, set the metric's prediction_type to 'Any'") from Nonereturn self._parsed_prediction_typedef get_metric_name(self):if self.artifact_identifier is not None:return self.artifact_identifierreturn self.__class__.__name__def consume_stream(self, stream: Stream):references = []predictions = []254 unmodified linesn_resamples: int = OptionalField(default_factory=lambda: settings.num_resamples_for_global_metrics)# calculate scores for single instancesprocess_single_instances = Truedef process(self, stream: Stream, stream_name: Optional[str] = None) -> Generator:44 unmodified linesinstance_score[self.main_score] = no_score_valueinstance["score"]["instance"].update(instance_score)self._validate_references_and_prediction(references, predictions)result = self._compute(references, predictions, task_data)68 unmodified linesinstance["task_data"] if "task_data" in instance else {}for instance in stream]self._validate_references_and_prediction(references, predictions)# compute the metric over all refs and predsinstance_scores = self.compute(references=references,258 unmodified linesfor instance in stream:refs, pred = instance["references"], instance["prediction"]self._validate_prediction(pred)self._validate_reference(refs)task_data = instance["task_data"] if "task_data" in instance else {}instance_score = self.compute(107 unmodified linespassclass Accuracy(InstanceMetric):reduction_map = {"mean": ["accuracy"]}main_score = "accuracy"ci_scores = ["accuracy"]prediction_type = "Any" # string representation is compareddef compute(self, references: List[Any], prediction: Any, task_data: List[Dict]) -> dict:7 unmodified linesreturn resultclass UnsortedListExactMatch(InstanceMetric):reduction_map = {"mean": ["unsorted_list_exact_match"]}main_score = "unsorted_list_exact_match"ci_scores = ["unsorted_list_exact_match"]def compute(self, references: List[Any], prediction: Any, task_data: List[Dict]) -> dict:result = {self.main_score: float(sorted(prediction) == sorted(references[0]))}result["score"] = result[self.main_score]result["score_name"] = self.main_scorereturn resultclass StringContainment(InstanceMetric):reduction_map = {"mean": ["string_containment"]}main_score = "string_containment"ci_scores = ["string_containment"]prediction_type = "Any" # string representation is comparedsingle_reference_per_prediction = False # multiple references alloweddef compute(self, references: List[Any], prediction: Any, task_data: List[Dict]) -> dict:108 unmodified linespassed_task_data[additional_input_field] = next(iter(values))# add check that all required fields in self.metrics are in passed_task_dataresult = self.metric.compute(predictions=predictions,references=references,75 unmodified linesaverage = None # Report per class then aggregate by meanmetric = "f1"prediction_type = "str"single_reference_per_prediction = Truedef prepare(self):super().prepare()self._metric = evaluate.load(self.metric)5 unmodified linesself.id_to_str[id] = strreturn self.str_to_id[str]def compute(self,references: List[List[str]],predictions: List[str],task_data: List[Dict],) -> dict:self.str_to_id = {}self.id_to_str = {}formatted_references = [28 unmodified linesclass F1Binary(F1):"""Calculate f1 for a binary task, using 0.5 as the threshold in the case of float predictions."""process_single_instances = Falsemain_score = "f1_binary"average = "binary"pos_classes = {"1", "1.0", "yes", "true"}threshold = 0.5def get_str_id(self, str):return int(str)def compute(self,references: List[List[str]],predictions: List[str],task_data: List[Dict],) -> dict:predictions_floats = [to_float_or_default(p) for p in predictions]predictions = [str(int(p > self.threshold)) for p in predictions_floats]references = [["1"] if r[0].lower() in self.pos_classes else ["0"] for r in references]return super().compute(references, predictions, task_data)class RecallBinary(F1Binary):21 unmodified linesaverage = None # Report per class then aggregate by meanmetric = "f1"prediction_type = "List[str]"single_reference_per_prediction = Truedef prepare(self):super().prepare()self._metric = evaluate.load(self.metric, "multilabel")21 unmodified linesself.str_to_id = {}self.id_to_str = {}references = [reference[0] for reference in references]labels = list({label for reference in references for label in reference})36 unmodified linesfinal_result = {self.main_score: result[self.metric]}return final_resultclass PrecisionMacroMultiLabel(F1MultiLabel):main_score = "precision_macro"34 unmodified linesmain_score = "rougeL"scale = 1.0prediction_type = "str"single_reference_per_prediction = False # multiple references alloweduse_aggregator: bool = Truerouge_types: List[str] = ["rouge1", "rouge2", "rougeL", "rougeLsum"]31 unmodified linesreduction_map = {"mean": ["char_edit_dist_accuracy"]}main_score = "char_edit_dist_accuracy"ci_scores = ["char_edit_dist_accuracy"]prediction_type = "str"single_reference_per_prediction = True_requirements_list: List[str] = ["editdistance"]4 unmodified linesself.eval = editdistance.evaldef compute(self, references, prediction: str, task_data: List[Dict]) -> dict:formatted_prediction = "".join(prediction.split())formatted_reference = "".join(references[0].split())max_length = max(len(formatted_reference), len(formatted_prediction))6 unmodified linesclass Wer(HuggingfaceMetric):hf_metric_name = "wer"main_score = "wer"prediction_type = "str"single_reference_per_prediction = True_requirements_list: List[str] = ["jiwer"]3 unmodified linespredictions: List[str],task_data: List[Dict],) -> dict:formatted_references = [reference[0] for reference in references]result = self.metric.compute(predictions=predictions, references=formatted_references5 unmodified lineshf_metric_name = "spearmanr"main_score = "spearmanr"process_single_instances = Falseprediction_type = "float"# Spearmanr references are not listdef _validate_reference(self, reference):if not isoftype(reference, self.get_prediction_type()):raise ValueError(f"Each reference is expected to be of type '{self.prediction_type}' in {self.get_metric_name()} metric. Received prediction of type {type(reference)}: {reference}")class KendallTauMetric(GlobalMetric):main_score = "kendalltau_b"variant = "b"process_single_instances = Falseprediction_type = "str"_requirements_list: List[str] = ["scipy"]26 unmodified linesmain_score = "matthews_correlation"str_to_id: dict = InternalField(default_factory=dict)single_reference_per_prediction = Trueprediction_type = "str"def get_str_id(self, str):if str not in self.str_to_id:id = len(self.str_to_id)21 unmodified linesmain_score = "roc_auc"process_single_instances = False_requirements_list: List[str] = ["sklearn"]single_reference_per_prediction = Trueprediction_type = "str"def prepare(self):from sklearn import metrics21 unmodified linesclass CustomF1(GlobalMetric):main_score = "f1_micro"prediction_type = "Any"single_reference_per_prediction = Truegroups = Nonezero_division = 0.048 unmodified linesdef get_groups(self, elements, task_data):groups = set()for sublist, additional_input in zip(elements, task_data):if not isinstance(sublist, list):sublist = [sublist]for e in sublist:if self.should_ignore_element(e, additional_input):continue6 unmodified linespredictions: List[Any],task_data: List[Dict],) -> dict:references = [element[0] for element in references]if self.groups is None:groups = self.get_groups(references, task_data)86 unmodified linesclass NER(CustomF1):prediction_type = "List[Tuple[str,str]]"def get_element_group(self, element, additional_input):return element[1]24 unmodified linesreduction_map = {"mean": ["f1", "precision", "recall"]}main_score = "f1"ci_scores = ["f1", "precision", "recall"]single_reference_per_prediction = Falseprediction_type = "str"def compute(self, references: List[Any], prediction: Any, task_data: List[Dict]128 unmodified linesclass LlamaIndexCorrectness(InstanceMetric):"""LlamaIndex based metric class for evaluating correctness."""model_name: str = ""main_score: str = ""prediction_type: str = "str"reduction_map: Dict[str, List[str]] = Noneopenai_models: List[str] = ["gpt-3.5-turbo"]anthropic_models: List[14 unmodified linesReturns:Tuple[float, str]: A tuple containing the score as a float and the reasoning as a string."""import rematch = re.search(r"\b\d+\.\d+\b|\b\d+\b", eval_response)if match:score = float(match.group())else:raise Exception("could not parse judge response")reasoning_str = "\n".join(eval_response.split("\n")[1:])reasoning = reasoning_str.lstrip("\n")return score, reasoning58 unmodified lines), f"Cannot run send data to remote APIs ({self.model_name}) when unitxt.settings.allow_passing_data_to_remote_api=False. Set UNITXT_ALLOW_PASSING_DATA_TO_REMOTE_API environment variable, if you want to allow this."query = task_data["question"]contexts = Noneif "contexts" in task_data:contexts = task_data["contexts"]per_reference_results = []for reference_response in references:19 unmodified linesmain_score = "perplexity"reduction_map = {"mean": ["perplexity"]}prediction_type = "str"perplexity_prompt: strbatch_size: int = 32model_name: str216 unmodified linesreturn shifted_logits, shifted_labelsclass Squad(HuggingfaceMetric):hf_metric_name = "squad"main_score = "f1"scale = 100.0scaled_fields = ["f1", "exact_match"]prediction_type = "Dict[str,Any]"# Squad references are not list, but a dict that contain a field called 'answers/text'# which is the list of referencesdef _validate_reference(self, reference):if not isoftype(reference, self.get_prediction_type()):raise ValueError(f"Each reference is expected to be of type '{self.prediction_type}' in {self.get_metric_name()} metric. Received prediction of type {type(reference)}: {reference}")class NDCG(GlobalMetric):"""Normalized Discounted Cumulative Gain: measures the quality of ranking with respect to ground truth ranking scores.12 unmodified linesmain_score = "nDCG"_requirements_list: List[str] = ["sklearn"]single_reference_per_prediction = Trueprediction_type = "Optional[float]"def prepare(self):from sklearn.metrics import ndcg_score10 unmodified linesfrom collections import defaultdictquery_to_predictions_and_references = defaultdict(lambda: [[], []])references = [reference[0] for reference in references]for reference, pred, inputs_dict in zip(references, predictions, task_data):query = inputs_dict.get("query")query_to_predictions_and_references[query][0].append(pred)24 unmodified linesclass RetrievalMetric(InstanceMetric):prediction_type = "List[str]"single_reference_per_prediction = Truedef compute(self, references: List[Any], prediction: Any, task_data: Dict) -> dict:# digest inputpred_ids: List[Any] = predictionref_ids: List[Any] = list(dict.fromkeys(references[0]))# 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 starts141 unmodified linesclass KPA(CustomF1):prediction_type = "str"single_reference_per_prediction = Truedef get_element_group(self, element, additional_input):return additional_input["keypoint"]674 unmodified linesclass BinaryMaxF1(F1Binary):"""Calculate the maximal F1 and the decision threshold that achieves it for a binary task with float predictions."""main_score = "max_f1_binary"prediction_type = strsingle_reference_per_prediction = Truedef compute(self,1 unmodified linepredictions: List[List[str]],task_data: List[Dict],) -> dict:float_predictions = [to_float_or_default(p) for p in predictions]best_thr = -1best_f1 = -1for thr in set(float_predictions):new_predictions = ["1" if float_prediction >= thr else "0"for float_prediction in float_predictions]f1 = super().compute(references, new_predictions, task_data)[4 unmodified linesbest_thr = thrreturn {self.main_score: best_f1, "best_thr_maxf1": best_thr}class BinaryAccuracy(InstanceMetric):"""Calculate accuracy for a binary task, using 0.5 as the threshold in the case of float predictions."""reduction_map = {"mean": ["accuracy_binary"]}main_score = "accuracy_binary"ci_scores = ["accuracy_binary"]pos_classes = {"1", "1.0", "yes", "true"}threshold = 0.5prediction_type = "str"single_reference_per_prediction = Truedef compute(self, references: List[Any], prediction: Any, task_data: List[Dict]) -> dict:float_prediction = to_float_or_default(prediction)prediction = str(int(float_prediction > self.threshold))references = ["1"] if references[0].lower() in self.pos_classes else ["0"]result = {self.main_score: float([prediction] == references)}result["score"] = result[self.main_score]result["score_name"] = self.main_scorereturn resultclass BinaryMaxAccuracy(GlobalMetric):"""Calculate the maximal accuracy and the decision threshold that achieves it for a binary task with float predictions."""process_single_instances = Falsemain_score = "max_accuracy_binary"pos_classes = {"1", "1.0", "yes", "true"}prediction_type = "str"single_reference_per_prediction = Truedef compute(self,references: List[List[str]],predictions: List[List[str]],task_data: List[Dict],) -> dict:float_predictions = [to_float_or_default(p) for p in predictions]references = [["1"] if r[0].lower() in self.pos_classes else ["0"] for r in references]best_thr = -1best_acc = -1for thr in set(float_predictions):new_predictions = ["1" if float_prediction >= thr else "0"for float_prediction in float_predictions]acc = np.mean([[prediction] == referencefor prediction, reference in zip(new_predictions, references)])if acc > best_acc:best_acc = accbest_thr = thrreturn {self.main_score: best_acc, "best_thr_max_acc": best_thr}
metrics.py+273-141