Upload metrics.py with huggingface_hub
Browse files15 unmodified lines161718191920212235 unmodified lines585960616263646566676869707172735 unmodified lines798081727374757682838485149 unmodified lines235236237238239240241242243244245246247248249250251252390 unmodified lines643644645628646647648631632633634649650651652101 unmodified lines754755756742757758759760761762763764765766767768769770771772190 unmodified lines96396496596696796896997097197297397441 unmodified lines1016101710189911019102010211022102310241025102610271028102910302271 unmodified lines33023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333115 unmodified linesfrom scipy.stats._warnings_errors import DegenerateDataWarning
from .artifact import Artifactfrom .dataclass import InternalField, OptionalFieldfrom .dataclass import AbstractField, InternalField, OptionalFieldfrom .logging_utils import get_loggerfrom .metric_utils import InstanceInput, MetricRequest, MetricResponsefrom .operator import (35 unmodified lines return 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 here warnings.simplefilter("ignore", category=RuntimeWarning) return np.nanmax(x)
class UpdateStream(StreamInstanceOperator): update: dict
5 unmodified lines
class Metric(Artifact): @property @abstractmethod def main_score(self): pass
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] )
@staticmethod def 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] )
@staticmethod def _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_data subgroup_column = None implemented_reductions: List[str] = field( default_factory=lambda: ["mean", "group_mean"] default_factory=lambda: ["mean", "group_mean", "max"] )
@property @abstractmethod def reduction_map(self) -> dict: pass 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 lines
field_name_full_prefix = "" # used for passing to the bootstrapping, depends on whether the groups are fixed or not aggregation_function = self.average_item_scores aggregation_function = None if reduction_type == "mean": aggregation_function = self.average_item_scores reduction_fields = list(set(reduction_params)) # no group reduction, so resample instances individually scores_to_resample = instances elif reduction_type == "max": aggregation_function = self.max_item_scores reduction_fields = list(set(reduction_params)) # no group reduction, so resample instances individually scores_to_resample = instances elif reduction_type == "group_mean": aggregation_function = self.average_item_scores self._validate_group_mean_reduction(instances=instances) reduction_fields = ( [self.main_score]190 unmodified lines return result
class 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 lines self.metric.disable_confidence_interval_calculation()
def verify(self): assert self.main_score is not None, "main_score is not set" 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 lines best_thr = thr
return {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.0 scaled_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