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_hyperparam_train.py 6.2 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
  1. import argparse
  2. import logging
  3. import os
  4. import pickle
  5. import sys
  6. import numpy as np
  7. import optuna
  8. import pandas as pd
  9. from sklearn.ensemble import BaggingClassifier
  10. from sklearn.metrics import accuracy_score, f1_score
  11. from sklearn.model_selection import KFold
  12. from sklearn.svm import SVC
  13. from common.tools import *
  14. optuna.logging.get_logger("optuna").addHandler(logging.StreamHandler(sys.stdout))
  15. parser = argparse.ArgumentParser()
  16. parser.add_argument("GRAPH_VER", help="version of the graph you want regex to label your CSV with", type=str)
  17. parser.add_argument("DATASET_PATH", help="path to your input CSV", type=str)
  18. args = parser.parse_args()
  19. GRAPH_VER = args.GRAPH_VER
  20. DATASET_PATH = args.DATASET_PATH
  21. MODEL_DIR = "../models/hyper_svm_regex_graph_v{}.sav".format(GRAPH_VER)
  22. TFIDF_DIR = "../models/tfidf_hyper_svm_graph_v{}.pickle".format(GRAPH_VER)
  23. TAGS_TO_PREDICT = get_graph_vertices(GRAPH_VER)
  24. EXPERIMENT_DATA_PATH = ".."
  25. CODE_COLUMN = "code_block"
  26. TARGET_COLUMN = "graph_vertex_id"
  27. RANDOM_STATE = 42
  28. N_TRIALS = 20
  29. MAX_ITER = 10000
  30. HYPERPARAM_SPACE = {
  31. "svm_c": (1e-1, 1e3),
  32. "tfidf_min_df": (1, 10),
  33. "tfidf_max_df": (0.2, 0.7),
  34. "svm_kernel": ["linear", "poly", "rbf"],
  35. "svm_degree": (2, 6), # in case of poly kernel
  36. "b_estimators": (3, 10),
  37. "b_max_samples": (0.5, 1.0),
  38. "b_max_features": (0.8, 1.0),
  39. }
  40. def cross_val_scores(kf, clf, X, y):
  41. f1s = []
  42. accuracies = []
  43. for i, (train_index, test_index) in enumerate(kf.split(X)):
  44. X_train, X_test = X[train_index], X[test_index]
  45. y_train, y_test = y[train_index], y[test_index]
  46. clf.fit(X_train, y_train)
  47. y_pred = clf.predict(X_test)
  48. f1s.append(f1_score(y_test, y_pred, average="weighted"))
  49. accuracies.append(accuracy_score(y_test, y_pred))
  50. f1s = np.array(f1s)
  51. accuracies = np.array(accuracies)
  52. return f1s.mean(), f1s.std(), accuracies.mean(), accuracies.std()
  53. class Objective:
  54. def __init__(self, df, kfold_params, svm_c, tfidf_min_df, tfidf_max_df, svm_kernel, svm_degree, b_estimators, b_max_samples, b_max_features):
  55. self.kf = KFold(**kfold_params)
  56. self.c_range = svm_c
  57. self.min_df_range = tfidf_min_df
  58. self.max_df_range = tfidf_max_df
  59. self.kernels = svm_kernel
  60. self.poly_degrees = svm_degree
  61. self.n_estimators_range = b_estimators
  62. self.max_samples_range = b_max_samples
  63. self.max_features_range = b_max_features
  64. self.df = df
  65. def __call__(self, trial):
  66. tfidf_params = {
  67. "min_df": trial.suggest_int("tfidf__min_df", *self.min_df_range),
  68. "max_df": trial.suggest_loguniform("tfidf__max_df", *self.max_df_range),
  69. "smooth_idf": True,
  70. }
  71. code_blocks_tfidf = tfidf_fit_transform(self.df[CODE_COLUMN], tfidf_params)
  72. X, y = code_blocks_tfidf.toarray(), self.df[TARGET_COLUMN].values
  73. svm_params = {
  74. "C": trial.suggest_loguniform("svm__C", *self.c_range),
  75. "kernel": trial.suggest_categorical("svm__kernel", self.kernels),
  76. "random_state": RANDOM_STATE,
  77. "max_iter": MAX_ITER,
  78. }
  79. if svm_params["kernel"] == "poly":
  80. svm_params["degree"] = trial.suggest_int("svm__degree", *self.poly_degrees)
  81. bagging_params = {
  82. "base_estimator": SVC(**svm_params),
  83. "n_estimators": trial.suggest_int("bagging__n_estimators", *self.n_estimators_range),
  84. "max_samples": trial.suggest_loguniform("bagging__max_samples", *self.max_samples_range),
  85. "max_features": trial.suggest_loguniform("bagging__max_features", *self.max_features_range),
  86. "random_state": RANDOM_STATE,
  87. }
  88. clf = BaggingClassifier(**bagging_params)
  89. f1_mean, _, _, _ = cross_val_scores(self.kf, clf, X, y)
  90. return f1_mean
  91. def select_hyperparams(df, kfold_params, tfidf_path, model_path):
  92. """
  93. Uses optuna to find hyperparams that maximize F1 score
  94. :param df: labelled dataset
  95. :param kfold_params: parameters for sklearn's KFold
  96. :param tfidf_dir: where to save trained tf-idf
  97. :return: dict with parameters and metrics
  98. """
  99. study = optuna.create_study(direction="maximize", study_name="svm with kernels")
  100. objective = Objective(df, kfold_params, **HYPERPARAM_SPACE)
  101. study.optimize(objective, n_trials=N_TRIALS)
  102. best_tfidf_params = {
  103. "smooth_idf": True,
  104. }
  105. best_svm_params = {
  106. "random_state": RANDOM_STATE,
  107. "max_iter": MAX_ITER,
  108. }
  109. best_bagging_params = {
  110. "random_state": RANDOM_STATE
  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. elif model_name == "bagging":
  119. best_bagging_params[param_name] = value
  120. code_blocks_tfidf = tfidf_fit_transform(df[CODE_COLUMN], best_tfidf_params, tfidf_path)
  121. X, y = code_blocks_tfidf.toarray(), df[TARGET_COLUMN].values
  122. clf = BaggingClassifier(base_estimator=SVC(**best_svm_params), **best_bagging_params)
  123. f1_mean, f1_std, accuracy_mean, accuracy_std = cross_val_scores(objective.kf, clf, 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, best_bagging_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": 15,
  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, bagging_params, metrics = select_hyperparams(df, kfold_params, TFIDF_DIR, MODEL_DIR)
  152. print("hyperparams:", "\ntfidf", tfidf_params, "\nbagging", bagging_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...