-
Notifications
You must be signed in to change notification settings - Fork 5
/
NpSplineTransformer.py
181 lines (142 loc) · 6.52 KB
/
NpSplineTransformer.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
from utils.stats import _weighted_percentile
import numpy as np
import numexpr as ne
#This is CPU version
def _interpolate(X, Aug, base_knots, M):
basis = np.ones((base_knots.shape[1] - 2) + 2 * M - 1)
basis[Aug[1:] == Aug[:-1]] = 0
B = np.repeat(np.expand_dims(basis, axis=0), len(X), axis=0)
B = ((Aug <= X[:, 0][:, np.newaxis])[:, :-1] & (Aug > X[:, 0][:, np.newaxis])[:, 1:]) * B
for i in range(1, M):
aug1 = Aug[:-i - 1]
aug2 = Aug[i:-1]
temp1 = ne.evaluate("(X - aug1) / (aug2 - aug1)")
temp1[:, aug1 == aug2] = 0
aug1 = Aug[i + 1:]
aug2 = Aug[1:-i]
temp2 = ne.evaluate("(aug1 - X) / (aug1 - aug2)")
temp2[:, aug1 == aug2] = 0
B1 = B[:, :-1]
B2 = B[:, 1:]
B = ne.evaluate("temp1 * B1 + temp2 * B2")
return B
class NpSplineTransformer():
def __init__(self, n_knots=5, degree=3, knots="uniform", extrapolation="constant"):
self.n_knots = n_knots
self.degree = degree
self.knots = knots
self.M = degree + 1
self.extrapolation = extrapolation
def _get_base_knot_positions(self, X, n_knots=10, knots="uniform", sample_weight=None):
if knots == "quantile":
percentiles = 100 * np.linspace(start=0, stop=1, num=n_knots, dtype=np.float64)
if sample_weight is None:
knots = np.percentile(X, percentiles, axis=0)
else:
knots = np.array(
[
_weighted_percentile(X, sample_weight, percentile)
for percentile in percentiles
]
)
else:
mask = slice(None, None, 1) if sample_weight is None else sample_weight > 0
x_min = np.amin(X[mask], axis=0)
x_max = np.amax(X[mask], axis=0)
knots = np.linspace(
start=x_min,
stop=x_max,
num=n_knots,
endpoint=True,
dtype=np.float64,
)
return knots
def fit(self, X, sample_weight=None):
degree = self.degree
if isinstance(self.knots, str) and self.knots in ["uniform", "quantile", ]:
base_knots = self._get_base_knot_positions(
X,
n_knots=self.n_knots,
knots=self.knots,
sample_weight=sample_weight
)
elif isinstance(self.knots, np.ndarray):
base_knots = self.knots
else:
raise ValueError("knots = [\"uniform\", \"quantile\"] or a ndarray.")
if self.extrapolation == "periodic":
period = base_knots[-1] - base_knots[0]
knots = np.r_[
base_knots[-(degree + 1): -1] - period,
base_knots,
base_knots[1: (degree + 1)] + period,
]
else:
dist_min = base_knots[1] - base_knots[0]
dist_max = base_knots[-1] - base_knots[-2]
knots = np.r_[
np.linspace(
base_knots[0] - degree * dist_min,
base_knots[0] - dist_min,
num=degree,
),
base_knots,
np.linspace(
base_knots[-1] + dist_max,
base_knots[-1] + degree * dist_max,
num=degree,
),
]
self.base_knots = base_knots.T
self.Augment = knots.T
def transform(self, X):
n_samples, n_features = X.shape
n_splines = self.base_knots.shape[1] + self.degree - 1
XBS = np.zeros((n_samples, n_splines * n_features))
if self.extrapolation == "error":
for i in range(n_features):
temp_X = X[:, i][:, np.newaxis]
if np.any((temp_X > self.base_knots[i, -1]) | (temp_X < self.base_knots[i, 0])):
raise ValueError("X contains values beyond the limits of the knots.")
else:
XBS[:, i * n_splines:(i + 1) * n_splines] = _interpolate(temp_X, self.Augment[i], self.base_knots,
self.M)
elif self.extrapolation == "constant":
for i in range(n_features):
temp_X = X[:, i][:, np.newaxis]
XBS[:, i * n_splines:(i + 1) * n_splines] = _interpolate(temp_X, self.Augment[i], self.base_knots,
self.M)
f_min = _interpolate(np.array([self.base_knots[i, 0]])[:, np.newaxis], self.Augment[i], self.base_knots,
self.M)[0]
f_max = \
_interpolate(np.array([self.base_knots[i, -1]])[:, np.newaxis], self.Augment[i], self.base_knots,
self.M)[0]
mask = X[:, i] < self.base_knots[i, 0]
if np.any(mask):
XBS[mask, (i * n_splines): (i * n_splines + self.degree)] = f_min[
:self.degree
]
mask = X[:, i] > self.base_knots[i, -1]
if np.any(mask):
XBS[
mask,
((i + 1) * n_splines - self.degree): ((i + 1) * n_splines),
] = f_max[-self.degree:]
elif self.extrapolation == "periodic":
n_p_splines = self.base_knots.shape[1] - 1
n = self.Augment.shape[1] - self.degree - 1
for i in range(n_features):
x = (self.Augment[i][self.degree] + (X[:, i] - self.Augment[i][self.degree]) % (
self.Augment[i][n] - self.Augment[i][self.degree]
))[:, np.newaxis]
XBS[:, i * n_splines:(i + 1) * n_splines] = _interpolate(x, self.Augment[i], self.base_knots, self.M)
XBS[:, :n_splines - n_p_splines] = XBS[:, :n_splines - n_p_splines] + XBS[:, n_p_splines:]
XBS = XBS[:, :n_p_splines]
elif self.extrapolation == "linear":
i = 0
_interpolate(X, self.Augment[i], self.base_knots, self.M)
return
return XBS
def fit_transform(self, X):
self.fit(X)
return self.transform(X)