-
Notifications
You must be signed in to change notification settings - Fork 0
/
classifier_trainer.py
195 lines (173 loc) · 8.84 KB
/
classifier_trainer.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
import pickle
import os
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import balanced_accuracy_score
from sklearn.metrics import plot_confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import RidgeClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import LinearSVC
from sklearn.neural_network import MLPClassifier
class Classification:
def __init__(self):
print("Training Initialized for Continuous Variable:")
def train(self, data, var, info):
print(var)
train_metrics = dict()
method_list = info[0]
default_active = info[1]
params = info[2]
if not os.path.exists(var):
os.makedirs(var)
try:
for count, method in enumerate(method_list):
cls = getattr(self, "train_" + method)(default_active[count], params[count])
train_metrics[method] = self.train_data(data, var, method, cls)
return train_metrics
except AttributeError:
print("The continuous training method '" + method + "' does not exist, kindly check the config files!")
@staticmethod
def train_data(self, data, var, method, cls):
try:
print("Training " + var + " with " + method + " classification method.")
y = np.array(data[var])
x = np.array(data.drop(columns=[var]))
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)
cls.fit(x_train, y_train)
y_pred = cls.predict(x_test)
pkl_filename = method + ".pkl"
with open(var + "/" + pkl_filename, 'wb') as file:
pickle.dump(cls, file)
plot_confusion_matrix(cls, x_test, y_test)
plt.title(var + ": Confusion Matrix by " + method + " classification")
plt.ylabel('Actual Classes')
plt.xlabel('Predicted Classes')
plt.savefig(var + "/" + method + "_cm.jpg")
metric_dict = {
"accuracy": balanced_accuracy_score(y_test, y_pred),
"precision": precision_score(y_test, y_pred, average='weighted'),
"recall": recall_score(y_test, y_pred, average='weighted'),
"f1_score": f1_score(y_test, y_pred, average='weighted')
}
print("Training of " + var + " with " + method + " classification method complete!")
return metric_dict
except:
print("Training of " + var + " with " + method + " classification method incomplete!")
return {
"accuracy": 0,
"precision": 0,
"recall": 0,
"f1_score": 0
}
@staticmethod
def train_logistic_reg(self, default, param):
if default:
cls_trainer = LogisticRegression(random_state=0)
else:
cls_trainer = LogisticRegression(
penalty=param["penalty"], dual=param["dual"], tol=param["tol"],
C=param["C"], fit_intercept=param["fit_intercept"],
intercept_scaling=param["intercept_scaling"], class_weight=param["class_weight"],
random_state=param["random_state"], solver=param["solver"],
max_iter=param["max_iter"], multi_class=param["multi_class"],
verbose=param["verbose"], warm_start=param["warm_start"],
n_jobs=param["n_jobs"], l1_ratio=param["l1_ratio"])
return cls_trainer
@staticmethod
def train_ridge(self, default, param):
if default:
cls_trainer = RidgeClassifier(random_state=0)
else:
cls_trainer = RidgeClassifier(
alpha=param["alpha"], fit_intercept=param["fit_intercept"],
normalize=param["normalize"], max_iter=param["max_iter"],
tol=param["tol"], class_weight=param["class_weight"],
random_state=param["random_state"], solver=param["solver"])
return cls_trainer
@staticmethod
def train_naive_bayes(self, default, param):
if default:
cls_trainer = MultinomialNB()
else:
cls_trainer = MultinomialNB(alpha=param["alpha"], fit_prior=param["fit_prior"],
class_prior=param["class_prior"])
return cls_trainer
@staticmethod
def train_KNN(self, default, param):
if default:
cls_trainer = KNeighborsClassifier()
else:
cls_trainer = KNeighborsClassifier(
n_neighbors=param["n_neighbors"], weights=param["weights"],
algorithm=param["algorithm"], max_iter=param["max_iter"],
leaf_size=param["leaf_size"], p=param["p"], metric=param["metric"],
metric_params=param["metric_params"], n_jobs=param["n_jobs"]
)
return cls_trainer
@staticmethod
def train_random_forest(self, default, param):
if default:
cls_trainer = RandomForestClassifier(random_state=0)
else:
cls_trainer = RandomForestClassifier(
n_estimators=param["n_estimators"], criterion=param["criterion"], max_depth=param["max_depth"],
min_samples_split=param["min_samples_split"], min_samples_leaf=param["min_samples_leaf"],
min_weight_fraction_leaf=param["min_weight_fraction_leaf"], max_features=param["max_features"],
random_state=param["random_state"], max_leaf_nodes=param["max_leaf_nodes"],
min_impurity_decrease=param["min_impurity_decrease"], bootstrap=param["bootstrap"],
oob_score=param["oob_score"], n_jobs=param["n_jobs"], verbose=param["verbose"],
warm_start=param["warm_start"], class_weight=param["class_weight"], ccp_alpha=param["ccp_alpha"],
max_samples=param["max_samples"])
return cls_trainer
@staticmethod
def train_decision_tree(self, default, param):
if default:
cls_trainer = DecisionTreeClassifier(random_state=0)
else:
cls_trainer = DecisionTreeClassifier(
criterion=param["criterion"], splitter=param["splitter"], max_depth=param["max_depth"],
min_samples_split=param["min_samples_split"], min_samples_leaf=param["min_samples_leaf"],
min_weight_fraction_leaf=param["min_weight_fraction_leaf"], max_features=param["max_features"],
random_state=param["random_state"], max_leaf_nodes=param["max_leaf_nodes"],
min_impurity_decrease=param["min_impurity_decrease"], class_weight=param["class_weight"],
ccp_alpha=param["ccp_alpha"]
)
return cls_trainer
@staticmethod
def train_support_vector(self, default, param):
if default:
cls_trainer = LinearSVC(random_state=0)
else:
cls_trainer = LinearSVC(
C=param["C"], kernel=param["kernel"], degree=param["degree"], gamma=param["gamma"],
coef0=param["coef0"], shrinking=param["shrinking"], probability=param["probability"], tol=param["tol"],
cache_size=param["cache_size"], class_weight=param["class_weight"], verbose=param["verbose"],
max_iter=param["max_iter"], decision_function_shape=param["decision_function_shape"],
break_ties=param["break_ties"], random_state=param["random_state"]
)
return cls_trainer
@staticmethod
def train_neural_MLP(self, default, param):
if default:
cls_trainer = MLPClassifier(random_state=0, max_iter=300)
else:
cls_trainer = MLPClassifier(
hidden_layer_sizes=tuple(param["hidden_layer_sizes"]), activation=param["activation"],
solver=param["solver"],
alpha=param["alpha"], batch_size=param["batch_size"], learning_rate=param["learning_rate"],
learning_rate_init=param["learning_rate_init"], power_t=param["power_t"], max_iter=param["max_iter"],
shuffle=param["shuffle"], random_state=param["random_state"], tol=param["tol"],
verbose=param["verbose"], warm_start=param["warm_start"], momentum=param["momentum"],
nesterovs_momentum=param["nesterovs_momentum"], early_stopping=param["early_stopping"],
validation_fraction=param["validation_fraction"], beta_1=param["beta_1"], beta_2=param["beta_2"],
epsilon=param["epsilon"], n_iter_no_change=param["n_iter_no_change"], max_fun=param["max_fun"]
)
return cls_trainer