MODULE REFERENCE
fittable_data_transformer
anomx.data.processing.transformers.fittable_data_transformerFittable Data Transformer Base Class
FittableDataTransformer
FittableDataTransformer(name: str = 'FittableDataTransformer', n_jobs: int = 1, verbose: bool = False, parallel_params: bool | Sequence[str] = False, mask_components: bool = True, columns: str | list[str] | None = None, global_fit: bool = False, uses_insample: bool = False)Bases: BaseDataTransformer
| Parameter | Type | Default |
|---|---|---|
name | str | 'FittableDataTransformer' |
n_jobs | int | 1 |
verbose | bool | False |
parallel_params | bool | Sequence[str] | False |
mask_components | bool | True |
columns | str | list[str] | None | None |
global_fit | bool | False |
uses_insample | bool | False |
Base class for fittable transformers.
All the deriving classes have to implement the static methods ts_transform() and ts_fit(). The fitting and transformation functions must be passed during the transformer's initialization. This class takes care of parallelizing operations involving multiple TimeSeries when possible.
Parameters
- name
The data transformer's name
- n_jobs
The number of jobs to run in parallel. Parallel jobs are created only when a
Sequence[TimeSeries]is passed as input to a method, parallelising operations regarding differentTimeSeries. Defaults to1(sequential). Setting the parameter to-1means using all the available processors. Note: for a small amount of data, the parallelisation overhead could end up increasing the total required amount of time.- verbose
Optionally, whether to print operations progress
- parallel_params
Optionally, specifies which fixed parameters (i.e. the attributes initialized in the child-most class's
__init__) take on different values for different parallel jobs. Fixed parameters specified byparallel_paramsare assumed to be aSequenceof values that should be used for that parameter in each parallel job; the length of thisSequenceshould equal the number of parallel jobs. Ifparallel_params=True, every fixed parameter will take on a different value for each parallel job. Ifparallel_params=False, every fixed parameter will take on the same value for each parallel job. Ifparallel_paramsis aSequenceof fixed attribute names, only those attribute names specified will take on different values between different parallel jobs.- mask_components
Optionally, whether to automatically apply any provided
component_masks to theTimeSeriesinputs passed totransform,fit,inverse_transform, orfit_transform. IfTrue, any specifiedcomponent_maskwill be applied to each input timeseries before passing them to the called method; the masked components will also be automatically 'unmasked' in the returnedTimeSeries. IfFalse, thencomponent_mask(if provided) will be passed as a keyword argument, but won't automatically be applied to the input timeseries. Seeapply_component_maskmethod ofBaseDataTransformerfor further details.- columns
Optionally, a string or list of strings specifying the names of the components (columns) to transform. If specified, only these components will be transformed, and the remaining components will be kept untouched. For more information refer to the
BaseDataTransformerdocumentation. In case the transformer is applied on multiple TimeSeries, it is expected that all series have the same column order.- global_fit
Optionally, whether all
TimeSeriespassed to thefit()method should be used to fit a *single* set of parameters, or if a different set of parameters should be independently fitted to each providedTimeSeries. IfTrue, then aSequence[TimeSeries]is passed tots_fitand a single set of parameters is fitted using all providedTimeSeries. IfFalse, then eachTimeSeriesis individually passed tots_fit, and a different set of fitted parameters if yielded for each of these fitting operations. Seets_fitfor further details.- uses_insample
Whether the transformer requires the in-sample (historic) series during inverse transformation. If
True,inverse_transformwill use theinsampleargument to pass the transformed historic series tots_inverse_transform. This is needed when inverse transforming a partial series (e.g. a forecast) requires information from earlier times (e.g. foranomx.data.processing.transformers.diff.Diff).
Notes
If global_fit is False and fit is called with a Sequence containing n different TimeSeries, then n sets of parameters will be fitted. When transform and/or inverse_transform is subsequently called with a Series[TimeSeries], the ith set of fitted parameter values will be passed to ts_transform/ts_inverse_transform to transform the ith TimeSeries in this sequence. Conversely, if global_fit is True, then only a single set of fitted values will be produced when fit is provided with a Sequence[TimeSeries]. Consequently, if a Sequence[TimeSeries] is then passed to transform/inverse_transform, each of these TimeSeries will be transformed using the exact same set of fitted parameters.
Note that if an invertible *and* fittable data transformer is to be globally fitted, the data transformer class should first inherit from FittableDataTransformer and then from InvertibleDataTransformer. In other words, MyTransformer(FittableDataTransformer, InvertibleDataTransformer) is correct, but MyTransformer(InvertibleDataTransformer, FittableDataTransformer) is not. If this is not implemented correctly, then the global_fit parameter will not be correctly passed to FittableDataTransformer's constructor.
The ts_transform() and ts_fit() methods are designed to be static methods instead of instance methods to allow an efficient parallelisation also when the scaler instance is storing a non-negligible amount of data. Using instance methods would imply copying the instance's data through multiple processes, which can easily introduce a bottleneck and nullify parallelisation benefits.
Example
>>> from anomx.data.processing.transformers import FittableDataTransformer
>>> from anomx._series_utils.timeseries_generation import linear_timeseries
>>>
>>> class SimpleRangeScaler(FittableDataTransformer):
>>>
>>> def __init__(self, scale, position):
>>> self._scale = scale
>>> self._position = position
>>> super().__init__()
>>>
>>> @staticmethod
>>> def ts_transform(series, params):
>>> vals = series.all_values(copy=False)
>>> fit_params = params['fitted']
>>> unit_scale = (vals - fit_params['position'])/fit_params['scale']
>>> fix_params = params['fixed']
>>> rescaled = fix_params['_scale'] * unit_scale + fix_params['_position']
>>> return series.from_values(rescaled)
>>>
>>> @staticmethod
>>> def ts_fit(series, params):
>>> vals = series.all_values(copy=False)
>>> scale = vals.max() - vals.min()
>>> position = vals[0]
>>> return {'scale': scale, 'position': position}
>>>
>>> series = linear_timeseries(length=5, start_value=1, end_value=5)
>>> print(series.values())
[[1.]
[2.]
[3.]
[4.]
[5.]]
>>> series = SimpleRangeScaler(scale=2, position=-1).fit_transform(series)
>>> print(series.values())
[[-1. ]
[-0.5]
[ 0. ]
[ 0.5]
[ 1. ]]Members
ts_fitstaticmethod
ts_fit(series: TimeSeriesLike, params: Mapping[str, Any], *args, **kwargs)The function that will be applied to each series when fit is called.
If the global_fit attribute is set to False, then ts_fit should accept a TimeSeries as a first argument and return a set of parameters that are fitted to this individual TimeSeries. Conversely, if the global_fit attribute is set to True, then ts_fit should accept a Sequence[TimeSeries] and return a set of parameters that are fitted to *all* of the provided TimeSeries. All these parameters will be stored in self._fitted_params, which can be later used during the transformation step.
Regardless of whether the global_fit attribute is set to True or False, ts_fit should also accept a dictionary of fixed parameter values as a second argument (i.e. params['fixed'] contains the fixed parameters of the data transformer).
Any additional positional and/or keyword arguments passed to the fit method will be passed as positional/keyword arguments to ts_fit.
This method is not implemented in the base class and must be implemented in the deriving classes.
If more parameters are added as input in the derived classes, _fit_iterator() should be redefined accordingly, to yield the necessary arguments to this function (See _fit_iterator() for further details)
Parameters
- series
TimeSeriesagainst which the scaler will be fit.
Notes
This method is designed to be a static method instead of instance methods to allow an efficient parallelisation also when the scaler instance is storing a non-negligible amount of data. Using instance methods would imply copying the instance's data through multiple processes, which can easily introduce a bottleneck and nullify parallelisation benefits.
| Parameter | Type | Default |
|---|---|---|
series | TimeSeriesLike | required |
params | Mapping[str, Any] | required |
*args | — | — |
**kwargs | — | — |
fitmethod
fit(series: TimeSeriesLike, *args, component_mask: np.ndarray | None = None, **kwargs) -> 'FittableDataTransformer'Fits transformer to a (sequence of) TimeSeries by calling the user-implemented ts_fit method.
The fitted parameters returned by ts_fit are stored in the self._fitted_params attribute. If a Sequence[TimeSeries] is passed as the series data, then one of two outcomes will occur:
- If the
global_fitattribute was set toFalse, then a different set of parameters will be individually fitted to eachTimeSeriesin theSequence. In this case, this function automatically parallelises this fitting process over all of the multipleTimeSeriesthat have been passed. - If the
global_fitattribute was set toTrue, then all of theTimeSeriesobjects will be used fit a single set of parameters.
Parameters
- series
(sequence of) series to fit the transformer on.
- args
Additional positional arguments for the
ts_fitmethod- component_mask
Optionally, a 1-D boolean np.ndarray of length
series.n_componentsthat specifies which components of the underlyingseriesthe transform should be fitted to.- kwargs
Additional keyword arguments for the
ts_fitmethod
Returns
- FittableDataTransformer
Fitted transformer.
| Parameter | Type | Default |
|---|---|---|
series | TimeSeriesLike | required |
*args | — | — |
component_maskkeyword only | np.ndarray | None | None |
**kwargs | — | — |
Returns 'FittableDataTransformer'
transformmethod
transform(series: TimeSeriesLike, *args, component_mask: np.ndarray | None = None, series_idx: int | Sequence[int] | None = None, **kwargs) -> TimeSeries | list[TimeSeries]| Parameter | Type | Default |
|---|---|---|
series | TimeSeriesLike | required |
*args | — | — |
component_maskkeyword only | np.ndarray | None | None |
series_idxkeyword only | int | Sequence[int] | None | None |
**kwargs | — | — |
Returns TimeSeries | list[TimeSeries]
fit_transformmethod
fit_transform(series: TimeSeriesLike, *args, component_mask: np.ndarray | None = None, **kwargs) -> TimeSeries | list[TimeSeries]Fit the transformer to the (sequence of) series and return the transformed input.
Parameters
- series
the (sequence of) series to transform.
- args
Additional positional arguments passed to the
ts_transformandts_fitmethods.- component_mask
Optionally, a 1-D boolean np.ndarray of length
series.n_componentsthat specifies which components of the underlyingseriesthe transform should be fitted and applied to.- kwargs
Additional keyword arguments passed to the
ts_transformandts_fitmethods.
Returns
- TimeSeriesLike
Transformed data.
| Parameter | Type | Default |
|---|---|---|
series | TimeSeriesLike | required |
*args | — | — |
component_maskkeyword only | np.ndarray | None | None |
**kwargs | — | — |
Returns TimeSeries | list[TimeSeries]