-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathregression.py
More file actions
364 lines (298 loc) · 13.3 KB
/
regression.py
File metadata and controls
364 lines (298 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
import random
import warnings
warnings.filterwarnings('ignore')
from multiprocessing import cpu_count
from sklearn.base import BaseEstimator
from sklearn.base import is_classifier
from sklearn.base import RegressorMixin
from sklearn.base import ClassifierMixin
from sklearn.kernel_ridge import KernelRidge
from sklearn.svm import SVR, NuSVR, LinearSVR
from sklearn.tree import DecisionTreeRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import ParameterSampler
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.neighbors import RadiusNeighborsRegressor, KNeighborsRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel, DotProduct, WhiteKernel
from sklearn.ensemble import AdaBoostRegressor, ExtraTreesRegressor, RandomForestRegressor
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet, Lars, LassoLars, OrthogonalMatchingPursuit, BayesianRidge, ARDRegression, SGDRegressor, PassiveAggressiveRegressor, RANSACRegressor, HuberRegressor
from sklearn.ensemble import GradientBoostingRegressor
from hunga_bunga.core import *
from hunga_bunga.params import *
linear_models_n_params = [
(LinearRegression, {'normalize': normalize}),
(Ridge,
{'alpha': alpha, 'normalize': normalize, 'tol': tol,
'solver': ['svd', 'cholesky', 'lsqr', 'sparse_cg', 'sag']
}),
(Lasso,
{'alpha': alpha, 'normalize': normalize, 'tol': tol, 'warm_start': warm_start
}),
(ElasticNet,
{'alpha': alpha, 'normalize': normalize, 'tol': tol,
'l1_ratio': [0.1, 0.2, 0.3, 0.5, 0.7, 0.8, 0.9],
}),
(Lars,
{'normalize': normalize,
'n_nonzero_coefs': [100, 300, 500, np.inf],
}),
(LassoLars,
{ 'max_iter_inf': max_iter_inf, 'normalize': normalize, 'alpha': alpha
}),
(OrthogonalMatchingPursuit,
{'n_nonzero_coefs': [100, 300, 500, np.inf, None],
'tol': tol, 'normalize': normalize
}),
(BayesianRidge,
{
'n_iter': [100, 300, 1000],
'tol': tol, 'normalize': normalize,
'alpha_1': [1e-6, 1e-4, 1e-2, 0.1, 0],
'alpha_2': [1e-6, 1e-4, 1e-2, 0.1, 0],
'lambda_1': [1e-6, 1e-4, 1e-2, 0.1, 0],
'lambda_2': [1e-6, 1e-4, 1e-2, 0.1, 0],
}),
# WARNING: ARDRegression takes a long time to run
(ARDRegression,
{'n_iter': [100, 300, 1000],
'tol': tol, 'normalize': normalize,
'alpha_1': [1e-6, 1e-4, 1e-2, 0.1, 0],
'alpha_2': [1e-6, 1e-4, 1e-2, 0.1, 0],
'lambda_1': [1e-6, 1e-4, 1e-2, 0.1, 0],
'lambda_2': [1e-6, 1e-4, 1e-2, 0.1, 0],
'threshold_lambda': [1e2, 1e3, 1e4, 1e6]}),
(SGDRegressor,
{'loss': ['squared_loss', 'huber', 'epsilon_insensitive', 'squared_epsilon_insensitive'],
'penalty': penalty_12e, 'n_iter': n_iter, 'epsilon': epsilon, 'eta0': eta0,
'alpha': [1e-6, 1e-5, 1e-2, 'optimal'],
'l1_ratio': [0.1, 0.2, 0.3, 0.5, 0.7, 0.8, 0.9],
'learning_rate': ['constant', 'optimal', 'invscaling'],
'power_t': [0.1, 0.25, 0.5]
}),
(PassiveAggressiveRegressor,
{'C': C, 'epsilon': epsilon, 'n_iter': n_iter, 'warm_start': warm_start,
'loss': ['epsilon_insensitive', 'squared_epsilon_insensitive']
}),
(RANSACRegressor,
{'min_samples': [0.1, 0.5, 0.9, None],
'max_trials': n_iter,
'stop_score': [0.8, 0.9, 1],
'stop_probability': [0.9, 0.95, 0.99, 1],
'loss': ['absolute_loss', 'squared_loss']
}),
(HuberRegressor,
{ 'epsilon': [1.1, 1.35, 1.5, 2],
'max_iter': max_iter, 'alpha': alpha, 'warm_start': warm_start, 'tol': tol
}),
(KernelRidge,
{'alpha': alpha, 'degree': degree, 'gamma': gamma, 'coef0': coef0
})
]
linear_models_n_params_small = [
(LinearRegression, {'normalize': normalize}),
(Ridge,
{'alpha': alpha_small, 'normalize': normalize
}),
(Lasso,
{'alpha': alpha_small, 'normalize': normalize
}),
(ElasticNet,
{'alpha': alpha, 'normalize': normalize,
'l1_ratio': [0.1, 0.3, 0.5, 0.7, 0.9],
}),
(Lars,
{'normalize': normalize,
'n_nonzero_coefs': [100, 300, 500, np.inf],
}),
(LassoLars,
{'normalize': normalize, 'max_iter': max_iter_inf, 'alpha': alpha_small
}),
(OrthogonalMatchingPursuit,
{'n_nonzero_coefs': [100, 300, 500, np.inf, None],
'normalize': normalize
}),
(BayesianRidge,
{ 'n_iter': [100, 300, 1000],
'alpha_1': [1e-6, 1e-3],
'alpha_2': [1e-6, 1e-3],
'lambda_1': [1e-6, 1e-3],
'lambda_2': [1e-6, 1e-3],
'normalize': normalize,
}),
# WARNING: ARDRegression takes a long time to run
(ARDRegression,
{'n_iter': [100, 300],
'normalize': normalize,
'alpha_1': [1e-6, 1e-3],
'alpha_2': [1e-6, 1e-3],
'lambda_1': [1e-6, 1e-3],
'lambda_2': [1e-6, 1e-3],
}),
(SGDRegressor,
{'loss': ['squared_loss', 'huber'],
'penalty': penalty_12e, 'n_iter': n_iter,
'alpha': [1e-6, 1e-5, 1e-2, 'optimal'],
'l1_ratio': [0.1, 0.3, 0.5, 0.7, 0.9],
}),
(PassiveAggressiveRegressor,
{'C': C, 'n_iter': n_iter,
}),
(RANSACRegressor,
{'min_samples': [0.1, 0.5, 0.9, None],
'max_trials': n_iter,
'stop_score': [0.8, 1],
'loss': ['absolute_loss', 'squared_loss']
}),
(HuberRegressor,
{ 'max_iter': max_iter, 'alpha_small': alpha_small,
}),
(KernelRidge,
{'alpha': alpha_small, 'degree': degree,
})
]
svm_models_n_params_small = [
(SVR,
{'kernel': kernel, 'degree': degree, 'shrinking': shrinking
}),
(NuSVR,
{'nu': nu_small, 'kernel': kernel, 'degree': degree, 'shrinking': shrinking,
}),
(LinearSVR,
{'C': C_small, 'epsilon': epsilon,
'loss': ['epsilon_insensitive', 'squared_epsilon_insensitive'],
'intercept_scaling': [0.1, 1, 10]
})
]
svm_models_n_params = [
(SVR,
{'C': C, 'epsilon': epsilon, 'kernel': kernel, 'degree': degree, 'gamma': gamma, 'coef0': coef0, 'shrinking': shrinking, 'tol': tol, 'max_iter': max_iter_inf2
}),
(NuSVR,
{'C': C, 'epsilon': epsilon, 'kernel': kernel, 'degree': degree, 'gamma': gamma, 'coef0': coef0, 'shrinking': shrinking, 'tol': tol, 'max_iter': max_iter_inf2
}),
(LinearSVR,
{'C': C, 'epsilon': epsilon, 'tol': tol, 'max_iter': max_iter,
'loss': ['epsilon_insensitive', 'squared_epsilon_insensitive'],
'intercept_scaling': [0.1, 0.5, 1, 5, 10]
})
]
neighbor_models_n_params = [
(RadiusNeighborsRegressor,
{'radius': neighbor_radius, 'algo': neighbor_algo, 'leaf_size': neighbor_leaf_size, 'metric': neighbor_metric,
'weights': ['uniform', 'distance'],
'p': [1, 2],
}),
(KNeighborsRegressor,
{'n_neighbors': n_neighbors, 'algo': neighbor_algo, 'leaf_size': neighbor_leaf_size, 'metric': neighbor_metric,
'p': [1, 2],
'weights': ['uniform', 'distance'],
})
]
gaussianprocess_models_n_params = [
(GaussianProcessRegressor,
{'kernel': [RBF(), ConstantKernel(), DotProduct(), WhiteKernel()],
'n_restarts_optimizer': [3],
'alpha': [1e-10, 1e-5],
'normalize_y': [True, False]
})
]
nn_models_n_params = [
(MLPRegressor,
{ 'hidden_layer_sizes': [(16,), (64,), (100,), (32, 64)],
'activation': ['identity', 'logistic', 'tanh', 'relu'],
'alpha': alpha, 'learning_rate': learning_rate, 'tol': tol, 'warm_start': warm_start,
'batch_size': ['auto', 50],
'max_iter': [1000],
'early_stopping': [True, False],
'epsilon': [1e-8, 1e-5]
})
]
nn_models_n_params_small = [
(MLPRegressor,
{ 'hidden_layer_sizes': [(64,), (32, 64)],
'activation': ['identity', 'tanh', 'relu'],
'max_iter': [500],
'early_stopping': [True],
'learning_rate': learning_rate_small
})
]
tree_models_n_params = [
(DecisionTreeRegressor,
{'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'min_impurity_split': min_impurity_split,
'criterion': ['mse', 'mae']}),
(ExtraTreesRegressor,
{'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf, 'min_impurity_split': min_impurity_split, 'warm_start': warm_start,
'criterion': ['mse', 'mae']}),
(GradientBoostingRegressor,
{'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf, 'min_impurity_split': min_impurity_split, 'warm_start': warm_start}),
]
tree_models_n_params_small = [
(DecisionTreeRegressor,
{'max_features': max_features_small, 'max_depth': max_depth_small, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf,
'criterion': ['mse', 'mae']}),
(ExtraTreesRegressor,
{'n_estimators': n_estimators_small, 'max_features': max_features_small, 'max_depth': max_depth_small, 'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf,
'criterion': ['mse', 'mae']}),
(GradientBoostingRegressor,
{'n_estimators': n_estimators_small, 'max_features': max_features_small, 'max_depth': max_depth_small, 'min_samples_split': min_samples_split,
'min_samples_leaf': min_samples_leaf})
]
def gen_reg_data(x_mu=10., x_sigma=1., num_samples=100, num_features=3, y_formula=sum, y_sigma=1.):
x = np.random.normal(x_mu, x_sigma, (num_samples, num_features))
y = np.apply_along_axis(y_formula, 1, x) + np.random.normal(0, y_sigma, (num_samples,))
return x, y
def run_all_regressors(x, y, small = True, normalize_x = True, n_jobs=cpu_count()-1, brain=False, test_size=0.2, n_splits=5, upsample=True, scoring=None, verbose=False, grid_search=True):
all_params = (linear_models_n_params_small if small else linear_models_n_params) + (nn_models_n_params_small if small else nn_models_n_params) + ([] if small else gaussianprocess_models_n_params) + neighbor_models_n_params + (svm_models_n_params_small if small else svm_models_n_params) + (tree_models_n_params_small if small else tree_models_n_params)
return main_loop(all_params, StandardScaler().fit_transform(x) if normalize_x else x, y, isClassification=False, n_jobs=n_jobs, brain=brain, test_size=test_size, n_splits=n_splits, upsample=upsample, scoring=scoring, verbose=verbose, grid_search=grid_search)
def run_one_regressor(x, y, small = True, normalize_x = True, n_jobs=cpu_count()-1, brain=False, test_size=0.2, n_splits=5, upsample=True, scoring=None, verbose=False, grid_search=True):
all_params = (linear_models_n_params_small if small else linear_models_n_params) + (nn_models_n_params_small if small else nn_models_n_params) + ([] if small else gaussianprocess_models_n_params) + neighbor_models_n_params + (svm_models_n_params_small if small else svm_models_n_params) + (tree_models_n_params_small if small else tree_models_n_params)
all_params = random.choice(all_params)
return all_params[0](**(list(ParameterSampler(all_params[1], n_iter=1))[0]))
class HungaBungaRegressor(RegressorMixin):
def __init__(self, brain=False, test_size = 0.2, n_splits = 5, random_state=None, upsample=True, scoring=None, verbose=False, normalize_x = True, n_jobs =cpu_count() - 1, grid_search=True):
self.model = None
self.brain = brain
self.test_size = test_size
self.n_splits = n_splits
self.random_state = random_state
self.upsample = upsample
self.scoring = None
self.verbose = verbose
self.n_jobs = n_jobs
self.normalize_x = normalize_x
self.grid_search=grid_search
super(HungaBungaRegressor, self).__init__()
def fit(self, x, y):
self.model = run_all_regressors(x, y, normalize_x=self.normalize_x, test_size=self.test_size, n_splits=self.n_splits, upsample=self.upsample, scoring=self.scoring, verbose=self.verbose, brain=self.brain, n_jobs=self.n_jobs, grid_search=self.grid_search)[0]
return self
def predict(self, x):
return self.model.predict(x)
class HungaBungaRandomRegressor(RegressorMixin):
def __init__(self, brain=False, test_size = 0.2, n_splits = 5, random_state=None, upsample=True, scoring=None, verbose=False, normalize_x = True, n_jobs =cpu_count() - 1, grid_search=True):
self.model = None
self.brain = brain
self.test_size = test_size
self.n_splits = n_splits
self.random_state = random_state
self.upsample = upsample
self.scoring = None
self.verbose = verbose
self.n_jobs = n_jobs
self.normalize_x = normalize_x
self.grid_search=grid_search
super(HungaBungaRandomRegressor, self).__init__()
def fit(self, x, y):
self.model = run_one_regressor(x, y, normalize_x=self.normalize_x, test_size=self.test_size, n_splits=self.n_splits, upsample=self.upsample, scoring=self.scoring, verbose=self.verbose, brain=self.brain, n_jobs=self.n_jobs, grid_search=self.grid_search)
self.model.fit(x, y)
return self
def predict(self, x):
return self.model.predict(x)
if __name__ == '__main__':
x, y = gen_reg_data(10, 3, 100, 3, sum, 0.3)
mdl = HungaBungaRegressor()
mdl.fit(x, y)
print(mdl.predict(x).shape)