-
Notifications
You must be signed in to change notification settings - Fork 1
/
regressions.py
206 lines (130 loc) · 6.59 KB
/
regressions.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
# -*- coding: utf-8 -*-
"""
Created on Tue May 26 16:39:12 2020
@author: Sameitos
"""
import os, sys
import numpy as np
from sklearn.model_selection import RandomizedSearchCV,RepeatedKFold, PredefinedSplit
import pickle
import warnings
warnings.filterwarnings("ignore")
class regressors(object):
def __init__(self,path):
"""
Description:
Six different machine learning methods for regression
are introduced. Their hyperparameters are tuned by
RandomizedSearchCV and all methods return only their hyperparameters
that give the best respect to cross-validation that is created by RepeatedKFold.
Parameters:
path: {string}, A destination point where model is saved.
X_train: Feature matrix, {list, numpy array}
y_train: (default = None), Label matrix, type = {list, numpy array}
X_valid: (default = None), Validation Set, type = {list,numpy array}
y_valid: (default = None), Validation Label, type = {list,numpy array}
Returns:
model: Parameters of fitted model
"""
self.path = path
self.parameters = None
self.n_jobs = -1
self.random_state = 0
def get_best_model(self, model, X_train, y_train,X_valid, y_valid):
if X_valid is None:
cv = RepeatedKFold(n_splits=10,n_repeats = 5,random_state= self.random_state)
else:
if y_valid is None:
raise ValueError(f'True label data for validation set cannot be None')
X_train = list(X_train)
y_train = list(y_train)
len_tra, len_val = len(X_train),len(X_valid)
X_train.extend(list(X_valid))
y_train.extend(list(y_valid))
test_fold = [0 if x in np.arange(len_tra) else -1 for x in np.arange(len_tra+len_val)]
cv = PredefinedSplit(test_fold)
clf = RandomizedSearchCV(model,self.parameters,n_iter = 10,
n_jobs=self.n_jobs, cv = cv,
scoring="f1")
if y_train is not None:
clf.fit(X_train,y_train)
else:
clf.fit(X_train)
best_model = clf.best_estimator_
if self.path is not None:
with open(self.path, 'wb') as f:
pickle.dump(best_model,f)
return best_model
def linear_regression(self,X_train,y_train,X_valid,y_valid):
from sklearn.linear_model import LinearRegression
from .hyperparameters import rgr_linear_regression_params as lrp
self.parameters = lrp
model = LinearRegression()
return self.get_best_model(model,X_train,y_train,X_valid,y_valid)
def SVM(self,X_train,y_train,X_valid,y_valid):
from sklearn.svm import SVR
from .hyperparameters import rgr_svm_params as svmp
self.parameters = svmp
model = SVR()
return self.get_best_model(model, X_train, y_train,X_valid, y_valid)
def random_forest(self,X_train,y_train,X_valid,y_valid):
from sklearn.ensemble import RandomForestRegressor
from .hyperparameters import rgr_random_forest_params as rfp
self.parameters = rfp
model = RandomForestRegressor()
return self.get_best_model(model, X_train, y_train,X_valid, y_valid)
def MLP(self,X_train,y_train,X_valid,y_valid):
from sklearn.neural_network import MLPRegressor
from .hyperparameters import rgr_mlp_params as mlpp
self.parameters = mlpp
model = MLPRegressor()
return self.get_best_model(model, X_train, y_train,X_valid, y_valid)
def decision_tree(self,X_train,y_train,X_valid,y_valid):
from sklearn.tree import DecisionTreeRegressor
from .hyperparameters import rgr_decision_tree_params as dtp
self.parameters = dtp
model = DecisionTreeRegressor()
return self.get_best_model(model, X_train, y_train,X_valid, y_valid)
def gradient_boosting(self,X_train,y_train,X_valid,y_valid):
from sklearn.ensemble import GradientBoostingRegressor as GBR
from .hyperparameters import rgr_gradient_boosting_params as gbp
self.parameters = gbp
model = GBR()
return self.get_best_model(model, X_train, y_train,X_valid, y_valid)
def regression_methods(X_train,ml_type = "SVM", y_train = None ,X_valid = None,y_valid = None, path = None):
"""
Description:
Six different machine learning methods for regression
are introduced. Their hyperparameters are tuned by
RandomizedSearchCV and all methods return only their hyperparameters
that give the best respect to cross-validation that is created by RepeatedKFold.
Parameters:
ml_type: {'linear_reg','SVM','random_forest','MLP',
'naive_bayes', decision_tree',gradient_boosting'}, default = "SVM",
Type of machine learning algorithm.
path: {string}, A destination point where model is saved.
X_train: Feature matrix, {list, numpy array}
y_train: (default = None), Label matrix, type = {list, numpy array}
X_valid: (default = None), Validation Set, type = {list,numpy array}
y_valid: (default = None), Validation Label, type = {list,numpy array}
Returns:
model: Parameters of fitted model
"""
if path is not None:
if os.path.isfile(path):
print(f'Model path {path} is already exist.'
f'To not lose model please provide new model path name or leave path as None')
sys.exit(1)
if set(y_train) == {1,-1} or set(y_train) == {1,0}:
raise ValueError('Data must be continous not binary')
r = regressors(path)
machine_methods = {
'linear_reg':r.linear_regression,
'SVM':r.SVM,
'random_forest':r.random_forest,
'MLP':r.MLP,
'decision_tree':r.decision_tree,
'gradient_boosting':r.gradient_boosting
}
machine_methods[ml_type](X_train = X_train,y_train = y_train,X_valid = X_valid,y_valid = y_valid)
return path