Upload operators.py with huggingface_hub
Browse files60 unmodified lines61626364656667813 unmodified lines881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936155 unmodified lines1092109310941044104510461047104810951096109710981099110011011052105310541102110311041105110611071108110910581110111110611112111311147 unmodified lines112211231124112511261076107710781079108010811082108310841085112711281129113011311132194 unmodified lines132713281329128613301331133213335 unmodified lines1339134013411298129913421343134413011345134613031347134813491306130713081309135013511352135313121354135513561357135813591 unmodified line13611362136313201364136513661367388 unmodified lines17561757175817151716175917601761176217631764176517661767176817221769177017711772177360 unmodified lines MultiStream, MultiStreamOperator, PagedStreamOperator, SequentialOperator, SingleStreamOperator, SingleStreamReducer, StreamingOperator,813 unmodified lines return instance
class 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 a relevant perturbation """
select_from: List[Any] = [] percentage_to_perturbate: int = 1 # 1 percent
def 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 value
if value in self.select_from: # 80% of cases, return a decent class, otherwise, perturbate the value itself as follows if self.random_generator.random() < 0.8: return self.random_generator.choice(self.select_from)
if isinstance(value, float): return value * (0.5 + self.random_generator.random())
if isinstance(value, int): perturb = 1 if self.random_generator.random() < 0.5 else -1 return value + perturb
if isinstance(value, str): if len(value) < 2: # give up perturbation return value # throw one char out prefix_len = self.random_generator.randint(1, len(value) - 1) return value[:prefix_len] + value[prefix_len + 1 :]
# and in any other case: return value
class CopyFields(FieldOperator): """Copies values from specified fields to specified fields.
155 unmodified lines """Applies value operators to each instance in a stream based on specified fields.
Args: inputs_fields (List[str]): list of field names, the values in which are to be processed fields_to_treat_as_list (List[str]): sublist of input_fields, each member of this sublist is supposed to contain a list of values, each of which is to be processed. operators_field (str): name of the field that contains the list of names of the operators to be applied, one after the other, for the processing. operators_field (str): name of the field that contains a single name, or a list of names, of the operators to be applied, one after the other, for the processing of the instance. Each operator is equipped with 'process_instance()' method.
default_operators (List[str]): A list of default operators to be used if no operators are found in the instance.
Example: when instance {"a": 111, "b": 2, "c": ["processors.to_string", "processors.first_character"]} is processed by operator: operator = ApplyOperatorsField(inputs_fields=["a"], operators_field="c", default_operators=["add"]), the resulting instance is: {"a": "1", "b": 2, "c": ["processors.to_string", "processors.first_character"]} when instance {"prediction": 111, "references": [222, 333] , "c": ["processors.to_string", "processors.first_character"]} is processed by operator (please look up the catalog that these operators, they are tuned to process fields "prediction" and "references"): operator = ApplyOperatorsField(operators_field="c"), the resulting instance is: {"prediction": "1", "references": ["2", "3"], "c": ["processors.to_string", "processors.first_character"]}
"""
inputs_fields: List[str] operators_field: str default_operators: List[str] = None fields_to_treat_as_list: List[str] = NonPositionalField(default_factory=list)
def process( self, instance: Dict[str, Any], stream_name: Optional[str] = None7 unmodified lines
if isinstance(operator_names, str): operator_names = [operator_names] # otherwise , operator_names is already a list
for name in operator_names: operator = self.get_artifact(name) for field_name in self.inputs_fields: value = instance[field_name] if field_name in self.fields_to_treat_as_list: instance[field_name] = [operator.process(v) for v in value] else: instance[field_name] = operator.process(value)
return instance # we now have a list of nanes of operators, each is equipped with process_instance method. operator = SequentialOperator(steps=operator_names) return operator.process_instance(instance)
class FilterByCondition(SingleStreamOperator):194 unmodified lines
def process(self, multi_stream: MultiStream) -> MultiStream: stream = multi_stream[self.stream_name] all_values = [] counter = Counter() for instance in stream: if (not isinstance(instance[self.field], list)) and ( self.process_every_value is True5 unmodified lines self.process_every_value is False ): # either not a list, or is a list but process_every_value == False : view contetns of 'field' as one entity whose occurrences are counted. all_values.append( (*instance[self.field],) counter.update( [(*instance[self.field],)] if isinstance(instance[self.field], list) else instance[self.field] else [instance[self.field]] ) # convert to a tuple if list, to enable the use of Counter which would not accept # a list as an entity to count its occurrences # a list as an hashable entity to count its occurrences else: # content of 'field' is a list and process_every_value == True: add one occurrence on behalf of each individual value all_values.extend(instance[self.field]) counter = Counter( all_values ) # here all_values is a list of individual values, or tupples. Hence, Counter is feasible counter.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 = len(all_values) * self.overall_top_frequency_percent / 100.0 top_frequency = ( sum(counter.values()) * self.overall_top_frequency_percent / 100.0 ) sum_counts = 0 for _i, p in enumerate(values_and_counts): sum_counts += p[1]1 unmodified line break values_and_counts = counter.most_common(_i + 1) if self.min_frequency_percent > 0: min_frequency = self.min_frequency_percent * len(all_values) / 100.0 min_frequency = self.min_frequency_percent * sum(counter.values()) / 100.0 while values_and_counts[-1][1] < min_frequency: values_and_counts.pop() values_to_keep = [388 unmodified lines
Args: segments_boundaries (List[int]): distinct integers sorted in increasing order, that maps a given total length into the index of the least of them that exceeds the total length. (If none exceeds -- into one index beyond, namely, the length of segments_boudaries) into the index of the least of them that exceeds the total length. (If none exceeds -- into one index beyond, namely, the length of segments_boudaries)
fields (Optional, List[str])
Example: when input [{"a": [1, 3], "b": 0, "id": 0}, {"a": [1, 3], "b": 0, "id": 1}, {"a": [], "b": "a", "id": 2}] is fed into
.. code-block::
LengthBalancer(fields=["a"], segments_boundaries=[1]) LengthBalancer(fields=["a"], segments_boundaries=[1])
input instances will be counted and balanced against two categories: empty total length (less than 1), and non-empty. """
operators.py+82-34