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

boosting_train.py 5.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
  1. import argparse
  2. import os
  3. import pickle
  4. import sys
  5. from catboost import CatBoostClassifier
  6. import numpy as np
  7. import optuna
  8. import pandas as pd
  9. from sklearn.metrics import accuracy_score, f1_score
  10. from sklearn.model_selection import KFold
  11. from common.tools import *
  12. parser = argparse.ArgumentParser()
  13. parser.add_argument("GRAPH_VER", help="version of the graph you want regex to label your CSV with", type=str)
  14. parser.add_argument("DATASET_PATH", help="path to your input CSV", type=str)
  15. args = parser.parse_args()
  16. GRAPH_VER = args.GRAPH_VER
  17. DATASET_PATH = args.DATASET_PATH
  18. MODEL_DIR = "../models/catboost_regex_graph_v{}.sav".format(GRAPH_VER)
  19. TFIDF_DIR = "../models/tfidf_catboost_graph_v{}.pickle".format(GRAPH_VER)
  20. TAGS_TO_PREDICT = get_graph_vertices(GRAPH_VER)
  21. EXPERIMENT_DATA_PATH = ".."
  22. CODE_COLUMN = "code_block"
  23. TARGET_COLUMN = "graph_vertex_id"
  24. RANDOM_STATE = 42
  25. N_TRIALS = 30
  26. HYPERPARAM_SPACE = {
  27. "tfidf_min_df": (1, 15),
  28. "tfidf_max_df": (0.2, 0.95),
  29. "catboost_lr": (0.1, 1.0),
  30. "catboost_iter": (100, 1500),
  31. "catboost_depth": (3, 6),
  32. }
  33. def cross_val_scores(kf, clf, X, y):
  34. f1s = []
  35. accuracies = []
  36. for i, (train_index, test_index) in enumerate(kf.split(X)):
  37. X_train, X_test = X[train_index], X[test_index]
  38. y_train, y_test = y[train_index], y[test_index]
  39. clf.fit(X_train, y_train)
  40. y_pred = clf.predict(X_test)
  41. f1s.append(f1_score(y_test, y_pred, average="weighted"))
  42. accuracies.append(accuracy_score(y_test, y_pred))
  43. f1s = np.array(f1s)
  44. accuracies = np.array(accuracies)
  45. return f1s.mean(), accuracies.mean()
  46. class Objective:
  47. def __init__(self, df, kfold_params, tfidf_min_df, tfidf_max_df, catboost_lr, catboost_iter, catboost_depth):
  48. self.kf = KFold(**kfold_params)
  49. self.df = df
  50. self.min_df_range = tfidf_min_df
  51. self.max_df_range = tfidf_max_df
  52. self.lr_range = catboost_lr
  53. self.max_iter_range = catboost_iter
  54. self.depth_range = catboost_depth
  55. def __call__(self, trial):
  56. tfidf_params = {
  57. "min_df": trial.suggest_int("tfidf__min_df", *self.min_df_range),
  58. "max_df": trial.suggest_loguniform("tfidf__max_df", *self.max_df_range),
  59. "smooth_idf": True,
  60. }
  61. code_blocks_tfidf = tfidf_fit_transform(self.df[CODE_COLUMN], tfidf_params)
  62. X, y = code_blocks_tfidf, self.df[TARGET_COLUMN].values
  63. boosting_params = {
  64. "learning_rate": trial.suggest_loguniform("boosting__learning_rate", *self.lr_range),
  65. "iterations": trial.suggest_int("boosting__iterations", *self.max_iter_range),
  66. "depth": trial.suggest_int("boosting__depth", *self.depth_range),
  67. "random_seed": RANDOM_STATE,
  68. "verbose": False,
  69. }
  70. clf = CatBoostClassifier(**boosting_params)
  71. f1_mean, _ = cross_val_scores(self.kf, clf, X, y)
  72. return f1_mean
  73. def select_hyperparams(df, kfold_params, tfidf_path, model_path):
  74. """
  75. Uses optuna to find hyperparams that maximize F1 score
  76. :param df: labelled dataset
  77. :param kfold_params: parameters for sklearn's KFold
  78. :param tfidf_dir: where to save trained tf-idf
  79. :return: dict with parameters and metrics
  80. """
  81. study = optuna.create_study(direction="maximize", study_name="boosting")
  82. objective = Objective(df, kfold_params, **HYPERPARAM_SPACE)
  83. study.optimize(objective, n_trials=N_TRIALS)
  84. best_tfidf_params = {
  85. "smooth_idf": True,
  86. }
  87. best_boosting_params = {
  88. "random_seed": RANDOM_STATE,
  89. "verbose": False,
  90. }
  91. for key, value in study.best_params.items():
  92. model_name, param_name = key.split("__")
  93. if model_name == "tfidf":
  94. best_tfidf_params[param_name] = value
  95. elif model_name == "boosting":
  96. best_boosting_params[param_name] = value
  97. code_blocks_tfidf = tfidf_fit_transform(df[CODE_COLUMN], best_tfidf_params, tfidf_path)
  98. X, y = code_blocks_tfidf, df[TARGET_COLUMN].values
  99. clf = CatBoostClassifier(**best_boosting_params)
  100. f1_mean, accuracy_mean = cross_val_scores(objective.kf, clf, X, y)
  101. clf.fit(X, y)
  102. pickle.dump(clf, open(model_path, "wb"))
  103. metrics = dict(test_f1_score=f1_mean, test_accuracy=accuracy_mean)
  104. return best_tfidf_params, best_boosting_params, metrics
  105. if __name__ == "__main__":
  106. df = load_data(DATASET_PATH)
  107. print(df.columns)
  108. nrows = df.shape[0]
  109. print("loaded")
  110. kfold_params = {
  111. "n_splits": 3,
  112. "random_state": RANDOM_STATE,
  113. "shuffle": True,
  114. }
  115. data_meta = {
  116. "DATASET_PATH": DATASET_PATH,
  117. "nrows": nrows,
  118. "label": TAGS_TO_PREDICT,
  119. "model": MODEL_DIR,
  120. "script_dir": __file__,
  121. }
  122. print("selecting hyperparameters")
  123. tfidf_params, boosting_params, metrics = select_hyperparams(df, kfold_params, TFIDF_DIR, MODEL_DIR)
  124. print("hyperparams:", "\nboosting", boosting_params, "\ntfidf", tfidf_params)
  125. print("metrics:", metrics)
  126. print("finished")
Tip!

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

Comments

Loading...