-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_model.py
397 lines (309 loc) · 15 KB
/
run_model.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
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
import process_data
import pandas as pd
from sklearn.metrics import confusion_matrix, classification_report
from sklearn import metrics
from sklearn.metrics import mean_absolute_error
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn import ensemble
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn.naive_bayes import GaussianNB
# MODEL : Linear Regression (works for continuous variables)
def linear_regression(X_train, X_test, y_train, y_test, show_columns, target_column):
'''
Linear Regression Model :
- performs regression task
- used for finding out the relationship between variables and outcome variable/target column
- based on supervised learning
Input ->
X_train, X_test, y_train, y_test : train test split data
show_columns : names of columns to print in prediction file
target_column : column name to predict
Output ->
if no y_test , creates prediction file in current directory & returns prediction list
else
prediction, mae : predictions for the target column, mean absolute error
'''
print('Running Linear Regression....')
model = LinearRegression()
model.fit(X_train, y_train)
# find y-intercept and x coefficients
print('\n y-intercept : ', model.intercept_)
model_results = pd.DataFrame(model.coef_, X_train.columns, columns=['Coefficients'])
print('\n x coefficients : \n', model_results)
print('\n')
prediction = model.predict(X_test)
mae = 0
# if predictions dont exist
if y_test == None:
process_data.create_prediction_file(X_test, show_columns, target_column, prediction)
# if validating
else :
mae = metrics.mean_absolute_error(y_test, prediction)
print("\nMean Absolute Error : ", mae)
return prediction, mae
print(' ----- END ----- ')
return prediction
# MODEL : Logistic Regression (works for discrete variables)
def logistic_regression(X_train, X_test, y_train, y_test, show_columns, target_column):
'''
Logistic Regression Model :
- performs regression task
- used for finding out the relationship between variables and outcome variable/target column
- models data using the sigmoid function
- supervised classification algorithm
- requires large training sets
Input ->
X_train, X_test, y_train, y_test : train test split data
show_columns : names of columns to print in prediction file
target_column : column name to predict
Output ->
if no y_test , creates prediction file in current directory
else
print confusion matrix : table used to define performance of classification algorithm
classification report : shows main classification metrics
model_predict : predictions for the target column
'''
print('Running Logistic Regression....')
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
model_predict = model.predict(X_test)
# if predictions dont exist
if y_test == None:
process_data.create_prediction_file(X_test, show_columns, target_column, model_predict)
# if validating
else :
print('\nConfusion Matrix : \n', confusion_matrix(y_test, model_predict))
print('\nClassification Report : \n', classification_report(y_test, model_predict))
print(' ----- END ----- ')
return model_predict
# MODEL : Decision Tree Classifier
def decision_tree_classifier(X_train, X_test, y_train, y_test, show_columns, target_column):
'''
Decision Tree Classifier Model :
- performs classification & regression tasks
- handles decision making automatically
- prone to overfitting
- can be trained on small training sets
- supervised learning algorithm
Input ->
X_train, X_test, y_train, y_test : train test split data
show_columns : names of columns to print in prediction file
target_column : column name to predict
Output ->
if no y_test , creates prediction file in current directory
else
print confusion matrix : table used to define performance of classification algorithm
classification report : shows main classification metrics
model_predict : predictions for the target column
'''
print('Running Decision Tree Classifier....')
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
model_predict = model.predict(X_test)
if y_test == None:
process_data.create_prediction_file(X_test, show_columns, target_column, model_predict)
else :
print('\nConfusion Matrix : \n', confusion_matrix(y_test, model_predict))
print('\nClassification Report : \n', classification_report(y_test, model_predict))
print(' ----- END ----- ')
return model_predict
# MODEL : Random Forest Classifier
def random_forest_classifier(X_train, X_test, y_train, y_test, show_columns, target_column, num_estimators):
'''
Random Forest Classifier Model :
- ensemble learning method that fits a number of decision tree classifiers
- performs classification & regression tasks
- handles decision making automatically
- supervised learning algorithm
Input ->
X_train, X_test, y_train, y_test : train test split data
show_columns : names of columns to print in prediction file
target_column : column name to predict
num_estimators : number of trees in forest
Output ->
if no y_test , creates prediction file in current directory
else
print confusion matrix : table used to define performance of classification algorithm
classification report : shows main classification metrics
model_predict : predictions for the target column
'''
print('Running Random Forest Classifier....')
model = RandomForestClassifier(n_estimators=num_estimators)
model.fit(X_train, y_train)
model_predict = model.predict(X_test)
if y_test == None:
process_data.create_prediction_file(X_test, show_columns, target_column, model_predict)
else :
print('\nConfusion Matrix : \n', confusion_matrix(y_test, model_predict))
print('\nClassification Report : \n', classification_report(y_test, model_predict))
print(' ----- END ----- ')
return model_predict
# MODEL : Gradient Boosting Classifier/Regressor
def gradient_boosting(X_train, X_test, y_train, y_test, show_columns, target_column, gb_type):
'''
Gradient Boosting Classifier/Regressor Model :
- ensemble of weak prediction models such as decision trees
- performs classification & regression tasks
- works for large & complex datasets, has good prediction speed & accuracy
- supervised learning algorithm
Input ->
X_train, X_test, y_train, y_test : train test split data
show_columns : names of columns to print in prediction file
target_column : column name to predict
gb_type : 'classifier' or 'regressor'
Output ->
if no y_test , creates prediction file in current directory
else
- if classifier
print confusion matrix : table used to define performance of classification algorithm
& classification report : shows main classification metrics
- else if regressor
print mean absolute error
model_predict : predictions for the target column
'''
if gb_type == 'classifier':
print('Running Gradient Boosting Classifier....')
model = ensemble.GradientBoostingClassifier(n_estimators=250, learning_rate=0.1, max_depth=5, min_samples_split=4, min_samples_leaf=6, max_features=0.6, loss='deviance')
model.fit(X_train, y_train)
model_predict = model.predict(X_test)
if y_test == None:
process_data.create_prediction_file(X_test, show_columns, target_column, model_predict)
else :
print('\nConfusion Matrix : \n', confusion_matrix(y_test, model_predict))
print('\nClassification Report : \n', classification_report(y_test, model_predict))
print(' ----- END ----- ')
return model_predict
# perform one-hot-encoding on categorical variables before
elif gb_type == 'regressor':
print('Running Gradient Boosting Regressor....')
model = ensemble.GradientBoostingRegressor(n_estimators=350, learning_rate=0.1, max_depth=5, min_samples_split=4, min_samples_leaf=6, max_features=0.6, loss='huber')
model.fit(X_train, y_train)
model_predict = model.predict(X_test)
if y_test == None:
process_data.create_prediction_file(X_test, show_columns, target_column, model_predict)
else :
mae_train = mean_absolute_error(y_test, model.predict(X_train))
print("Training Set Mean Absolute Error : %.2f" % mae_train)
mae_test = mean_absolute_error(y_test, model.predict(X_test))
print("Test Set Mean Absolute Error : %.2f" % mae_test)
print(' ----- END ----- ')
return model_predict
# MODEL : k-Nearest Neighbors (for relatively small and low dimensional datasets)
# scale data before this function
def k_neighbors_classifier(X_train, X_test, y_train, y_test, show_columns, target_column, k, scaled_features):
'''
k Nearest Neighbors Classifier Model :
- uses proximity to make classifications or predictions about grouping individual data point
- performs classification, regression & is non parametric
- supervised learning algorithm
Input ->
X_train, X_test, y_train, y_test : train test split data
show_columns : names of columns to print in prediction file
target_column : column name to predict
k : number of neighbors
scaled_features : list of columns names to predict for scaled dataset
Output ->
if no y_test , creates prediction file in current directory
else
print confusion matrix : table used to define performance of classification algorithm
& classification report : shows main classification metrics
model_predict : predictions for the dataset
scaled_model_predict : predictions for the scaled dataset
'''
print('Running k-Nearest Neighbor Classifier....')
model = KNeighborsClassifier(n_neighbors=k)
model.fit(X_train, y_train)
model_predict = model.predict(X_test)
if y_test == None:
process_data.create_prediction_file(X_test, show_columns, target_column, model_predict)
else :
print('\nConfusion Matrix : \n', confusion_matrix(y_test, model_predict))
print('\nClassification Report : \n', classification_report(y_test, model_predict))
scaled_model_predict = []
if scaled_features:
scaled_model_predict = model.predict(scaled_features)
if y_test == None:
process_data.create_prediction_file(X_test, show_columns, target_column, scaled_model_predict)
else :
print('\nConfusion Matrix : \n', confusion_matrix(y_test, scaled_model_predict))
print('\nClassification Report : \n', classification_report(y_test, scaled_model_predict))
print(' ----- END ----- ')
return model_predict, scaled_model_predict
# MODEL : Support Vector Machines (allows categorical variables)
def support_vector_classifier(X_train, X_test, y_train, y_test, show_columns, target_column):
'''
Support Vector Classifier Model :
- find a hyperplane in a multi dimensional space that distinctly classifies the data points
- performs classification, regression & outlier detection
- supervised learning algorithm
Input ->
X_train, X_test, y_train, y_test : train test split data
show_columns : names of columns to print in prediction file
target_column : column name to predict
Output ->
if no y_test , creates prediction file in current directory
else
print confusion matrix : table used to define performance of classification algorithm
& classification report : shows main classification metrics
model_predictions : predictions for the dataset
grid_predictions : predictions for the dataset using grid search
'''
print('Running Support Vector Classifier....')
model = SVC()
model.fit(X_train, y_train)
model_predict = model.predict(X_test)
if y_test == None:
process_data.create_prediction_file(X_test, show_columns, target_column, model_predict)
#pass
else :
print('\nConfusion Matrix : \n', confusion_matrix(y_test, model_predict))
print('\nClassification Report : \n', classification_report(y_test, model_predict))
# Grid Search
hyperparameters = {'C':[10,25,50], 'gamma':[0.001,0.0001,0.00001]}
grid = GridSearchCV(SVC(), hyperparameters)
grid.fit(X_train, y_train)
print('\nOptimal HyperParameter : ', grid.best_params_)
grid_predictions = grid.predict(X_test)
if y_test == None:
process_data.create_prediction_file(X_test, show_columns, target_column, grid_predictions)
#pass
else :
print('\nConfusion Matrix : \n', confusion_matrix(y_test, grid_predictions))
print('\nClassification Report : \n', classification_report(y_test, grid_predictions))
print(' ----- END ----- ')
return model_predict, grid_predictions
# MODEL : Gaussian Naive Bayes Classifier
def gaussian_naive_bayes_classifier(X_train, X_test, y_train, y_test, show_columns, target_column):
'''
Gaussian Naive Bayes Classifier Model :
- based on Bayes theorem : probability of target class given selected features is inversely proportional to the probability of selected features & directly proportional to probabilty of target class or that of the selcted features given the target class
- time efficient as naive bayes classifiers are faster than others
- performs classification tasks
- supervised learning algorithm
Input ->
X_train, X_test, y_train, y_test : train test split data
show_columns : names of columns to print in prediction file
target_column : column name to predict
Output ->
if no y_test , creates prediction file in current directory
else
print confusion matrix : table used to define performance of classification algorithm
classification report : shows main classification metrics
model_predict : predictions for the target column
'''
print('Running Gaussian Naive Bayes Classifier....')
model = GaussianNB()
model.fit(X_train, y_train)
model_predict = model.predict(X_test)
if y_test == None:
process_data.create_prediction_file(X_test, show_columns, target_column, model_predict)
else :
print('\nConfusion Matrix : \n', confusion_matrix(y_test, model_predict))
print('\nClassification Report : \n', classification_report(y_test, model_predict))
print(' ----- END ----- ')
return model_predict