Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

hierarchy_svm_svm.py 8.7 KB

You have to be logged in to leave a comment. Sign In
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
  1. import argparse
  2. import logging
  3. import sys
  4. import optuna
  5. from sklearn.model_selection import StratifiedKFold, KFold
  6. from sklearn.svm import SVC
  7. from common.tools import *
  8. optuna.logging.get_logger("optuna").addHandler(logging.StreamHandler(sys.stdout))
  9. parser = argparse.ArgumentParser()
  10. parser.add_argument("GRAPH_VER", help="path to actual_graph CSV", type=str) # ../data_updated/actual_graph_2021-06-09.csv
  11. parser.add_argument("DATASET_PATH", help="path to your input CSV", type=str)
  12. parser.add_argument("N_TRIALS", help="optuna n trials, if 0 use default hyperparams", type=int)
  13. args = parser.parse_args()
  14. GRAPH_VER = args.GRAPH_VER
  15. DATASET_PATH = args.DATASET_PATH
  16. N_TRIALS = args.N_TRIALS
  17. MODEL_DIR = "../models/hyper_svm_regex_graph_upper_clf.sav"
  18. TFIDF_DIR = "../models/tfidf_hyper_svm_graph_upper.pickle"
  19. RANDOM_STATE = 42
  20. MAX_ITER = 10000
  21. HYPERPARAM_SPACE = {
  22. "svm_c": (1e-1, 1e3),
  23. "tfidf_min_df": (1, 10),
  24. "tfidf_max_df": (0.2, 0.7),
  25. "svm_kernel": ["linear", "poly", "rbf"],
  26. "svm_degree": (2, 6), # in case of poly kernel
  27. }
  28. DEFAULT_HYPERPARAMS_UPPER = {
  29. "svm__C": 149.65,
  30. "tfidf__min_df": 1,
  31. "tfidf__max_df": 0.99,
  32. "svm__kernel": "poly",
  33. "svm__degree": 2,
  34. "tfidf__smooth_idf": True,
  35. "svm__random_state": RANDOM_STATE,
  36. "svm__max_iter": MAX_ITER,
  37. }
  38. def get_ver_to_sub(graph_df):
  39. ver_to_sub = dict()
  40. for i in graph_df.index:
  41. ver_to_sub[i] = graph_df.graph_vertex[i]
  42. return ver_to_sub
  43. def get_vertices(df, ver_to_sub):
  44. return df["graph_vertex_id"].apply(lambda x: ver_to_sub[x])
  45. def cross_val_predict(kf, clf, X, y, predict=True):
  46. f1s = []
  47. accuracies = []
  48. if predict:
  49. preds = pd.DataFrame(-1, index=list(range(X.shape[0])), columns=["pred"])
  50. for i, (train_index, test_index) in enumerate(kf.split(X, y)):
  51. X_train, X_test = X[train_index], X[test_index]
  52. y_train, y_test = y[train_index], y[test_index]
  53. if len(set(y_train)) == 1:
  54. y_pred = np.array([y_train[0]] * X_train.shape[0])
  55. else:
  56. clf.fit(X_train, y_train)
  57. y_pred = clf.predict(X_test)
  58. if predict:
  59. preds.loc[test_index, 'pred'] = y_pred
  60. f1s.append(f1_score(y_test, y_pred, average="weighted"))
  61. accuracies.append(accuracy_score(y_test, y_pred))
  62. f1s = np.array(f1s)
  63. accuracies = np.array(accuracies)
  64. if not predict:
  65. preds = None
  66. return f1s.mean(), f1s.std(), accuracies.mean(), accuracies.std(), preds
  67. class Objective:
  68. def __init__(
  69. self,
  70. df,
  71. kfold_params,
  72. code_col,
  73. target_col,
  74. svm_c,
  75. tfidf_min_df,
  76. tfidf_max_df,
  77. svm_kernel,
  78. svm_degree,
  79. ):
  80. self.kf = StratifiedKFold(**kfold_params)
  81. self.c_range = svm_c
  82. self.min_df_range = tfidf_min_df
  83. self.max_df_range = tfidf_max_df
  84. self.kernels = svm_kernel
  85. self.poly_degrees = svm_degree
  86. self.df = df
  87. self.code_col = code_col
  88. self.target_col = target_col
  89. def __call__(self, trial):
  90. tfidf_params = {
  91. "min_df": trial.suggest_int("tfidf__min_df", *self.min_df_range),
  92. "max_df": trial.suggest_loguniform("tfidf__max_df", *self.max_df_range),
  93. "smooth_idf": True,
  94. }
  95. code_blocks_tfidf = tfidf_fit_transform(self.df[self.code_col], tfidf_params)
  96. X, y = code_blocks_tfidf, self.df[self.target_col].values
  97. svm_params = {
  98. "C": trial.suggest_loguniform("svm__C", *self.c_range),
  99. "kernel": trial.suggest_categorical("svm__kernel", self.kernels),
  100. "random_state": RANDOM_STATE,
  101. "max_iter": MAX_ITER,
  102. }
  103. if svm_params["kernel"] == "poly":
  104. svm_params["degree"] = trial.suggest_int("svm__degree", *self.poly_degrees)
  105. clf = SVC(**svm_params)
  106. f1_mean, _, _, _, _ = cross_val_predict(self.kf, clf, X, y, False)
  107. return f1_mean
  108. def select_hyperparams(
  109. df,
  110. kfold_params,
  111. tfidf_path,
  112. model_path,
  113. code_col,
  114. target_col,
  115. n_trials,
  116. hyperparam_space,
  117. default_hyperparams,
  118. ):
  119. """
  120. Uses optuna to find hyperparams that maximize F1 score
  121. :param df: labelled dataset
  122. :param kfold_params: parameters for sklearn's KFold
  123. :param tfidf_path: where to save trained tf-idf
  124. :return: dict with parameters and metrics
  125. """
  126. study = optuna.create_study(direction="maximize", study_name="svm with kernels")
  127. objective = Objective(df, kfold_params, code_col, target_col, **hyperparam_space)
  128. if n_trials > 0:
  129. study.optimize(objective, n_trials=n_trials)
  130. params = study.best_params
  131. else:
  132. params = default_hyperparams
  133. best_tfidf_params = {
  134. "smooth_idf": True,
  135. }
  136. best_svm_params = {
  137. "random_state": RANDOM_STATE,
  138. "max_iter": MAX_ITER,
  139. }
  140. for key, value in params.items():
  141. model_name, param_name = key.split("__")
  142. if model_name == "tfidf":
  143. best_tfidf_params[param_name] = value
  144. elif model_name == "svm":
  145. best_svm_params[param_name] = value
  146. code_blocks_tfidf = tfidf_fit_transform(df[code_col], best_tfidf_params, tfidf_path)
  147. X, y = code_blocks_tfidf, df[target_col].values
  148. clf = SVC(**best_svm_params)
  149. f1_mean, f1_std, accuracy_mean, accuracy_std, preds = cross_val_predict(
  150. objective.kf, clf, X, y
  151. )
  152. if model_path is not None:
  153. clf.fit(X, y)
  154. pickle.dump(clf, open(model_path, "wb"))
  155. metrics = dict(
  156. test_f1_score=f1_mean,
  157. test_accuracy=accuracy_mean,
  158. test_f1_std=f1_std,
  159. test_accuracy_std=accuracy_std,
  160. )
  161. return best_tfidf_params, best_svm_params, metrics, preds
  162. if __name__ == "__main__":
  163. graph_df = pd.read_csv(GRAPH_VER, index_col=0)
  164. ver_to_sub = get_ver_to_sub(graph_df)
  165. df = load_data(DATASET_PATH, sep=";")
  166. codes, uniques = pd.factorize(get_vertices(df, ver_to_sub))
  167. df["graph_upper_vertex"] = codes
  168. print(df.columns)
  169. nrows = df.shape[0]
  170. print("loaded")
  171. kfold_params = {
  172. "n_splits": 10,
  173. "random_state": RANDOM_STATE,
  174. "shuffle": True,
  175. }
  176. print("selecting hyperparameters")
  177. tfidf_params, svm_params, metrics, preds_upper = select_hyperparams(
  178. df.drop(columns=["graph_vertex_id"]),
  179. kfold_params,
  180. TFIDF_DIR,
  181. MODEL_DIR,
  182. "code_block",
  183. "graph_upper_vertex",
  184. N_TRIALS,
  185. HYPERPARAM_SPACE,
  186. DEFAULT_HYPERPARAMS_UPPER,
  187. )
  188. print(
  189. "upper classifier hyperparams:", "\ntfidf", tfidf_params, "\nmodel", svm_params
  190. )
  191. print("metrics:", metrics)
  192. lower_vertex_params = dict()
  193. kfold_params = {
  194. "n_splits": 2,
  195. "random_state": RANDOM_STATE,
  196. "shuffle": True,
  197. }
  198. for vertex in range(len(uniques)):
  199. print("search params for", uniques[vertex])
  200. tfidf_params, svm_params, metrics, preds = select_hyperparams(
  201. df[df['graph_upper_vertex'] == vertex].reset_index().drop(columns=["graph_upper_vertex"]),
  202. kfold_params,
  203. TFIDF_DIR,
  204. None,
  205. "code_block",
  206. "graph_vertex_id",
  207. N_TRIALS,
  208. HYPERPARAM_SPACE,
  209. DEFAULT_HYPERPARAMS_UPPER,
  210. )
  211. lower_vertex_params[vertex] = (uniques[vertex], tfidf_params, svm_params)
  212. print(
  213. "lower classifier hyperparams for", uniques[vertex], ":", "\ntfidf", tfidf_params, "\nmodel", svm_params
  214. )
  215. # df['upper_pred'] = -1
  216. df['upper_pred'] = preds_upper['pred']
  217. final_preds = pd.DataFrame(-1, index=list(range(len(df))), columns=["pred"])
  218. kf = KFold(**kfold_params)
  219. for vertex in range(len(uniques)):
  220. idx = df[df['upper_pred'] == vertex].index
  221. df_sub = df.loc[idx].copy()
  222. df_sub = df_sub.drop(columns=["graph_upper_vertex", 'upper_pred'])
  223. _, best_tfidf_params, best_svm_params = lower_vertex_params[vertex]
  224. try:
  225. code_blocks_tfidf = tfidf_fit_transform(df_sub["code_block"], best_tfidf_params, TFIDF_DIR)
  226. except ValueError:
  227. # for min_df > max_df
  228. best_tfidf_params["min_df"] = 1
  229. best_tfidf_params["max_df"] = 0.99
  230. code_blocks_tfidf = tfidf_fit_transform(df_sub["code_block"], best_tfidf_params, TFIDF_DIR)
  231. X, y = code_blocks_tfidf, df_sub["graph_vertex_id"].values
  232. clf = SVC(**best_svm_params)
  233. _, _, _, _, preds_sub = cross_val_predict(
  234. kf, clf, X, y
  235. )
  236. final_preds.loc[idx, 'pred'] = preds_sub['pred'].values
  237. print("F1 total:", f1_score(df["graph_vertex_id"], final_preds['pred'], average="weighted"))
  238. print("Accuracy total:", accuracy_score(df["graph_vertex_id"], final_preds['pred']))
  239. print("finished")
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...