-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbenchmark.py
186 lines (165 loc) · 5.1 KB
/
benchmark.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
import numpy as np
import pandas as pd
import sys
import time
import preparer
import attr_map
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.linear_model import LogisticRegression
from lightgbm import LGBMClassifier
from sklearn.metrics import roc_auc_score
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from category_encoders import TargetEncoder
from category_encoders import CatBoostEncoder
from category_encoders import CountEncoder
from category_encoders import JamesSteinEncoder
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
# Arg handling
if len(sys.argv) < 3:
sys.exit(
'Please provide arguments!\n'
'Arguments: path/to/dataset algorithm encoding\n'
'algorithm: cart logistic svm knn bagging rf adaboost lgbm\n'
'encoding: target js catboost freq\n'
f'Example: python3 {sys.argv[0]} path/to/dataset.csv cart target'
)
dataset_path = sys.argv[1]
algorithm = sys.argv[2] # cart, lgbm
encoding = sys.argv[3] # freq, target, or loo
# KNN & SVM suffers if we have large data & dimension
if algorithm in ['knn', 'svm']:
MAX_COLUMNS = 10
else:
MAX_COLUMNS = 100
# Mapping
CLF_MAP = {
'cart': DecisionTreeClassifier,
'logistic': LogisticRegression,
'svm': SVC,
'knn': KNeighborsClassifier,
'bagging': BaggingClassifier,
'rf': RandomForestClassifier,
'adaboost': AdaBoostClassifier,
'lgbm': LGBMClassifier
}
ENCODER_MAP = {
'target': TargetEncoder,
'js': JamesSteinEncoder,
'freq': CountEncoder,
'catboost': CatBoostEncoder,
# 'loo': LeaveOneOutEncoder # LOO is buggy on the pipeline
}
PARAM_GRID_MAP = {
'cart': {
'clf__criterion': ['gini', 'entropy'],
'clf__min_samples_leaf': np.array(range(10, 21, 5)) / 10_000,
},
'logistic': {
'clf__penalty': ['l2', 'none'],
'clf__C': [0.5, 0.75, 1.0],
},
'svm': {
'clf__kernel': ['linear', 'rbf'],
'clf__C': [0.5, 1.0, 0.25]
},
'knn': {
'clf__n_neighbors': [3, 5, 7],
'clf__weights': ['uniform', 'distance']
},
'bagging': {
'clf__n_estimators': [10, 15],
'clf__max_samples': [0.5, 1.0],
'clf__max_features': [0.5, 1.0],
},
'rf': {
'clf__criterion': ['gini', 'entropy'],
'clf__min_samples_leaf': np.array(range(10, 21, 5)) / 10_000,
},
'adaboost': {
'clf__n_estimators': [50, 100],
'clf__learning_rate': [0.5, 0.75, 1.0],
},
'lgbm': {
'clf__reg_alpha': [0, 2.5, 5],
'clf__min_child_samples': [50, 100, 150],
}
}
# Attributes
attributes = attr_map.ATTR_MAP[encoding]['attrs'][:MAX_COLUMNS]
cat_attributes = np.intersect1d(
attributes, attr_map.ATTR_MAP[encoding]['cat_attrs']
)
target = attr_map.TARGET
# Prepare & split data
df = preparer.get_data(dataset_path, encoding)
X_train, X_test, y_train, y_test = train_test_split(
df[attributes], df[target], test_size=0.2, random_state=42
)
# Encoder & classifier
encoder = ENCODER_MAP[encoding](cols=cat_attributes)
if algorithm == 'svm':
clf = CLF_MAP[algorithm](probability=True) # so we can predict_proba
else:
clf = CLF_MAP[algorithm]()
# Initialize pipeline
estimators = list()
# Encoder to pipeline
if encoding == 'freq': # CountEncoder needn't be put in pipeline for CV
encoder.fit(pd.concat([X_train, X_test])) # Because needn't label
X_train = encoder.transform(X_train)
X_test = encoder.transform(X_test)
else:
estimators.append(('encoder', encoder))
# Add scaler and classifier to the pipeline
estimators += [
('imputer', SimpleImputer()),
('scaler', StandardScaler()),
('clf', clf)
]
pipe = Pipeline(steps=estimators)
# Parameter grid
param_grid = PARAM_GRID_MAP[algorithm]
# Fit
start = time.time()
grid = GridSearchCV(pipe, param_grid=param_grid, scoring='roc_auc')
grid.fit(X_train, y_train)
# Print grid search results
print(f'{algorithm} {encoding} {X_train.shape[0] + X_test.shape[0]}\n')
print('Grid Search Results')
print('Best params:')
print(grid.best_params_)
print('Best score:')
print(grid.best_score_)
print('Scores:')
print(grid.cv_results_['mean_test_score'])
# Test
y_pred = grid.predict_proba(X_test)
print()
print('TEST SCORE:')
print(roc_auc_score(y_test, y_pred[:, 1]))
end = time.time()
print()
print('Running Time:', end - start, 'seconds')
# Feature importances
TREE_ALGOS = ['cart', 'rf', 'adaboost', 'lgbm']
if algorithm in TREE_ALGOS:
fi_df = pd.DataFrame(index=X_test.columns, columns=['Importance'])
fi_df['Importance'] = grid.best_estimator_.steps[-1][1].feature_importances_
print()
print('Feature Importances')
print(fi_df.sort_values('Importance', ascending=False))
# # Fit
# pipe.fit(X_train, y_train)
# # Test
# y_pred = pipe.predict(X_test)
# print()
# print('TEST SCORE:')
# print(roc_auc_score(y_test, y_pred))