/
feature_calculators.py
2509 lines (1953 loc) · 80.1 KB
/
feature_calculators.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)
# Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016
"""
This module contains the feature calculators that take time series as input and calculate the values of the feature.
There are two types of features:
1. feature calculators which calculate a single number (simple)
2. feature calculators which calculate a bunch of features for a list of parameters at once,
to use e.g. cached results (combiner). They return a list of (key, value) pairs for each input parameter.
They are specified using the "fctype" parameter of each feature calculator, which is added using the
set_property function. Only functions in this python module, which have a parameter called "fctype" are
seen by tsfresh as a feature calculator. Others will not be calculated.
Feature calculators of type combiner should return the concatenated parameters sorted
alphabetically ascending.
"""
import functools
import itertools
import warnings
from builtins import range
from collections import defaultdict
import numpy as np
import pandas as pd
import stumpy
from numpy.linalg import LinAlgError
from scipy.signal import cwt, find_peaks_cwt, ricker, welch
from scipy.stats import linregress
from statsmodels.tools.sm_exceptions import MissingDataError
from statsmodels.tsa.ar_model import AutoReg
try:
import matrixprofile as mp
from matrixprofile.exceptions import NoSolutionPossible
except ImportError:
mp = None
from tsfresh.utilities.string_manipulation import convert_to_output_format
with warnings.catch_warnings():
# Ignore warnings of the patsy package
warnings.simplefilter("ignore", DeprecationWarning)
from statsmodels.tsa.stattools import acf, adfuller, pacf
# todo: make sure '_' works in parameter names in all cases, add a warning if not
def _roll(a, shift):
"""
Roll 1D array elements. Improves the performance of numpy.roll() by reducing the overhead introduced from the
flexibility of the numpy.roll() method such as the support for rolling over multiple dimensions.
Elements that roll beyond the last position are re-introduced at the beginning. Similarly, elements that roll
back beyond the first position are re-introduced at the end (with negative shift).
Examples
--------
>>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> _roll(x, shift=2)
>>> array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
>>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> _roll(x, shift=-2)
>>> array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
>>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> _roll(x, shift=12)
>>> array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
Benchmark
---------
>>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> %timeit _roll(x, shift=2)
>>> 1.89 µs ± 341 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> %timeit np.roll(x, shift=2)
>>> 11.4 µs ± 776 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
:param a: the input array
:type a: array_like
:param shift: the number of places by which elements are shifted
:type shift: int
:return: shifted array with the same shape as a
:return type: ndarray
"""
if not isinstance(a, np.ndarray):
a = np.asarray(a)
idx = shift % len(a)
return np.concatenate([a[-idx:], a[:-idx]])
def _get_length_sequences_where(x):
"""
This method calculates the length of all sub-sequences where the array x is either True or 1.
Examples
--------
>>> x = [0,1,0,0,1,1,1,0,0,1,0,1,1]
>>> _get_length_sequences_where(x)
>>> [1, 3, 1, 2]
>>> x = [0,True,0,0,True,True,True,0,0,True,0,True,True]
>>> _get_length_sequences_where(x)
>>> [1, 3, 1, 2]
>>> x = [0,True,0,0,1,True,1,0,0,True,0,1,True]
>>> _get_length_sequences_where(x)
>>> [1, 3, 1, 2]
:param x: An iterable containing only 1, True, 0 and False values
:return: A list with the length of all sub-sequences where the array is either True or False. If no ones or Trues
contained, the list [0] is returned.
"""
if len(x) == 0:
return [0]
else:
res = [len(list(group)) for value, group in itertools.groupby(x) if value == 1]
return res if len(res) > 0 else [0]
def _estimate_friedrich_coefficients(x, m, r):
"""
Coefficients of polynomial :math:`h(x)`, which has been fitted to
the deterministic dynamics of Langevin model
.. math::
\\dot{x}(t) = h(x(t)) + \\mathcal{N}(0,R)
As described by
Friedrich et al. (2000): Physics Letters A 271, p. 217-222
*Extracting model equations from experimental data*
For short time-series this method is highly dependent on the parameters.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:param m: order of polynomial to fit for estimating fixed points of dynamics
:type m: int
:param r: number of quantiles to use for averaging
:type r: float
:return: coefficients of polynomial of deterministic dynamics
:return type: ndarray
"""
assert m > 0, "Order of polynomial need to be positive integer, found {}".format(m)
df = pd.DataFrame({"signal": x[:-1], "delta": np.diff(x)})
try:
df["quantiles"] = pd.qcut(df.signal, r)
except (ValueError, IndexError):
return [np.NaN] * (m + 1)
quantiles = df.groupby("quantiles")
result = pd.DataFrame(
{"x_mean": quantiles.signal.mean(), "y_mean": quantiles.delta.mean()}
)
result.dropna(inplace=True)
try:
return np.polyfit(result.x_mean, result.y_mean, deg=m)
except (np.linalg.LinAlgError, ValueError):
return [np.NaN] * (m + 1)
def _aggregate_on_chunks(x, f_agg, chunk_len):
"""
Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f_agg on
consecutive chunks of length chunk_len
:param x: the time series to calculate the aggregation of
:type x: numpy.ndarray
:param f_agg: The name of the aggregation function that should be an attribute of the pandas.Series
:type f_agg: str
:param chunk_len: The size of the chunks where to aggregate the time series
:type chunk_len: int
:return: A list of the aggregation function over the chunks
:return type: list
"""
return [
getattr(x[i * chunk_len : (i + 1) * chunk_len], f_agg)()
for i in range(int(np.ceil(len(x) / chunk_len)))
]
def _into_subchunks(x, subchunk_length, every_n=1):
"""
Split the time series x into subwindows of length "subchunk_length", starting every "every_n".
For example, the input data if [0, 1, 2, 3, 4, 5, 6] will be turned into a matrix
0 2 4
1 3 5
2 4 6
with the settings subchunk_length = 3 and every_n = 2
"""
len_x = len(x)
assert subchunk_length > 1
assert every_n > 0
# how often can we shift a window of size subchunk_length over the input?
num_shifts = (len_x - subchunk_length) // every_n + 1
shift_starts = every_n * np.arange(num_shifts)
indices = np.arange(subchunk_length)
indexer = np.expand_dims(indices, axis=0) + np.expand_dims(shift_starts, axis=1)
return np.asarray(x)[indexer]
def set_property(key, value):
"""
This method returns a decorator that sets the property key of the function to value
"""
def decorate_func(func):
setattr(func, key, value)
if func.__doc__ and key == "fctype":
func.__doc__ = (
func.__doc__ + "\n\n *This function is of type: " + value + "*\n"
)
return func
return decorate_func
@set_property("fctype", "simple")
def variance_larger_than_standard_deviation(x):
"""
Is variance higher than the standard deviation?
Boolean variable denoting if the variance of x is greater than its standard deviation. Is equal to variance of x
being larger than 1
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: bool
"""
y = np.var(x)
return y > np.sqrt(y)
@set_property("fctype", "simple")
def ratio_beyond_r_sigma(x, r):
"""
Ratio of values that are more than r * std(x) (so r times sigma) away from the mean of x.
:param x: the time series to calculate the feature of
:type x: iterable
:param r: the ratio to compare with
:type r: float
:return: the value of this feature
:return type: float
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return np.sum(np.abs(x - np.mean(x)) > r * np.std(x)) / x.size
@set_property("fctype", "simple")
def large_standard_deviation(x, r):
"""
Does time series have *large* standard deviation?
Boolean variable denoting if the standard dev of x is higher than 'r' times the range = difference between max and
min of x. Hence it checks if
.. math::
std(x) > r * (max(X)-min(X))
According to a rule of the thumb, the standard deviation should be a forth of the range of the values.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:param r: the percentage of the range to compare with
:type r: float
:return: the value of this feature
:return type: bool
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return np.std(x) > (r * (np.max(x) - np.min(x)))
@set_property("fctype", "combiner")
def symmetry_looking(x, param):
"""
Boolean variable denoting if the distribution of x *looks symmetric*. This is the case if
.. math::
| mean(X)-median(X)| < r * (max(X)-min(X))
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:param param: contains dictionaries {"r": x} with x (float) is the percentage of the range to compare with
:type param: list
:return: the value of this feature
:return type: bool
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
mean_median_difference = np.abs(np.mean(x) - np.median(x))
max_min_difference = np.max(x) - np.min(x)
return [
("r_{}".format(r["r"]), mean_median_difference < (r["r"] * max_min_difference))
for r in param
]
@set_property("fctype", "simple")
def has_duplicate_max(x):
"""
Checks if the maximum value of x is observed more than once
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: bool
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return np.sum(x == np.max(x)) >= 2
@set_property("fctype", "simple")
def has_duplicate_min(x):
"""
Checks if the minimal value of x is observed more than once
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: bool
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return np.sum(x == np.min(x)) >= 2
@set_property("fctype", "simple")
def has_duplicate(x):
"""
Checks if any value in x occurs more than once
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: bool
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return x.size != np.unique(x).size
@set_property("fctype", "simple")
@set_property("minimal", True)
def sum_values(x):
"""
Calculates the sum over the time series values
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if len(x) == 0:
return 0
return np.sum(x)
@set_property("fctype", "combiner")
def agg_autocorrelation(x, param):
"""
Descriptive statistics on the autocorrelation of the time series.
Calculates the value of an aggregation function :math:`f_{agg}` (e.g. the variance or the mean) over the
autocorrelation :math:`R(l)` for different lags. The autocorrelation :math:`R(l)` for lag :math:`l` is defined as
.. math::
R(l) = \\frac{1}{(n-l)\\sigma^2} \\sum_{t=1}^{n-l}(X_{t}-\\mu )(X_{t+l}-\\mu)
where :math:`X_i` are the values of the time series, :math:`n` its length. Finally, :math:`\\sigma^2` and
:math:`\\mu` are estimators for its variance and mean
(See `Estimation of the Autocorrelation function <http://en.wikipedia.org/wiki/Autocorrelation#Estimation>`_).
The :math:`R(l)` for different lags :math:`l` form a vector. This feature calculator applies the aggregation
function :math:`f_{agg}` to this vector and returns
.. math::
f_{agg} \\left( R(1), \\ldots, R(m)\\right) \\quad \\text{for} \\quad m = max(n, maxlag).
Here :math:`maxlag` is the second parameter passed to this function.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:param param: contains dictionaries {"f_agg": x, "maxlag", n} with x str, the name of a numpy function
(e.g. "mean", "var", "std", "median"), its the name of the aggregator function that is applied to the
autocorrelations. Further, n is an int and the maximal number of lags to consider.
:type param: list
:return: the value of this feature
:return type: float
"""
# if the time series is longer than the following threshold, we use fft to calculate the acf
THRESHOLD_TO_USE_FFT = 1250
var = np.var(x)
n = len(x)
max_maxlag = max([config["maxlag"] for config in param])
if np.abs(var) < 10**-10 or n == 1:
a = [0] * len(x)
else:
a = acf(x, adjusted=True, fft=n > THRESHOLD_TO_USE_FFT, nlags=max_maxlag)[1:]
return [
(
'f_agg_"{}"__maxlag_{}'.format(config["f_agg"], config["maxlag"]),
getattr(np, config["f_agg"])(a[: int(config["maxlag"])]),
)
for config in param
]
@set_property("fctype", "combiner")
def partial_autocorrelation(x, param):
"""
Calculates the value of the partial autocorrelation function at the given lag.
The lag `k` partial autocorrelation of a time series :math:`\\lbrace x_t, t = 1 \\ldots T \\rbrace` equals the
partial correlation of :math:`x_t` and :math:`x_{t-k}`, adjusted for the intermediate variables
:math:`\\lbrace x_{t-1}, \\ldots, x_{t-k+1} \\rbrace` ([1]).
Following [2], it can be defined as
.. math::
\\alpha_k = \\frac{ Cov(x_t, x_{t-k} | x_{t-1}, \\ldots, x_{t-k+1})}
{\\sqrt{ Var(x_t | x_{t-1}, \\ldots, x_{t-k+1}) Var(x_{t-k} | x_{t-1}, \\ldots, x_{t-k+1} )}}
with (a) :math:`x_t = f(x_{t-1}, \\ldots, x_{t-k+1})` and (b) :math:`x_{t-k} = f(x_{t-1}, \\ldots, x_{t-k+1})`
being AR(k-1) models that can be fitted by OLS. Be aware that in (a), the regression is done on past values to
predict :math:`x_t` whereas in (b), future values are used to calculate the past value :math:`x_{t-k}`.
It is said in [1] that "for an AR(p), the partial autocorrelations [ :math:`\\alpha_k` ] will be nonzero for `k<=p`
and zero for `k>p`."
With this property, it is used to determine the lag of an AR-Process.
.. rubric:: References
| [1] Box, G. E., Jenkins, G. M., Reinsel, G. C., & Ljung, G. M. (2015).
| Time series analysis: forecasting and control. John Wiley & Sons.
| [2] https://onlinecourses.science.psu.edu/stat510/node/62
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:param param: contains dictionaries {"lag": val} with int val indicating the lag to be returned
:type param: list
:return: the value of this feature
:return type: float
"""
# Check the difference between demanded lags by param and possible lags to calculate (depends on len(x))
max_demanded_lag = max([lag["lag"] for lag in param])
n = len(x)
# Check if list is too short to make calculations
if n <= 1:
pacf_coeffs = [np.nan] * (max_demanded_lag + 1)
else:
# https://github.com/statsmodels/statsmodels/pull/6846
# PACF limits lag length to 50% of sample size.
if max_demanded_lag >= n // 2:
max_lag = n // 2 - 1
else:
max_lag = max_demanded_lag
if max_lag > 0:
pacf_coeffs = list(pacf(x, method="ld", nlags=max_lag))
pacf_coeffs = pacf_coeffs + [np.nan] * max(0, (max_demanded_lag - max_lag))
else:
pacf_coeffs = [np.nan] * (max_demanded_lag + 1)
return [("lag_{}".format(lag["lag"]), pacf_coeffs[lag["lag"]]) for lag in param]
@set_property("fctype", "combiner")
def augmented_dickey_fuller(x, param):
"""
Does the time series have a unit root?
The Augmented Dickey-Fuller test is a hypothesis test which checks whether a unit root is present in a time
series sample. This feature calculator returns the value of the respective test statistic.
See the statsmodels implementation for references and more details.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:param param: contains dictionaries {"attr": x, "autolag": y} with x str, either "teststat", "pvalue" or "usedlag"
and with y str, either of "AIC", "BIC", "t-stats" or None (See the documentation of adfuller() in
statsmodels).
:type param: list
:return: the value of this feature
:return type: float
"""
@functools.lru_cache()
def compute_adf(autolag):
try:
return adfuller(x, autolag=autolag)
except LinAlgError:
return np.NaN, np.NaN, np.NaN
except ValueError: # occurs if sample size is too small
return np.NaN, np.NaN, np.NaN
except MissingDataError: # is thrown for e.g. inf or nan in the data
return np.NaN, np.NaN, np.NaN
res = []
for config in param:
autolag = config.get("autolag", "AIC")
adf = compute_adf(autolag)
index = 'attr_"{}"__autolag_"{}"'.format(config["attr"], autolag)
if config["attr"] == "teststat":
res.append((index, adf[0]))
elif config["attr"] == "pvalue":
res.append((index, adf[1]))
elif config["attr"] == "usedlag":
res.append((index, adf[2]))
else:
res.append((index, np.NaN))
return res
@set_property("fctype", "simple")
def abs_energy(x):
"""
Returns the absolute energy of the time series which is the sum over the squared values
.. math::
E = \\sum_{i=1,\\ldots, n} x_i^2
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return np.dot(x, x)
@set_property("fctype", "simple")
def cid_ce(x, normalize):
"""
This function calculator is an estimate for a time series complexity [1] (A more complex time series has more peaks,
valleys etc.). It calculates the value of
.. math::
\\sqrt{ \\sum_{i=1}^{n-1} ( x_{i} - x_{i-1})^2 }
.. rubric:: References
| [1] Batista, Gustavo EAPA, et al (2014).
| CID: an efficient complexity-invariant distance for time series.
| Data Mining and Knowledge Discovery 28.3 (2014): 634-669.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:param normalize: should the time series be z-transformed?
:type normalize: bool
:return: the value of this feature
:return type: float
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
if normalize:
s = np.std(x)
if s != 0:
x = (x - np.mean(x)) / s
else:
return 0.0
x = np.diff(x)
return np.sqrt(np.dot(x, x))
@set_property("fctype", "simple")
def mean_abs_change(x):
"""
Average over first differences.
Returns the mean over the absolute differences between subsequent time series values which is
.. math::
\\frac{1}{n-1} \\sum_{i=1,\\ldots, n-1} | x_{i+1} - x_{i}|
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
return np.mean(np.abs(np.diff(x)))
@set_property("fctype", "simple")
def mean_change(x):
"""
Average over time series differences.
Returns the mean over the differences between subsequent time series values which is
.. math::
\\frac{1}{n-1} \\sum_{i=1,\\ldots, n-1} x_{i+1} - x_{i} = \\frac{1}{n-1} (x_{n} - x_{1})
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
x = np.asarray(x)
return (x[-1] - x[0]) / (len(x) - 1) if len(x) > 1 else np.NaN
@set_property("fctype", "simple")
def mean_second_derivative_central(x):
"""
Returns the mean value of a central approximation of the second derivative
.. math::
\\frac{1}{2(n-2)} \\sum_{i=1,\\ldots, n-1} \\frac{1}{2} (x_{i+2} - 2 \\cdot x_{i+1} + x_i)
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
x = np.asarray(x)
return (x[-1] - x[-2] - x[1] + x[0]) / (2 * (len(x) - 2)) if len(x) > 2 else np.NaN
@set_property("fctype", "simple")
@set_property("minimal", True)
def median(x):
"""
Returns the median of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
return np.median(x)
@set_property("fctype", "simple")
@set_property("minimal", True)
def mean(x):
"""
Returns the mean of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
return np.mean(x)
@set_property("fctype", "simple")
@set_property("minimal", True)
def length(x):
"""
Returns the length of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: int
"""
return len(x)
@set_property("fctype", "simple")
@set_property("minimal", True)
def standard_deviation(x):
"""
Returns the standard deviation of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
return np.std(x)
@set_property("fctype", "simple")
def variation_coefficient(x):
"""
Returns the variation coefficient (standard error / mean, give relative value of variation around mean) of x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
mean = np.mean(x)
if mean != 0:
return np.std(x) / mean
else:
return np.nan
@set_property("fctype", "simple")
@set_property("minimal", True)
def variance(x):
"""
Returns the variance of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
return np.var(x)
@set_property("fctype", "simple")
@set_property("input", "pd.Series")
def skewness(x):
"""
Returns the sample skewness of x (calculated with the adjusted Fisher-Pearson standardized
moment coefficient G1).
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if not isinstance(x, pd.Series):
x = pd.Series(x)
return pd.Series.skew(x, skipna=False)
@set_property("fctype", "simple")
@set_property("input", "pd.Series")
def kurtosis(x):
"""
Returns the kurtosis of x (calculated with the adjusted Fisher-Pearson standardized
moment coefficient G2).
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if not isinstance(x, pd.Series):
x = pd.Series(x)
return pd.Series.kurtosis(x)
@set_property("fctype", "simple")
@set_property("minimal", True)
def root_mean_square(x):
"""
Returns the root mean square (rms) of the time series.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
return np.sqrt(np.mean(np.square(x))) if len(x) > 0 else np.NaN
@set_property("fctype", "simple")
def absolute_sum_of_changes(x):
"""
Returns the sum over the absolute value of consecutive changes in the series x
.. math::
\\sum_{i=1, \\ldots, n-1} \\mid x_{i+1}- x_i \\mid
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
return np.sum(np.abs(np.diff(x)))
@set_property("fctype", "simple")
def longest_strike_below_mean(x):
"""
Returns the length of the longest consecutive subsequence in x that is smaller than the mean of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return np.max(_get_length_sequences_where(x < np.mean(x))) if x.size > 0 else 0
@set_property("fctype", "simple")
def longest_strike_above_mean(x):
"""
Returns the length of the longest consecutive subsequence in x that is bigger than the mean of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return np.max(_get_length_sequences_where(x > np.mean(x))) if x.size > 0 else 0
@set_property("fctype", "simple")
def count_above_mean(x):
"""
Returns the number of values in x that are higher than the mean of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
m = np.mean(x)
return np.where(x > m)[0].size
@set_property("fctype", "simple")
def count_below_mean(x):
"""
Returns the number of values in x that are lower than the mean of x
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
m = np.mean(x)
return np.where(x < m)[0].size
@set_property("fctype", "simple")
def last_location_of_maximum(x):
"""
Returns the relative last location of the maximum value of x.
The position is calculated relatively to the length of x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
x = np.asarray(x)
return 1.0 - np.argmax(x[::-1]) / len(x) if len(x) > 0 else np.NaN
@set_property("fctype", "simple")
def first_location_of_maximum(x):
"""
Returns the first location of the maximum value of x.
The position is calculated relatively to the length of x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return np.argmax(x) / len(x) if len(x) > 0 else np.NaN
@set_property("fctype", "simple")
def last_location_of_minimum(x):
"""
Returns the last location of the minimal value of x.
The position is calculated relatively to the length of x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
x = np.asarray(x)
return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN
@set_property("fctype", "simple")
def first_location_of_minimum(x):
"""
Returns the first location of the minimal value of x.
The position is calculated relatively to the length of x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if not isinstance(x, (np.ndarray, pd.Series)):
x = np.asarray(x)
return np.argmin(x) / len(x) if len(x) > 0 else np.NaN
@set_property("fctype", "simple")
def percentage_of_reoccurring_values_to_all_values(x):
"""
Returns the percentage of values that are present in the time series
more than once.
len(different values occurring more than once) / len(different values)
This means the percentage is normalized to the number of unique values,
in contrast to the percentage_of_reoccurring_datapoints_to_all_datapoints.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if len(x) == 0:
return np.nan
unique, counts = np.unique(x, return_counts=True)
if counts.shape[0] == 0:
return 0
return np.sum(counts > 1) / float(counts.shape[0])
@set_property("fctype", "simple")
@set_property("input", "pd.Series")
def percentage_of_reoccurring_datapoints_to_all_datapoints(x):
"""
Returns the percentage of non-unique data points. Non-unique means that they are
contained another time in the time series again.
# of data points occurring more than once / # of all data points
This means the ratio is normalized to the number of data points in the time series,
in contrast to the percentage_of_reoccurring_values_to_all_values.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
if len(x) == 0:
return np.nan
if not isinstance(x, pd.Series):
x = pd.Series(x)
value_counts = x.value_counts()
reoccuring_values = value_counts[value_counts > 1].sum()
if np.isnan(reoccuring_values):
return 0
return reoccuring_values / x.size
@set_property("fctype", "simple")
def sum_of_reoccurring_values(x):
"""
Returns the sum of all values, that are present in the time series
more than once.
For example
sum_of_reoccurring_values([2, 2, 2, 2, 1]) = 2
as 2 is a reoccurring value, so it is summed up with all