Upload metrics.py with huggingface_hub
Browse files15 unmodified lines1617181920212235 unmodified lines5859606162635 unmodified lines6970717273747576777879149 unmodified lines229230231232233234390 unmodified lines625626627628629630631632633634635636637101 unmodified lines739740741742743744745746747748749750190 unmodified lines94194294394494594641 unmodified lines9889899909919929939942271 unmodified lines32663267326815 unmodified linesfrom scipy.stats._warnings_errors import DegenerateDataWarningfrom .artifact import Artifactfrom .dataclass import InternalField, OptionalFieldfrom .logging_utils import get_loggerfrom .metric_utils import InstanceInput, MetricRequest, MetricResponsefrom .operator import (35 unmodified linesreturn np.nanmean(x)class UpdateStream(StreamInstanceOperator):update: dict5 unmodified linesclass Metric(Artifact):@property@abstractmethoddef 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.149 unmodified lines[instance["score"]["instance"][score_name] for instance in instances])@staticmethoddef _all_instance_scores_equal(instances, score_name):instance_scores = [390 unmodified lines# if subgroup_column is not None, a column by the specified name will be required in task_datasubgroup_column = Noneimplemented_reductions: List[str] = field(default_factory=lambda: ["mean", "group_mean"])@property@abstractmethoddef reduction_map(self) -> dict:passdef _validate_group_mean_reduction(self, instances: List[dict]):"""Ensure that group_mean reduction_map is properly formatted.101 unmodified linesfield_name_full_prefix = ""# used for passing to the bootstrapping, depends on whether the groups are fixed or notaggregation_function = self.average_item_scoresif reduction_type == "mean":reduction_fields = list(set(reduction_params))# no group reduction, so resample instances individuallyscores_to_resample = instanceselif reduction_type == "group_mean":self._validate_group_mean_reduction(instances=instances)reduction_fields = ([self.main_score]190 unmodified linesreturn resultclass UnsortedListExactMatch(InstanceMetric):reduction_map = {"mean": ["unsorted_list_exact_match"]}main_score = "unsorted_list_exact_match"41 unmodified linesself.metric.disable_confidence_interval_calculation()def verify(self):assert self.main_score is not None, "main_score is not set"def prepare(self):super().prepare()2271 unmodified linesbest_thr = thrreturn {self.main_score: best_acc, "best_thr_max_acc": best_thr}15 unmodified lines1617181920212235 unmodified lines585960616263646566676869707172735 unmodified lines79808182838485149 unmodified lines235236237238239240241242243244245246247248249250251252390 unmodified lines643644645646647648649650651652101 unmodified lines754755756757758759760761762763764765766767768769770771772190 unmodified lines96396496596696796896997097197297397441 unmodified lines1016101710181019102010211022102310241025102610271028102910302271 unmodified lines33023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333115 unmodified linesfrom scipy.stats._warnings_errors import DegenerateDataWarningfrom .artifact import Artifactfrom .dataclass import AbstractField, InternalField, OptionalFieldfrom .logging_utils import get_loggerfrom .metric_utils import InstanceInput, MetricRequest, MetricResponsefrom .operator import (35 unmodified linesreturn np.nanmean(x)def nan_max(x):with warnings.catch_warnings():# final mean should be mean of scores, ignoring NaN, hence nanmax# but if the group function values is NaN for ALL values, nanmean throws a# RuntimeWarning that it is calculating the mean of an empty slice (with no non-Nans)# this is the desired behavior, but we want to avoid the warning herewarnings.simplefilter("ignore", category=RuntimeWarning)return np.nanmax(x)class UpdateStream(StreamInstanceOperator):update: dict5 unmodified linesclass Metric(Artifact):main_score: str = AbstractField()# 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.149 unmodified lines[instance["score"]["instance"][score_name] for instance in instances])@staticmethoddef max_item_scores(instances: List[dict], score_name: str):"""Calculate max of a set of instance scores (given by score_name), omitting NaN values.Args:instances: list of dicts of each instance's instance scores.score_name: score field names to compute the mean for."""return nan_max([instance["score"]["instance"][score_name] for instance in instances])@staticmethoddef _all_instance_scores_equal(instances, score_name):instance_scores = [390 unmodified lines# if subgroup_column is not None, a column by the specified name will be required in task_datasubgroup_column = Noneimplemented_reductions: List[str] = field(default_factory=lambda: ["mean", "group_mean", "max"])reduction_map: Dict[str, List[str]] = AbstractField()def _validate_group_mean_reduction(self, instances: List[dict]):"""Ensure that group_mean reduction_map is properly formatted.101 unmodified linesfield_name_full_prefix = ""# used for passing to the bootstrapping, depends on whether the groups are fixed or notaggregation_function = Noneif reduction_type == "mean":aggregation_function = self.average_item_scoresreduction_fields = list(set(reduction_params))# no group reduction, so resample instances individuallyscores_to_resample = instanceselif reduction_type == "max":aggregation_function = self.max_item_scoresreduction_fields = list(set(reduction_params))# no group reduction, so resample instances individuallyscores_to_resample = instanceselif reduction_type == "group_mean":aggregation_function = self.average_item_scoresself._validate_group_mean_reduction(instances=instances)reduction_fields = ([self.main_score]190 unmodified linesreturn resultclass MaxAccuracy(Accuracy):"""Calculate the maximal accuracy over all instances as the global score."""reduction_map = {"max": ["accuracy"]}class UnsortedListExactMatch(InstanceMetric):reduction_map = {"mean": ["unsorted_list_exact_match"]}main_score = "unsorted_list_exact_match"41 unmodified linesself.metric.disable_confidence_interval_calculation()def verify(self):assert (self.metric is not None), f"'metric' is not set in {self.get_metric_name()}"assert (self.main_score is not None), f"'main_score' is not set in {self.get_metric_name()}"assert isinstance(self.metric, Metric), f"'metric' is not set to a Metric class in {self.get_metric_name()} (type{self.metric})"def prepare(self):super().prepare()2271 unmodified linesbest_thr = thrreturn {self.main_score: best_acc, "best_thr_max_acc": best_thr}KO_ERROR_MESSAGE = """Additional dependencies required. To install them, run:`pip install "sacrebleu[ko]"`.For MacOS: If error on 'mecab-config' show up during installation ], one should run:`brew install mecab``pip install "sacrebleu[ko]"`"""class NormalizedSacrebleu(HuggingfaceMetric):hf_metric_name = "sacrebleu"hf_main_score = "score"prediction_type = "str"main_score = "sacrebleu"scale = 100.0scaled_fields = ["sacrebleu", "precisions"]hf_additional_input_fields_pass_one_value = ["tokenize"]_requirements_list = {"mecab_ko": KO_ERROR_MESSAGE,"mecab_ko_dic": KO_ERROR_MESSAGE,}
metrics.py+76-13