- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackml.py
More file actions
Latest commit
414 lines (296 loc) · 13.3 KB
/
Copy pathstackml.py
File metadata and controls
414 lines (296 loc) · 13.3 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# Basics
importnumpyasnp
importpandasaspd
importsklearnassk
fromtimeimporttime
importrandom
importpickle
fromcopyimportcopy, deepcopy
# Sklean Models
frommodelsimportregression_options, classification_options
# Training prep/scoring metrics
fromsklearn.model_selectionimportKFold, TimeSeriesSplit, GridSearchCV
fromsklearn.metricsimportr2_scoreasr2
# Model Persistance
fromsklearn.externalsimportjoblib
# Plotting
importplotly
importplotly.graph_objsasgo
fromplotly.graph_objsimportScatter, Layout
classStackML:
'''
Parameters:
----------------------------
cv_folds: int, default 3
'cv_folds' determines the number of CV folds Kfold or
TimeSeriesSplit will generate. It should be an int
'reuse_features' should be a string or a list of strings with the
name of columns that you want to add to the combiner model's
training set.
'shuffle' determined whether Kfold will shuffle the data before
generating CV indices. It should be True or False.
'timeseries' determines wich CV folding algorithm to use.
True --> TimeSeriesSplit, False --> Kfold
'base_models' can be 'all' or a list of models to use as the base
models in the ensemble.
'combiner' should be a string
Returns:
----------------------------
'''
def__init__(self,
cv_folds=3,
shuffle=False,
verbose=False,
timeseries=False,
base_models='all',
use_best_model=True,
reuse_features=None,
combiner='MLPRegressor',
discard_overfitting_base_models=True,
):
self.verbose=verbose
self.discard=discard_overfitting_base_models
# Kfold index generator parameters
self.shuffle=shuffle
self.cv_folds=cv_folds
self.cv_indices= {'train':[], 'test':[]}
self.timeseries=timeseries
model_options=copy(regression_options)
formodelinmodel_options:
model_options[model]['info'] = {'RMSE_train':[], 'RMSE_test':[]}
ifbase_models=='all':
self.base_models=model_options
else:
base_models= [base_models]
ifisinstance(combiner, str):
ifcombinernotinmodel_options:
raiseKeyError(f'''
The combiner model should either be a dict with a
callable model or one of the following string options:
{model_options.keys()}
''')
else:
self.combiner= {
'model' : copy(model_options[combiner]['model']),
'name' : model_options[combiner]['name'] +'_combiner',
'info' : {'RMSE_train':[], 'RMSE_test':[]}
}
elifisinstance(combiner, dict):
self.combiner=combiner
else:
self.combiner=None
self.reuse_features=reuse_features
deffit(self, Xtrain, ytrain):
self.Xtrain=Xtrain
self.ytrain=ytrain
# Initialize cross validation index generator
ifself.timeseries:
cv_splitter=TimeSeriesSplit(n_splits=self.cv_folds)
else:
cv_splitter=KFold(n_splits=self.cv_folds,
shuffle=self.shuffle,
random_state=1)
def_CV_stats(model_dict, CV_Xtrain, CV_Xtest,
CV_Ytrain, CV_Ytest):
model=model_dict['model']
train_score=round(model.score(CV_Xtrain, CV_Ytrain), 4)
test_score=round(model.score(CV_Xtest, CV_Ytest), 4)
model_dict['info']['RMSE_train'].append(train_score)
model_dict['info']['RMSE_test'].append(test_score)
ifself.verbose:
msg=f'Train score: {train_score} || Test score: {test_score}'
print(msg, '\n')
def_train_base_models():
ifself.verbose:
print('\nTraining Base Models')
print('-------------------------------------------------')
iteration=1
fortrain_inds, test_indsincv_splitter.split(self.Xtrain):
ifself.verbose:
print(f'\nCV fold: {iteration}')
print('---------------------------')
# Log CV index info
self.cv_indices['train'].append(train_inds)
self.cv_indices['test'].append(test_inds)
# Slice CV sets
CV_Xtrain=self.Xtrain.iloc[train_inds, :]
CV_Ytrain=self.ytrain.iloc[train_inds]
CV_Xtest=self.Xtrain.iloc[test_inds, :]
CV_Ytest=self.ytrain.iloc[test_inds]
# Train, save CV performance stats
formodel_name, model_dictinself.base_models.items():
t=time()
model_dict['model'].fit(CV_Xtrain, CV_Ytrain)
ifself.verbose:
print(f'{model_name}: {round(time() -t, 4)}s')
_CV_stats(model_dict, CV_Xtrain, CV_Xtest,
CV_Ytrain, CV_Ytest)
iteration+=1
ifself.discard:
formodelinlist(self.base_models.keys()):
score=self.base_models[model]['info']['RMSE_test'][-1]
ifscore<.60:
self.base_models.pop(model)
ifself.verbose:
print(f'---- Dropped {model} ----')
def_train_combiner():
# Compile Predictions from base models into features for
# training the Neural Network
# Restarting index generator
ifself.timeseries:
cv_splitter=TimeSeriesSplit(n_splits=self.cv_folds)
else:
cv_splitter=KFold(n_splits=self.cv_folds,
shuffle=self.shuffle,
random_state=1)
# Obtain combiner model features using predictions from base models
self.combiner_features=self._ensemble_features(self.Xtrain)
ifself.verbose:
print('\nTraining Combiner')
print('-------------------------------------------------')
# Train combiner with base model predictions
iteration=1
fortrain_inds, test_indsincv_splitter.split(self.combiner_features):
model_name=self.combiner['name']
CV_Xtrain=self.combiner_features.iloc[train_inds, :]
CV_Xtest=self.combiner_features.iloc[test_inds, :]
CV_Ytrain=self.ytrain.iloc[train_inds]
CV_Ytest=self.ytrain.iloc[test_inds]
ifself.verbose:
print(f'CV fold {iteration}')
t=time()
# Train, save CV performance stats
self.combiner['model'].fit(CV_Xtrain, CV_Ytrain)
ifself.verbose:
print(f'{model_name}: {round(time() -t, 4)}s')
_CV_stats(self.combiner, CV_Xtrain, CV_Xtest,
CV_Ytrain, CV_Ytest)
iteration+=1
_train_base_models()
ifself.combiner:
_train_combiner()
def_ensemble_features(self, data):
# Given a set of base model predictions, return features for the combiner model
combiner_features=pd.DataFrame(columns=self.base_models.keys())
it=0
formodelinself.base_models.keys():
tempPred=self.base_models[model]['model'].predict(data)
combiner_features[model] =tempPred
it+=1
ifself.reuse_features:
tempData=data[self.reuse_features].reset_index(drop=True)
combiner_features=pd.concat([combiner_features, tempData], axis=1)
returncombiner_features
defscore(self, Xtest, ytest, model='combiner'):
# Return R2 score of model on test set
self.Xtest=Xtest
self.ytest=ytest
assertself.ytestisnotNone, \
'Tried to score model with saved test data, but no test data was found'
iflen(self.base_models) ==1andself.combiner==None:
mod=list(self.base_models.keys())[0]
returnself.base_models[mod]['model'].score(self.Xtest, self.ytest)
elifmodel=='combiner':
assertself.combiner, \
'Attempted to score with combiner model but no combiner model was found'
self.combiner_features=self._ensemble_features(self.Xtest)
returnself.combiner['model'].score(self.combiner_features, self.ytest)
else:
assertmodelinself.base_models.keys(), \
'Attempted to score {} but {} was not found in base models'.format(model)
returnself.base_models[model]['model'].score(self.Xtest, self.ytest)
defpredict(self, X, model='combiner'):
# Given X, obtain combiner features from base model predictions,
# then return prediction from combiner
iflen(self.base_models) ==1andself.combiner==None:
returnself.base_models[list(self.base_models.keys())[0]]['model'].predict(X)
elifmodel=='combiner':
assertself.combiner, \
'Attempted to make a prediction with combiner model but no combiner model was found'
self.combiner_features=self._ensemble_features(X)
returnself.combiner['model'].predict(self.combiner_features)
else:
assertmodelinself.base_models.keys(), \
'Attempted to predict with {} but {} was not found in base models'.format(model)
returnself.base_models[model]['model'].predict(X)
defplot_prediction(self,
filename=None,
auto_open=False,
data=None,
x_axis_data=None):
'''
plot_prediction will automatically generate a plot of model predictions
vs. actual values using self.Xtest and self.ytest, or, it can take a
dictionary of prediction data and generate a custom plot. It will output
an .html file at a given directory/filename, and automatically open a
browser and display the plot if auto_open == True.
- 'filename' should be a string with the name of the file, without file
extension, in the form 'dir/dir.../filename'
- x_axis should be the name of the column to use as
- 'auto_open' toggles whether to open the browser
- 'data' should at a minimum be a dictionary in the form of:
{'predictions':<pd.Series>, 'actual':<pd.Series>}
or with optional metadata:
{'predictions':<pd.Series>, 'predictions_name':'<somestring>',
'actual':<pd.Series>, 'actual_name':'<somestring>',
'y_label':'<somestring>', 'x_label':'<somestring>',
'x_data': <pd.Series>, 'plot_title':'<somestring>', }
'''
predicted_price=self.predict(self.Xtest)
actual_price=self.ytest
ifx_axis_data:
iftype(x_axis_data) ==str:
x_data=self.Xtest[x_axis_data]
else:
assertlen(x_axis_data) ==len(self.Xtrain.index), \
"lengths of x_axis_data and training data are mismatched"
x_data=x_axis_data
else:
x_data=None
Actual=Scatter(
x=x_data,
y=actual_price,
name='Actual Values'
)
Prediction=Scatter(
x=x_data,
y=predicted_price,
name='Model Predictions'
)
layout=go.Layout(
title='Model Predictions vs. Actual'
)
iffilename:
filename=f'./plots/{filename}.html'
else:
filename='./plots/plot.html'
plotData= [Actual, Prediction]
plotly.offline.plot({'data': plotData,
'layout': layout},
filename=filename,
auto_open=auto_open
)
defsave_model(self, path='./model/saved_models/', f_name='saved_model'):
# Don't save data with model if selected
ifnotself.keep_data:
self.Xtrain=None
self.ytrain=None
self.Xtest=None
self.ytest=None
withopen(path+f_name+'.sav', 'wb') asfo:
pickle.dump(self, fo)
defexport_data(self, f_name, path='./model/saved_data/{}'):
iff_name[len(path)-4:] !='.sav':
f_name=f_name+'.sav'
data= {'Xtrain': self.Xtrain,
'Ytrain': self.ytrain,
'Xtest': self.Xtest,
'Ytest': self.ytest}
loc=path.format(f_name)
withopen(loc, 'wb') asfo:
pickle.dump(data, fo)
defload_model(path):
# loaded_model = joblib.load(path)
withopen(path, 'rb') asfo:
loaded_model=pickle.load(fo)
returnloaded_model