-
Notifications
You must be signed in to change notification settings - Fork 2
/
preprocessors.py
190 lines (136 loc) · 5.54 KB
/
preprocessors.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
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from regression_model.processing import errors
# categorical missing value imputer
class CategoricalImputer(BaseEstimator, TransformerMixin):
def __init__(self, variables=None):
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y=None):
# we need the fit statement to accomodate the sklearn pipeline
return self
def transform(self, X):
X = X.copy()
for feature in self.variables:
X[feature] = X[feature].fillna('Missing')
return X
# Numerical missing value imputer
class NumericalImputer(BaseEstimator, TransformerMixin):
def __init__(self, variables=None):
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y=None):
# persist mode in a dictionary
self.imputer_dict_ = {}
for feature in self.variables:
self.imputer_dict_[feature] = X[feature].mode()[0]
return self
def transform(self, X):
X = X.copy()
for feature in self.variables:
X[feature].fillna(self.imputer_dict_[feature], inplace=True)
return X
# Temporal variable calculator
class TemporalVariableEstimator(BaseEstimator, TransformerMixin):
def __init__(self, variables=None, reference_variable=None):
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
self.reference_variables = reference_variable
def fit(self, X, y=None):
# we need this step to fit the sklearn pipeline
return self
def transform(self, X):
X = X.copy()
for feature in self.variables:
X[feature] = X[self.reference_variables] - X[feature]
return X
# frequent label categorical encoder
class RareLabelCategoricalEncoder(BaseEstimator, TransformerMixin):
def __init__(self, tol=0.05, variables=None):
self.tol = tol
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y=None):
# persist frequent labels in dictionary
self.encoder_dict_ = {}
for var in self.variables:
# the encoder will learn the most frequent categories
t = pd.Series(X[var].value_counts() / np.float(len(X)))
# frequent labels:
self.encoder_dict_[var] = list(t[t >= self.tol].index)
return self
def transform(self, X):
X = X.copy()
for feature in self.variables:
X[feature] = np.where(X[feature].isin(self.encoder_dict_[feature]), X[feature], 'Rare')
return X
# string to numbers categorical encoder
class CategoricalEncoder(BaseEstimator, TransformerMixin):
def __init__(self, variables=None):
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y):
temp = pd.concat([X, y], axis=1)
temp.columns = list(X.columns) + ['target']
# persist transforming dictionary
self.encoder_dict_ = {}
for var in self.variables:
t = temp.groupby([var])['target'].mean().sort_values(ascending=True).index
self.encoder_dict_[var] = {k: i for i, k in enumerate(t, 0)}
return self
def transform(self, X):
# encode labels
X = X.copy()
for feature in self.variables:
X[feature] = X[feature].map(self.encoder_dict_[feature])
# check if transformer introduces NaN
if X[self.variables].isnull().any().any():
null_counts = X[self.variables].isnull().any()
vars_ = {key: value for (key, value) in null_counts.items()
if value is True}
raise errors.InvalidModelInputError(
f'Categorical encoder has introduced NaN when '
f'transforming categorical variables: {vars_.keys()}')
return X
# logarithm transformer
class LogTransformer(BaseEstimator, TransformerMixin):
def __init__(self, variables=None):
if not isinstance(variables, list):
self.variables = [variables]
else:
self.variables = variables
def fit(self, X, y=None):
# to accomodate the pipeline
return self
def transform(self, X):
X = X.copy()
# check that the values are non-negative for log transform
if not (X[self.variables] > 0).all().all():
vars_ = self.variables[(X[self.variables] <= 0).any()]
raise errors.InvalidModelInputError(
f"Variables contain zero or negative values, "
f"can't apply log for vars: {vars_}")
for feature in self.variables:
X[feature] = np.log(X[feature])
return X
class DropUnecessaryFeatures(BaseEstimator, TransformerMixin):
def __init__(self, variables_to_drop=None):
self.variables = variables_to_drop
def fit(self, X, y=None):
return self
def transform(self, X):
# encode labels
X = X.copy()
X = X.drop(self.variables, axis=1)
return X