Upload operators.py with huggingface_hub
Browse files179 unmodified lines18018118218318418518698 unmodified lines28528628728828929029144 unmodified lines33633733833934034134222 unmodified lines36536636736836937037136 unmodified lines40840941041141241341441541610 unmodified lines427428429430431432340 unmodified lines773774775776777778779780781782783108 unmodified lines892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925471 unmodified lines1397139813991400140114021403202 unmodified lines1606160716081609161016111612179 unmodified linesif value is not None:if (self.process_every_value is True) and (not isinstance(value, list)):raise ValueError(f"'process_every_field' == True is allowed only when all fields which have mappers, i.e., {list(self.mappers.keys())} are lists. Instace = {instance}")if isinstance(value, list) and self.process_every_value:for i, val in enumerate(value):98 unmodified linesreturn instanceclass FieldOperator(StreamInstanceOperator):"""A general stream instance operator that processes the values of a field (or multiple ones).Args:44 unmodified lines# self._field_to_field is built explicitly by pairs, or copied from argument 'field_to_field'if self.field_to_field is None:return# for backward compatibility also allow list of tupples of two stringsif isoftype(self.field_to_field, List[List[str]]) or isoftype(self.field_to_field, List[Tuple[str, str]]):22 unmodified lines)@abstractmethoddef process_value(self, value: Any) -> Any:passdef prepare(self):36 unmodified lines) from etry:if self.process_every_value:new_value = [self.process_value(value) for value in old_value]else:new_value = self.process_value(old_value)except Exception as e:raise ValueError(f"Failed to process '{from_field}' from {instance} due to : {e}"10 unmodified linesreturn instanceclass RenameFields(FieldOperator):"""Renames fields.340 unmodified linesreturn ".".join(parts)def str_to_function(self, function_str: str) -> Callable:splitted = function_str.split(".", 1)if len(splitted) == 1:return __builtins__[splitted[0]]module_name, function_name = splittedif module_name in __builtins__:obj = __builtins__[module_name]elif module_name in globals():108 unmodified linesreturn instanceclass Perturbate(FieldOperator):"""Slightly perturbates the contents of 'field'. Could be Handy for imitating prediction from given target.When task was classification, argument 'select_from' can be used to list the other potential classes, as arelevant perturbation"""select_from: List[Any] = []percentage_to_perturbate: int = 1 # 1 percentdef verify(self):assert (0 <= self.percentage_to_perturbate and self.percentage_to_perturbate <= 100), f"'percentage_to_perturbate' should be in the range 0..100. Received {self.percentage_to_perturbate}"def prepare(self):super().prepare()self.random_generator = new_random_generator(sub_seed="CopyWithPerturbation")def process_value(self, value: Any) -> Any:perturbate = (self.random_generator.randint(1, 100) <= self.percentage_to_perturbate)if not perturbate:return valueif value in self.select_from:# 80% of cases, return a decent class, otherwise, perturbate the value itself as followsif self.random_generator.random() < 0.8:return self.random_generator.choice(self.select_from)471 unmodified lineselse:# content of 'field' is a list and process_every_value == True: add one occurrence on behalf of each individual valuecounter.update(instance[self.field])# here counter counts occurrences of individual values, or tupples.values_and_counts = counter.most_common()if self.overall_top_frequency_percent < 100:top_frequency = (202 unmodified lines# by the first listed metric (as desired).metric_names = list(reversed(metric_names))# Workaround: The metric/MetricPipeline modifies the stream itself, sometines making it incompatible# for further metrics' processing, instead of just modifying the score field.# Here we keep all the fields besides the score, and restore them after the metric finishes.first_instance = stream.peek()179 unmodified lines18018118218318418518698 unmodified lines28528628728828929029144 unmodified lines33633733833934034134222 unmodified lines36536636736836937037136 unmodified lines40840941041141241341441541641741841910 unmodified lines430431432433434435436437438439440441442443444340 unmodified lines785786787788789790791792793794795108 unmodified lines904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935471 unmodified lines1407140814091410141114121413202 unmodified lines1616161716181619162016211622179 unmodified linesif value is not None:if (self.process_every_value is True) and (not isinstance(value, list)):raise ValueError(f"'process_every_field' == True is allowed only when all fields which have mappers, i.e., {list(self.mappers.keys())} are lists. Instance = {instance}")if isinstance(value, list) and self.process_every_value:for i, val in enumerate(value):98 unmodified linesreturn instanceclass InstanceFieldOperator(StreamInstanceOperator):"""A general stream instance operator that processes the values of a field (or multiple ones).Args:44 unmodified lines# self._field_to_field is built explicitly by pairs, or copied from argument 'field_to_field'if self.field_to_field is None:return# for backward compatibility also allow list of tuples of two stringsif isoftype(self.field_to_field, List[List[str]]) or isoftype(self.field_to_field, List[Tuple[str, str]]):22 unmodified lines)@abstractmethoddef process_instance_value(self, value: Any, instance: Dict[str, Any]):passdef prepare(self):36 unmodified lines) from etry:if self.process_every_value:new_value = [self.process_instance_value(value, instance)for value in old_value]else:new_value = self.process_instance_value(old_value, instance)except Exception as e:raise ValueError(f"Failed to process '{from_field}' from {instance} due to : {e}"10 unmodified linesreturn instanceclass FieldOperator(InstanceFieldOperator):def process_instance_value(self, value: Any, instance: Dict[str, Any]):return self.process_value(value)@abstractmethoddef process_value(self, value: Any) -> Any:passclass RenameFields(FieldOperator):"""Renames fields.340 unmodified linesreturn ".".join(parts)def str_to_function(self, function_str: str) -> Callable:parts = function_str.split(".", 1)if len(parts) == 1:return __builtins__[parts[0]]module_name, function_name = partsif module_name in __builtins__:obj = __builtins__[module_name]elif module_name in globals():108 unmodified linesreturn instanceclass Perturb(FieldOperator):"""Slightly perturbs the contents of 'field'. Could be Handy for imitating prediction from given target.When task was classification, argument 'select_from' can be used to list the other potential classes, as arelevant perturbation"""select_from: List[Any] = []percentage_to_perturb: int = 1 # 1 percentdef verify(self):assert (0 <= self.percentage_to_perturb and self.percentage_to_perturb <= 100), f"'percentage_to_perturb' should be in the range 0..100. Received {self.percentage_to_perturb}"def prepare(self):super().prepare()self.random_generator = new_random_generator(sub_seed="CopyWithPerturbation")def process_value(self, value: Any) -> Any:perturb = self.random_generator.randint(1, 100) <= self.percentage_to_perturbif not perturb:return valueif value in self.select_from:# 80% of cases, return a decent class, otherwise, perturb the value itself as followsif self.random_generator.random() < 0.8:return self.random_generator.choice(self.select_from)471 unmodified lineselse:# content of 'field' is a list and process_every_value == True: add one occurrence on behalf of each individual valuecounter.update(instance[self.field])# here counter counts occurrences of individual values, or tuples.values_and_counts = counter.most_common()if self.overall_top_frequency_percent < 100:top_frequency = (202 unmodified lines# by the first listed metric (as desired).metric_names = list(reversed(metric_names))# Workaround: The metric/MetricPipeline modifies the stream itself, sometimes making it incompatible# for further metrics' processing, instead of just modifying the score field.# Here we keep all the fields besides the score, and restore them after the metric finishes.first_instance = stream.peek()
operators.py+32-22