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

svm_oversampling.py 6.0 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
  1. import argparse
  2. import os
  3. import pickle
  4. import sys
  5. import numpy as np
  6. import optuna
  7. import pandas as pd
  8. from sklearn.metrics import accuracy_score, f1_score
  9. from sklearn.model_selection import StratifiedKFold
  10. from sklearn.svm import SVC
  11. import itertools, random
  12. import scipy as sp
  13. from sklearn.model_selection import train_test_split
  14. from imblearn.over_sampling import SMOTE
  15. from common.tools import *
  16. parser = argparse.ArgumentParser()
  17. parser.add_argument("GRAPH_VER", help="version of the graph you want regex to label your CSV with", type=str)
  18. parser.add_argument("DATASET_PATH", help="path to your input CSV", type=str)
  19. args = parser.parse_args()
  20. GRAPH_VER = args.GRAPH_VER
  21. DATASET_PATH = args.DATASET_PATH
  22. MODEL_DIR = "../models/linear_svm_regex_graph_v{}.sav".format(GRAPH_VER)
  23. TFIDF_DIR = "../models/tfidf_svm_graph_v{}.pickle".format(GRAPH_VER)
  24. TAGS_TO_PREDICT = get_graph_vertices(GRAPH_VER)
  25. EXPERIMENT_DATA_PATH = ".."
  26. CODE_COLUMN = "code_block"
  27. TARGET_COLUMN = "graph_vertex_id"
  28. RANDOM_STATE = 42
  29. N_TRIALS = 70
  30. MAX_ITER = 10000
  31. HYPERPARAM_SPACE = {
  32. "svm_c": (1e-1, 1e3),
  33. "tfidf_min_df": (1, 50),
  34. "tfidf_max_df": (0.2, 1.0),
  35. "svm_kernel": ["linear", "poly", "rbf"],
  36. "svm_degree": (2, 6), # in case of poly kernel
  37. }
  38. def cross_val_scores(kf, clf, X, y):
  39. f1s = []
  40. accuracies = []
  41. for i, (train_index, test_index) in enumerate(kf.split(X)):
  42. X_train, X_test = X[train_index], X[test_index]
  43. y_train, y_test = y[train_index], y[test_index]
  44. clf.fit(X_train, y_train)
  45. y_pred = clf.predict(X_test)
  46. f1s.append(f1_score(y_test, y_pred, average="weighted"))
  47. accuracies.append(accuracy_score(y_test, y_pred))
  48. f1s = np.array(f1s)
  49. accuracies = np.array(accuracies)
  50. return f1s.mean(), accuracies.mean()
  51. def cross_val_scores_smote(kf, clf, X, y):
  52. f1s = []
  53. accuracies = []
  54. for i, (train_index, test_index) in enumerate(kf.split(X, y)):
  55. X_train, X_test = X[train_index], X[test_index]
  56. y_train, y_test = y[train_index], y[test_index]
  57. sm = SMOTE(random_state=RANDOM_STATE, sampling_strategy='not majority', k_neighbors=3)
  58. X_train, y_train = sm.fit_resample(X_train, y_train)
  59. clf.fit(X_train, y_train)
  60. y_pred = clf.predict(X_test)
  61. f1s.append(f1_score(y_test, y_pred, average="weighted"))
  62. accuracies.append(accuracy_score(y_test, y_pred))
  63. f1s = np.array(f1s)
  64. accuracies = np.array(accuracies)
  65. return f1s.mean(), f1s.std(), accuracies.mean(), accuracies.std()
  66. class Objective:
  67. def __init__(self, df, kfold_params, svm_c, tfidf_min_df, tfidf_max_df, svm_kernel, svm_degree):
  68. self.kf = StratifiedKFold(**kfold_params)
  69. self.c_range = svm_c
  70. self.min_df_range = tfidf_min_df
  71. self.max_df_range = tfidf_max_df
  72. self.kernels = svm_kernel
  73. self.poly_degrees = svm_degree
  74. self.df = df
  75. def __call__(self, trial):
  76. tfidf_params = {
  77. "min_df": trial.suggest_int("tfidf__min_df", *self.min_df_range),
  78. "max_df": trial.suggest_loguniform("tfidf__max_df", *self.max_df_range),
  79. "smooth_idf": True,
  80. }
  81. code_blocks_tfidf = tfidf_fit_transform(self.df[CODE_COLUMN], tfidf_params)
  82. X, y = code_blocks_tfidf, self.df[TARGET_COLUMN].values
  83. svm_params = {
  84. "C": trial.suggest_loguniform("svm__C", *self.c_range),
  85. "kernel": trial.suggest_categorical("svm__kernel", self.kernels),
  86. "random_state": RANDOM_STATE,
  87. "max_iter": MAX_ITER,
  88. }
  89. if svm_params["kernel"] == "poly":
  90. svm_params["degree"] = trial.suggest_int("svm__degree", *self.poly_degrees)
  91. clf = SVC(**svm_params)
  92. f1, _, _, _ = cross_val_scores_smote(self.kf, clf, X, y)
  93. return f1
  94. def select_hyperparams(df, kfold_params, tfidf_path, model_path):
  95. """
  96. Uses optuna to find hyperparams that maximize F1 score
  97. :param df: labelled dataset
  98. :param kfold_params: parameters for sklearn's KFold
  99. :param tfidf_dir: where to save trained tf-idf
  100. :return: dict with parameters and metrics
  101. """
  102. study = optuna.create_study(direction="maximize", study_name="svm with oversampling")
  103. objective = Objective(df, kfold_params, **HYPERPARAM_SPACE)
  104. study.optimize(objective, n_trials=N_TRIALS)
  105. best_tfidf_params = {
  106. "smooth_idf": True,
  107. }
  108. best_svm_params = {
  109. "random_state": RANDOM_STATE,
  110. "max_iter": MAX_ITER,
  111. }
  112. for key, value in study.best_params.items():
  113. model_name, param_name = key.split("__")
  114. if model_name == "tfidf":
  115. best_tfidf_params[param_name] = value
  116. elif model_name == "svm":
  117. best_svm_params[param_name] = value
  118. code_blocks_tfidf = tfidf_fit_transform(df[CODE_COLUMN], best_tfidf_params, tfidf_path)
  119. X, y = code_blocks_tfidf, df[TARGET_COLUMN].values
  120. clf = SVC(**best_svm_params)
  121. f1_mean, f1_std, accuracy_mean, accuracy_std = cross_val_scores_smote(objective.kf, clf, X, y)
  122. sm = SMOTE(random_state=RANDOM_STATE, sampling_strategy='not majority', k_neighbors=3)
  123. X, y = sm.fit_resample(X, y)
  124. clf.fit(X, y)
  125. pickle.dump(clf, open(model_path, "wb"))
  126. metrics = dict(
  127. test_f1_score=f1_mean,
  128. test_accuracy=accuracy_mean,
  129. test_f1_std=f1_std,
  130. test_accuracy_std=accuracy_std,
  131. )
  132. return best_tfidf_params, best_svm_params, metrics
  133. if __name__ == "__main__":
  134. df = load_data(DATASET_PATH)
  135. print(df.columns)
  136. nrows = df.shape[0]
  137. print("loaded")
  138. kfold_params = {
  139. "n_splits": 9,
  140. "random_state": RANDOM_STATE,
  141. "shuffle": True,
  142. }
  143. data_meta = {
  144. "DATASET_PATH": DATASET_PATH,
  145. "nrows": nrows,
  146. "label": TAGS_TO_PREDICT,
  147. "model": MODEL_DIR,
  148. "script_dir": __file__,
  149. }
  150. print("selecting hyperparameters")
  151. tfidf_params, svm_params, metrics = select_hyperparams(df, kfold_params, TFIDF_DIR, MODEL_DIR)
  152. print("hyperparams:", "\ntfidf", tfidf_params, "\nmodel", svm_params)
  153. print("metrics:", metrics)
  154. print("finished")
Tip!

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

Comments

Loading...