-
Notifications
You must be signed in to change notification settings - Fork 0
/
Classification.py
276 lines (197 loc) · 9.61 KB
/
Classification.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
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
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from yellowbrick.model_selection import feature_importances
#===============================================================================================#
# Classification Models Class
#===============================================================================================#
class Classification():
"""
This class is for performing classifcation algorithms such as Logistic Regression, Decision Tree, Random Forest, and SVM.
Parameters
----------
model_type: 'Logistic Regression', 'Decision Tree', 'Random Forest', 'SVM'
the type of classifcation algorithm you would like to apply
x_train: dataframe
the independant variables of the training data
x_val: dataframe
the independant variables of the validation data
y_train: series
the target variable of the training data
y_val: series
the target variable of the validation data
"""
def __init__(self,model_type,x_train,x_val,y_train,y_val):
self.model_type = model_type
self.x_train = x_train
self.y_train = y_train
self.x_val = x_val
self.y_val = y_val
self.scores_table = pd.DataFrame()
self.feature_importances = pd.DataFrame()
self.name = self
if self.model_type == 'Logistic Regression':
self.technique = LogisticRegression(fit_intercept=False)
elif self.model_type == 'Decision Tree':
self.technique = DecisionTreeClassifier(random_state=42)
elif self.model_type == 'Random Forest':
self.technique = RandomForestClassifier(n_estimators=20,n_jobs=-1,random_state=42)
elif self.model_type == 'SVM':
self.technique = SVC()
elif self.model_type == 'Naive Bayes':
self.technique = GaussianNB()
elif self.model_type == 'KNN':
self.technique = KNeighborsClassifier(n_jobs=-1)
#===============================================================================================#
# Score Function
#===============================================================================================#
def scores(self,model,x_train,x_val,y_train,y_val):
"""
Gets the accuracy for the given data and creates a dataframe containing scores.
Parameters
----------
model: 'Logistic Regression', 'Decision Tree', 'Random Forest', 'SVM'
the type of classifcation applied
x_train: dataframe
the independant variables of the training data
x_val: dataframe
the independant variables of the validation data
y_train: series
the target variable of the training data
y_val: series
the target variable of the validation data
Returns
----------
scores_table: a dataframe with the model used, the train accuracy and validation accuracy
"""
self.acc_train = self.best_model.score(x_train,y_train)
self.acc_val = self.best_model.score(x_val,y_val)
d = {'Model Name': [self.model_type],
'Train Accuracy': [self.acc_train],
'Validation Accuracy': [self.acc_val],
'Accuracy Difference':[self.acc_train-self.acc_val]}
self.scores_table = pd.DataFrame(data=d)
return self.scores_table
#===============================================================================================#
# Get Scores Function
#===============================================================================================#
def get_scores(self,params,cv_type):
"""
Performs a gridsearch cross validation with given hyperparameters and data.
Gets the accuracy for the given data and creates a dataframe containing scores.
Parameters
----------
param_grid: dictionary
specified hyperparameters for chosen classification algorithm to be passed through gridsearch cross validation
cv_type: 'skf'
the type of cross validation split to be used for gridsearch
"""
classifier = self.technique
fit_classifier = classifier.fit(self.x_train,self.y_train)
opt_model = GridSearchCV(fit_classifier,
params,
cv=cv_type,
scoring='accuracy',
return_train_score=True,
n_jobs=-1)
self.opt_model = opt_model.fit(self.x_train,self.y_train)
self.best_model = opt_model.best_estimator_
self.scores = Classification.scores(self,self.best_model,self.x_train,self.x_val,self.y_train,self.y_val)
self.best_params = opt_model.best_params_
display(self.scores_table)
if params == {}:
pass
else:
print("The best hyperparameters are: ", self.best_params,'\n')
self.y_validated = self.best_model.predict(self.x_val)
self.classification_report = pd.DataFrame.from_dict(classification_report(self.y_val,self.y_validated,output_dict=True)).iloc[0:3,0:5]
return self.classification_report
#===============================================================================================#
# Feature Importance Function
#===============================================================================================#
def get_feature_importances(self):
"""
Create a confusion matrix.
Returns
----------
feature_importances_bar : a bar chart with feature importance of given model
"""
if (self.model_type == 'Decision Tree') or (self.model_type == 'Random Forest') or (self.model_type == 'SVM'):
self.feature_importances_table = pd.DataFrame(self.best_model.feature_importances_,
index = self.x_train.columns,
columns=['Importance']).sort_values('Importance',ascending =False)
plt.figure(figsize=(9,7.5))
self.feature_importances_bar = sns.barplot(y= self.feature_importances_table.index[:15], x= self.feature_importances_table['Importance'][:15])
plt.show()
return self.feature_importances_bar
else:
return print('This classification method does not have the attribute feature importance.')
#===============================================================================================#
# Confusion Matrix Function
#===============================================================================================#
def conf_matrix(self):
"""
Create a confusion matrix.
Returns
----------
scores_table: a confusion matrix
"""
plt.figure(figsize=(9,9))
ax = sns.heatmap(confusion_matrix(self.y_val, self.y_validated),
annot= True,
fmt = '.4g',
cbar=0,
xticklabels=[1,2,3,4,5],
yticklabels=[1,2,3,4,5])
ax.set(xlabel='Predicted', ylabel='True')
plt.show()
#===============================================================================================#
# Test Score Function
#===============================================================================================#
def get_test_scores(self,X_test,y_test):
"""
Gets a ROC AUC score for given data and creates a dataframe containing scores.
Creates a ROC plot.
Parameters
----------
x_test: dataframe
independant variables of the test data
y_test: dataframe
target variable of the test data
"""
self.y_test = y_test
self.x_test = X_test
self.scores_table = pd.DataFrame()
self.test_scores = Classification.scores(self,self.best_model,self.x_train,self.x_test,self.y_train,self.y_test)
display(self.scores_table)
self.y_tested = self.best_model.predict(self.x_test)
self.test_classification_report = pd.DataFrame.from_dict(classification_report(self.y_test,self.y_tested,output_dict=True)).iloc[0:3,0:5]
return self.test_classification_report
#===============================================================================================#
# Show Test Confusion Matrix Function
#===============================================================================================#
def test_conf_matrix(self):
"""
Create a confusion matrix for the test data.
Returns
----------
scores_table: a confusion matrix
"""
plt.figure(figsize=(9,9))
ax = sns.heatmap(confusion_matrix(self.y_test, self.y_tested),
annot= True,
fmt = '.4g',
cbar=0,
xticklabels=[1,2,3,4,5],
yticklabels=[1,2,3,4,5])
ax.set(xlabel='Predicted', ylabel='True')
plt.show()