/
preprocessing.py
245 lines (186 loc) · 6.63 KB
/
preprocessing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""Resampling and stationarization of time series data."""
# License: GNU AGPLv3
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.utils.validation import check_array, column_or_1d
from sklearn.utils.validation import check_is_fitted
from ..base import TransformerResamplerMixin
from ..utils._docs import adapt_fit_transform_docs
from ..utils.intervals import Interval
from ..utils.validation import validate_params
@adapt_fit_transform_docs
class Resampler(BaseEstimator, TransformerResamplerMixin):
"""Time series resampling at regular intervals.
Parameters
----------
period : int, default: ``2``
The sampling period, i.e. one point every period will be kept.
Examples
--------
>>> import numpy as np
>>> from gtda.time_series import Resampler
>>> # Create a noisy signal
>>> signal = np.asarray([np.sin(x /40) + np.random.random()
... for x in range(0, 300)])
>>> # Set up the Resampler
>>> period = 10
>>> periodic_sampler = Resampler(period=period)
>>> # Fit and transform the signal
>>> signal_resampled = periodic_sampler.fit_transform(signal)
>>> print(signal_resampled.shape)
(30,)
"""
_hyperparameters = {
'period': {'type': int, 'in': Interval(1, np.inf, closed='left')}
}
def __init__(self, period=2):
self.period = period
def fit(self, X, y=None):
"""Do nothing and return the estimator unchanged.
This method is here to implement the usual scikit-learn API and hence
work in pipelines.
Parameters
----------
X : ndarray of shape (n_samples,) or (n_samples, ...)
Input data.
y : None
Ignored.
Returns
-------
self : object
"""
check_array(X, ensure_2d=False, allow_nd=True)
validate_params(self.get_params(), self._hyperparameters)
self._is_fitted = True
return self
def transform(self, X, y=None):
"""Resample `X`.
Parameters
----------
X : ndarray of shape (n_samples,) or (n_samples, ...)
Input data.
y : None
There is no need for a target, yet the pipeline API requires this
parameter.
Returns
-------
Xt : ndarray of shape (n_samples_new, ...)
Resampled array. ``n_samples_new = n_samples // period``.
"""
check_is_fitted(self, '_is_fitted')
Xt = check_array(X, ensure_2d=False, allow_nd=True, copy=True)
if Xt.ndim == 1:
Xt = Xt[: None]
Xt = Xt[::self.period]
return Xt
def resample(self, y, X=None):
"""Resample `y`.
Parameters
----------
y : ndarray of shape (n_samples,)
Target.
X : None
There is no need for input data, yet the pipeline API requires this
parameter.
Returns
-------
yr : ndarray of shape (n_samples_new,)
Resampled target. ``n_samples_new = n_samples // period``.
"""
check_is_fitted(self, '_is_fitted')
yr = column_or_1d(y)
yr = yr[::self.period]
return yr
class Stationarizer(BaseEstimator, TransformerResamplerMixin):
"""Methods for stationarizing time series data.
Time series may be stationarized to remove or reduce linear or exponential
trends.
Parameters
----------
operation : ``'return'`` | ``'log-return'``, default: ``'return'``
The type of stationarization operation to perform. It can have two
values:
- ``'return'``:
This option transforms the time series :math:`{X_t}_t` into the
time series of relative returns, i.e. the ratio :math:`(X_t-X_{
t-1})/X_t`.
- ``'log-return'``:
This option transforms the time series :math:`{X_t}_t` into the
time series of relative log-returns, i.e. :math:`\\log(X_t/X_{
t-1})`.
Examples
--------
>>> import numpy as np
>>> from gtda.time_series import Stationarizer
>>> # Create a noisy signal
>>> signal = np.asarray([np.sin(x /40) + 5 + np.random.random()
>>> for x in range(0, 300)]).reshape(-1, 1)
>>> # Initialize the stationarizer
>>> stationarizer = Stationarizer(operation='return')
>>> # Fit and transform the signal
>>> signal_stationarized = stationarizer.fit_transform(signal)
>>> print(signal_stationarized.shape)
(299,)
"""
_hyperparameters = {
'operation': {'type': str, 'in': ['return', 'log-return']}
}
def __init__(self, operation='return'):
self.operation = operation
def fit(self, X, y=None):
"""Do nothing and return the estimator unchanged.
This method is here to implement the usual scikit-learn API and hence
work in pipelines.
Parameters
----------
X : ndarray of shape (n_samples,) or (n_samples, ...)
Input data.
y : None
Ignored.
Returns
-------
self : object
"""
check_array(X, ensure_2d=False, allow_nd=True)
validate_params(self.get_params(), self._hyperparameters)
self._is_fitted = True
return self
def transform(self, X, y=None):
"""Stationarize `X` by applying the procedure given by `operation`.
Parameters
----------
X : ndarray of shape (n_samples,) or (n_samples, ...)
Input data.
y : None
There is no need for a target, yet the pipeline API requires this
parameter.
Returns
-------
Xt : ndarray of shape (n_samples_new, ...)
Stationarized array. ``n_samples_new = n_samples - 1``.
"""
check_is_fitted(self, '_is_fitted')
Xt = check_array(X, ensure_2d=False, allow_nd=True)
if Xt.ndim == 1:
Xt = Xt[:, None]
if self.operation == 'return':
return np.diff(Xt, n=1, axis=0) / Xt[1:]
else: # Assumes 'log-return' operation
return np.diff(np.log(Xt), n=1, axis=0)
def resample(self, y, X=None):
"""Resample `y`.
Parameters
----------
y : ndarray of shape (n_samples,)
Target.
X : None
There is no need for input data, yet the pipeline API requires this
parameter.
Returns
-------
yr : ndarray of shape (n_samples_new,)
Resampled target. ``n_samples_new = n_samples - 1``.
"""
check_is_fitted(self, '_is_fitted')
y = column_or_1d(y)
return y[1:]