|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""Process Signals core functionality.""" |
| 3 | + |
| 4 | +from collections import Counter |
| 5 | + |
| 6 | +import pandas as pd |
| 7 | +from mlblocks import MLPipeline, load_primitive |
| 8 | + |
| 9 | + |
| 10 | +def _build_pipeline(transformations, aggregations): |
| 11 | + """Build Pipeline function. |
| 12 | +
|
| 13 | + Given a list of transformations and aggregations build a pipeline |
| 14 | + with the output of the aggregations, which take as name the specified |
| 15 | + name of the transformations and the aggregation. This lists are composed |
| 16 | + by dictionaries with the following specification: |
| 17 | +
|
| 18 | + * ``Name``: |
| 19 | + Name of the transformation / aggregation. |
| 20 | + * ``primitive``: |
| 21 | + Name of the primitive to apply. |
| 22 | + * ``init_params``: |
| 23 | + Dictionary containing the initializing parameters for the primitive. |
| 24 | +
|
| 25 | + Args: |
| 26 | + transformations (list): |
| 27 | + List of dictionaries containing the transformation primitives. |
| 28 | + transformations (list): |
| 29 | + List of dictionaries containing the aggregation primitives. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + mlblocks.MLPipeline: |
| 33 | + An ``MLPipeline`` object that first applies all the transformations |
| 34 | + and then produces as output the aggregations specified. |
| 35 | + """ |
| 36 | + primitives = [] |
| 37 | + init_params = {} |
| 38 | + prefix = [] |
| 39 | + outputs = [] |
| 40 | + counter = Counter() |
| 41 | + |
| 42 | + for transformation in transformations: |
| 43 | + prefix.append(transformation['name']) |
| 44 | + primitive = transformation['primitive'] |
| 45 | + counter[primitive] += 1 |
| 46 | + primitive_name = f'{primitive}#{counter[primitive]}' |
| 47 | + primitives.append(primitive) |
| 48 | + params = transformation.get('init_params') |
| 49 | + if params: |
| 50 | + init_params[primitive_name] = params |
| 51 | + |
| 52 | + prefix = '.'.join(prefix) if prefix else '' |
| 53 | + |
| 54 | + for aggregation in aggregations: |
| 55 | + aggregation_name = f'{prefix}.{aggregation["name"]}' if prefix else aggregation['name'] |
| 56 | + |
| 57 | + primitive = aggregation['primitive'] |
| 58 | + counter[primitive] += 1 |
| 59 | + primitive_name = f'{primitive}#{counter[primitive]}' |
| 60 | + primitives.append(primitive) |
| 61 | + |
| 62 | + primitive = load_primitive(primitive) |
| 63 | + primitive_outputs = primitive['produce']['output'] |
| 64 | + |
| 65 | + for output in primitive_outputs: |
| 66 | + output = output['name'] |
| 67 | + outputs.append({ |
| 68 | + 'name': f'{aggregation_name}.{output}', |
| 69 | + 'variable': f'{primitive_name}.{output}' |
| 70 | + }) |
| 71 | + |
| 72 | + params = aggregation.get('init_params') |
| 73 | + if params: |
| 74 | + init_params[primitive_name] = params |
| 75 | + |
| 76 | + outputs = {'default': outputs} if outputs else None |
| 77 | + |
| 78 | + return MLPipeline( |
| 79 | + primitives, |
| 80 | + init_params=init_params, |
| 81 | + outputs=outputs |
| 82 | + ) |
| 83 | + |
| 84 | + |
| 85 | +def _apply_pipeline(row, pipeline, values_column_name): |
| 86 | + """Apply a ``mlblocks.MLPipeline`` to a row. |
| 87 | +
|
| 88 | + Apply a ``MLPipeline`` to a row of a ``pd.DataFrame``, this function can |
| 89 | + be combined with the ``pd.DataFrame.apply`` method to be applied to the |
| 90 | + entire data frame. |
| 91 | +
|
| 92 | + Args: |
| 93 | + row (pd.Series): |
| 94 | + Row used to apply the pipeline to. |
| 95 | + pipeline (mlblocks.MLPipeline): |
| 96 | + Pipeline to be used for producing the results. |
| 97 | + values_column_name (str): |
| 98 | + The name of the column that contains the signal values. |
| 99 | + """ |
| 100 | + context = row.to_dict() |
| 101 | + amplitude_values = context.pop(values_column_name) |
| 102 | + output = pipeline.predict( |
| 103 | + amplitude_values=amplitude_values, |
| 104 | + **context, |
| 105 | + ) |
| 106 | + output_names = pipeline.get_output_names() |
| 107 | + |
| 108 | + # ensure that we can iterate over output |
| 109 | + output = output if isinstance(output, tuple) else (output, ) |
| 110 | + |
| 111 | + return pd.Series(dict(zip(output_names, output))) |
| 112 | + |
| 113 | + |
| 114 | +def process_signals(data, transformations, aggregations, |
| 115 | + values_column_name='values', keep_values=False): |
| 116 | + """Process Signals. |
| 117 | +
|
| 118 | + The Process Signals is responsible for applying a collection of primitives specified by the |
| 119 | + user in order to create features for the given data. |
| 120 | +
|
| 121 | + Given a list of transformations and aggregations which are composed |
| 122 | + by dictionaries with the following specification: |
| 123 | +
|
| 124 | + * ``Name``: |
| 125 | + Name of the transformation / aggregation. |
| 126 | + * ``primitive``: |
| 127 | + Name of the primitive to apply. |
| 128 | + * ``init_params``: |
| 129 | + Dictionary containing the initializing parameters for the primitive. |
| 130 | +
|
| 131 | + The process signals will build an ``mlblocks.MLPipeline`` and will generate the features |
| 132 | + by previously applying the transformations and then compute the aggregations. |
| 133 | +
|
| 134 | + Args: |
| 135 | + data (pandas.DataFrame): |
| 136 | + Dataframe with a column that contains signal values. |
| 137 | + transformations (list): |
| 138 | + List of dictionaries containing the transformation primitives. |
| 139 | + aggregations (list): |
| 140 | + List of dictionaries containing the aggregation primitives. |
| 141 | + values_column_name (str): |
| 142 | + The name of the column that contains the signal values. Defaults to ``values``. |
| 143 | + keep_values (bool): |
| 144 | + Whether or not to keep the original signal values or remove them. |
| 145 | +
|
| 146 | + Returns: |
| 147 | + pandas.DataFrame: |
| 148 | + A data frame with new feature columns by applying the previous primitives. If |
| 149 | + ``keep_values`` is ``True`` the original signal values will be conserved in the |
| 150 | + data frame, otherwise the original signal values will be deleted. |
| 151 | + """ |
| 152 | + pipeline = _build_pipeline(transformations, aggregations) |
| 153 | + features = data.apply( |
| 154 | + _apply_pipeline, |
| 155 | + args=(pipeline, values_column_name), |
| 156 | + axis=1 |
| 157 | + ) |
| 158 | + |
| 159 | + data = pd.concat([data, features], axis=1) |
| 160 | + |
| 161 | + if not keep_values: |
| 162 | + del data[values_column_name] |
| 163 | + |
| 164 | + return data |
0 commit comments