This repository has been archived by the owner on Jun 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 170
/
Copy pathmodels.py
208 lines (173 loc) · 8.3 KB
/
models.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
from attrdict import AttrDict
from deepsense import neptune
import lightgbm as lgb
import numpy as np
import pandas as pd
from sklearn.externals import joblib
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from steppy.base import BaseTransformer
from toolkit.sklearn_transformers.models import SklearnClassifier
import xgboost as xgb
from .utils import get_logger
logger = get_logger()
ctx = neptune.Context()
class XGBoost(BaseTransformer):
def __init__(self, **params):
super().__init__()
logger.info('initializing XGBoost...')
self.params = params
self.training_params = ['nrounds', 'early_stopping_rounds']
self.evaluation_function = None
@property
def model_config(self):
return AttrDict({param: value for param, value in self.params.items()
if param not in self.training_params})
@property
def training_config(self):
return AttrDict({param: value for param, value in self.params.items()
if param in self.training_params})
def fit(self,
X, y,
X_valid, y_valid,
feature_names=None,
feature_types=None,
**kwargs):
train = xgb.DMatrix(X,
label=y,
feature_names=feature_names,
feature_types=feature_types)
valid = xgb.DMatrix(X_valid,
label=y_valid,
feature_names=feature_names,
feature_types=feature_types)
evaluation_results = {}
self.estimator = xgb.train(params=self.model_config,
dtrain=train,
evals=[(train, 'train'), (valid, 'valid')],
evals_result=evaluation_results,
num_boost_round=self.training_config.nrounds,
early_stopping_rounds=self.training_config.early_stopping_rounds,
verbose_eval=self.model_config.verbose,
feval=self.evaluation_function)
return self
def transform(self, X, y=None, feature_names=None, feature_types=None, **kwargs):
X_DMatrix = xgb.DMatrix(X,
label=y,
feature_names=feature_names,
feature_types=feature_types)
prediction = self.estimator.predict(X_DMatrix)
return {'prediction': prediction}
def load(self, filepath):
self.estimator = xgb.Booster(params=self.model_config)
self.estimator.load_model(filepath)
return self
def persist(self, filepath):
self.estimator.save_model(filepath)
class LightGBM(BaseTransformer):
def __init__(self, name=None, **params):
super().__init__()
logger.info('initializing LightGBM...')
self.params = params
self.training_params = ['number_boosting_rounds', 'early_stopping_rounds']
self.evaluation_function = None
self.callbacks = callbacks(channel_prefix=name)
@property
def model_config(self):
return AttrDict({param: value for param, value in self.params.items()
if param not in self.training_params})
@property
def training_config(self):
return AttrDict({param: value for param, value in self.params.items()
if param in self.training_params})
def fit(self,
X,
y,
X_valid,
y_valid,
feature_names='auto',
categorical_features='auto',
**kwargs):
evaluation_results = {}
self._check_target_shape_and_type(y, 'y')
self._check_target_shape_and_type(y_valid, 'y_valid')
y = self._format_target(y)
y_valid = self._format_target(y_valid)
logger.info('LightGBM, train data shape {}'.format(X.shape))
logger.info('LightGBM, validation data shape {}'.format(X_valid.shape))
logger.info('LightGBM, train labels shape {}'.format(y.shape))
logger.info('LightGBM, validation labels shape {}'.format(y_valid.shape))
data_train = lgb.Dataset(data=X,
label=y,
feature_name=feature_names,
categorical_feature=categorical_features,
**kwargs)
data_valid = lgb.Dataset(X_valid,
label=y_valid,
feature_name=feature_names,
categorical_feature=categorical_features,
**kwargs)
self.estimator = lgb.train(self.model_config,
data_train,
feature_name=feature_names,
categorical_feature=categorical_features,
valid_sets=[data_train, data_valid],
valid_names=['data_train', 'data_valid'],
evals_result=evaluation_results,
num_boost_round=self.training_config.number_boosting_rounds,
early_stopping_rounds=self.training_config.early_stopping_rounds,
verbose_eval=self.model_config.verbose,
feval=self.evaluation_function,
callbacks=self.callbacks,
**kwargs)
return self
def transform(self, X, **kwargs):
prediction = self.estimator.predict(X)
return {'prediction': prediction}
def load(self, filepath):
self.estimator = joblib.load(filepath)
return self
def persist(self, filepath):
joblib.dump(self.estimator, filepath)
def _check_target_shape_and_type(self, target, name):
if not any([isinstance(target, obj_type) for obj_type in [pd.Series, np.ndarray, list]]):
raise TypeError(
'"target" must be "numpy.ndarray" or "Pandas.Series" or "list", got {} instead.'.format(type(target)))
try:
assert len(target.shape) == 1, '"{}" must be 1-D. It is {}-D instead.'.format(name,
len(target.shape))
except AttributeError:
print('Cannot determine shape of the {}. '
'Type must be "numpy.ndarray" or "Pandas.Series" or "list", got {} instead'.format(name,
type(target)))
def _format_target(self, target):
if isinstance(target, pd.Series):
return target.values
elif isinstance(target, np.ndarray):
return target
elif isinstance(target, list):
return np.array(target)
else:
raise TypeError(
'"target" must be "numpy.ndarray" or "Pandas.Series" or "list", got {} instead.'.format(type(target)))
def get_sklearn_classifier(ClassifierClass, normalize, **kwargs):
class SklearnBinaryClassifier(SklearnClassifier):
def transform(self, X, y=None, target=1, **kwargs):
prediction = self.estimator.predict_proba(X)[:, target]
return {SklearnClassifier.RESULT_KEY: prediction}
if normalize:
return SklearnBinaryClassifier(Pipeline([('standarizer', StandardScaler()),
('classifier', ClassifierClass(**kwargs))]))
return SklearnBinaryClassifier(ClassifierClass(**kwargs))
def callbacks(channel_prefix):
neptune_monitor = neptune_monitor_lgbm(channel_prefix)
return [neptune_monitor]
def neptune_monitor_lgbm(channel_prefix=''):
def callback(env):
for name, loss_name, loss_value, _ in env.evaluation_result_list:
if channel_prefix != '':
channel_name = '{}_{}_{}'.format(channel_prefix, name, loss_name)
else:
channel_name = '{}_{}'.format(name, loss_name)
ctx.channel_send(channel_name, x=env.iteration, y=loss_value)
return callback