-
Notifications
You must be signed in to change notification settings - Fork 89
/
slope.py
145 lines (115 loc) · 4.46 KB
/
slope.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
"""Slope transformer."""
__all__ = ["SlopeTransformer"]
__author__ = ["mloning"]
import math
import numpy as np
from aeon.transformations._split import SplitsTimeSeries
from aeon.transformations.collection import BaseCollectionTransformer
class SlopeTransformer(BaseCollectionTransformer, SplitsTimeSeries):
"""Piecewise slope transformation.
Class to perform a slope transformation on a collection of time series.
Numpy array of shape (n_instances, n_channels, series_length) is
transformed to numpy array of shape (n_instances, n_channels, n_intervals).
The new feature is the slope over that interval found using a
total least squares regression (note that total least squares is different
from ordinary least squares regression.)
Parameters
----------
n_intervals : int, number of approx equal segments
to split the time series into.
Examples
--------
>>> import numpy as np
>>> from aeon.transformations.collection.slope import SlopeTransformer
>>> X = np.array([[[4, 6, 10, 12, 8, 6, 5, 5]]])
>>> s = SlopeTransformer(n_intervals=2)
>>> res = s.fit_transform(X)
"""
_tags = {
"capability:multivariate": True,
"fit_is_empty": True,
}
def __init__(self, n_intervals=8):
self.n_intervals = n_intervals
super(SlopeTransformer, self).__init__()
def _transform(self, X, y=None):
"""Transform X and return a transformed version.
private _transform containing core logic, called from transform
Parameters
----------
X : 3D np.ndarray of shape = [n_instances, n_channels, series_length]
collection of time series to transform
y : ignored argument for interface compatibility
Returns
-------
3D np.ndarray of shape = [n_instances, n_channels, series_length]
collection of time series to transform
"""
# Get information about the dataframe
n_cases, n_channels, series_length = X.shape
self._check_parameters(series_length)
full_data = []
for i in range(n_cases):
case_data = []
for j in range(n_channels):
# Calculate gradients
res = [self._get_gradient(x) for x in self._split(X[i][j])]
case_data.append(res)
full_data.append(np.asarray(case_data))
return np.array(full_data)
def _get_gradient(self, Y):
"""Get gradient of lines.
Function to get the gradient of the line of best fit given a
section of a time series.
Equation adopted from:
real-statistics.com/regression/total-least-squares
Parameters
----------
Y : a numpy array of shape = [interval_size]
Returns
-------
m : an int corresponding to the gradient of the best fit line.
"""
# Create an array that contains 1,2,3,...,len(Y) for the x coordinates.
X = np.arange(1, len(Y) + 1)
# Calculate the mean of both arrays
meanX = np.mean(X)
meanY = np.mean(Y)
# Calculate (yi-mean(y))^2
yminYbar = (Y - meanY) ** 2
# Calculate (xi-mean(x))^2
xminXbar = (X - meanX) ** 2
# Sum them to produce w.
w = np.sum(yminYbar) - np.sum(xminXbar)
# Sum (xi-mean(x))*(yi-mean(y)) and multiply by 2 to calculate r
r = 2 * np.sum((X - meanX) * (Y - meanY))
if r == 0:
# remove nans
m = 0
else:
# Gradient is defined as (w+sqrt(w^2+r^2))/r
m = (w + math.sqrt(w**2 + r**2)) / r
return m
def _check_parameters(self, n_timepoints):
"""Check values of parameters for Slope transformer.
Throws
------
ValueError or TypeError if a parameters input is invalid.
"""
if isinstance(self.n_intervals, int):
if self.n_intervals <= 0:
raise ValueError(
"num_intervals must have the value \
of at least 1"
)
if self.n_intervals > n_timepoints:
raise ValueError(
"num_intervals cannot be higher than \
subsequence_length"
)
else:
raise TypeError(
"num_intervals must be an 'int'. Found '"
+ type(self.n_intervals).__name__
+ "'instead."
)