forked from AlexWarembourg/Medium
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeatures_utils.py
More file actions
310 lines (232 loc) · 10.9 KB
/
features_utils.py
File metadata and controls
310 lines (232 loc) · 10.9 KB
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
from pyspark.sql.types import *
import pyspark.sql.functions as F
from pyspark.sql import Window
import sys
from pyspark.sql.functions import udf
from functools import reduce
from pyspark.ml.pipeline import Transformer
from pyspark.ml.linalg import Vectors, VectorUDT
import numpy as np
#if spark version < 2.2
get_weekday = F.udf(lambda ts: int(ts.strftime('%w')), IntegerType())
@udf(VectorUDT())
def toSparseVector(index, values):
day_list_index, qty_list_values = zip(*sorted(zip(index, values)))
#367 for bisextile year (1 to 366 +1)
return Vectors.sparse(366, day_list_index, qty_list_values)
@udf(FloatType())
def getReference(currentDay, referenceDay):
#get the reference values
try :
if currentDay in referenceDay.indices :
return float(referenceDay.values[np.where(referenceDay.indices == currentDay)])
except AttributeError :
#case when indices is None it'll return no indices
return None
#define 2 windows to be sure to catch at decent amount of reference
windows = [7,14,21]
#loop over windows if the previous year reference doesnt exist
for window in windows:
#catch every day between the span
in_range_values = referenceDay.values[np.where((referenceDay.indices >= currentDay - window) \
& (referenceDay.indices <= currentDay + window+1))]
#check how many values there's in range
common_count = len(in_range_values)
#if there's more than 1 do the mean
if common_count > 0 :
try :
return float((sum(in_range_values) / common_count))
#except none value error
except AttributeError :
in_range_values = [x for x in in_range_values if ~np.isnan(x)]
return float((sum(in_range_values) / common_count))
class VivaldiExtractor(Transformer):
def __init__(self, inputCol='month', outputCol='season'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("VivaldiExtractor"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != IntegerType()):
raise Exception('seasonExtractor input type %s did not match input type IntegerType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol,
F.when((df[self.inputCol] >= 3), "Spring")
.otherwise(F.when((df[self.inputCol] >= 5), "Summer")
.otherwise(F.when((df[self.inputCol] <= 9 ), "fall")
.otherwise("Winter"))))
class MonthQuarterExtractor(Transformer):
def __init__(self, inputCol='day', outputCol='monthquarter'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("MonthQuarterExtractor"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != IntegerType()):
raise Exception('monthQuarterExtractor input type %s did not match input type IntegerType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol, F.when((df[self.inputCol] <= 8), 0)
.otherwise(F.when((df[self.inputCol] <= 16), 1)
.otherwise(F.when((df[self.inputCol] <= 24), 2)
.otherwise(3))))
class DayExtractor(Transformer):
def __init__(self, inputCol, outputCol='day'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("DayExtractor"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != DateType()):
raise Exception('DayExtractor input type %s did not match input type DateType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol, F.dayofmonth(df[self.inputCol]))
class MonthExtractor(Transformer):
def __init__(self, inputCol, outputCol='month'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("MonthExtractor"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != DateType()):
raise Exception('MonthExtractor input type %s did not match input type DateType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol, F.month(df[self.inputCol]))
class YearExtractor(Transformer):
def __init__(self, inputCol, outputCol='year'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("YearExtractor"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != DateType()):
raise Exception('YearExtractor input type %s did not match input type DateType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol, F.year(df[self.inputCol]))
class WeekDayExtractor(Transformer):
def __init__(self, inputCol, outputCol='weekday'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("WeekDayExtractor"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != DateType()):
raise Exception('WeekDayExtractor input type %s did not match input type DateType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol, get_weekday(F.col(self.inputCol)))
class WeekendExtractor(Transformer):
def __init__(self, inputCol='weekday', outputCol='weekend'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("WeekendExtractor"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != IntegerType()):
raise Exception('WeekendExtractor input type %s did not match input type IntegerType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol, F.when(((df[self.inputCol] == 5) | (df[self.inputCol] == 6)), 1).otherwise(0))
class MonthBeginExtractor(Transformer):
def __init__(self, inputCol='day', outputCol='monthbegin'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("MonthBeginExtractor"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != IntegerType()):
raise Exception('MonthBeginExtractor input type %s did not match input type IntegerType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol, F.when((df[self.inputCol] <= 7), 1).otherwise(0))
class MonthEndExtractor(Transformer):
def __init__(self, inputCol='day', outputCol='monthend'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("MonthEndExtractor"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != IntegerType()):
raise Exception('MonthEndExtractor input type %s did not match input type IntegerType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol, F.when((df[self.inputCol] >= 24), 1).otherwise(0))
class YearQuarterExtractor(Transformer):
def __init__(self, inputCol='month', outputCol='yearquarter'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("YearQuarterExtractor"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != IntegerType()):
raise Exception('YearQuarterExtractor input type %s did not match input type IntegerType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol, F.when((df[self.inputCol] <= 3), 0)
.otherwise(F.when((df[self.inputCol] <= 6), 1)
.otherwise(F.when((df[self.inputCol] <= 9), 2)
.otherwise(3))))
class YearDayExtractor(Transformer):
def __init__(self, inputCol, outputCol='yearday'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("YearDayExtractor"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != DateType()):
raise Exception('YearDayExtractor input type %s did not match input type DateType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol, F.dayofyear(F.col(self.inputCol)))
class LogTarget(Transformer):
def __init__(self, inputCol="F_TOTAL_QTY", outputCol='F_TOTAL_QTY'):
self.inputCol = inputCol
self.outputCol = outputCol
def this():
this(Identifiable.randomUID("LogTarget"))
def copy(extra):
defaultCopy(extra)
def check_input_type(self, schema):
field = schema[self.inputCol]
if (field.dataType != IntegerType()):
raise Exception('LogTarget input type %s did not match input type IntegerType' % field.dataType)
def _transform(self, df):
self.check_input_type(df.schema)
return df.withColumn(self.outputCol, F.log1p(F.col(self.inputCol)))