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

naive_bayes_train.py 5.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
  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.naive_bayes import MultinomialNB, ComplementNB
  11. from tokenizers import Tokenizer
  12. from common.tools import *
  13. parser = argparse.ArgumentParser()
  14. parser.add_argument("GRAPH_VER", help="version of the graph you want regex to label your CSV with", type=str)
  15. parser.add_argument("DATASET_PATH", help="path to your input CSV", type=str)
  16. args = parser.parse_args()
  17. GRAPH_VER = args.GRAPH_VER
  18. DATASET_PATH = args.DATASET_PATH
  19. TOKENIZER_PATH = "../models/bpe_tokenizer.json"
  20. MODEL_DIR = "../models/nb_graph_v{}.sav".format(GRAPH_VER)
  21. COUNTVEC_DIR = "../models/countvec_nb_graph_v{}.pickle".format(GRAPH_VER)
  22. TAGS_TO_PREDICT = get_graph_vertices(GRAPH_VER)
  23. EXPERIMENT_DATA_PATH = ".."
  24. CODE_COLUMN = "code_block"
  25. TARGET_COLUMN = "graph_vertex_id"
  26. RANDOM_STATE = 42
  27. N_TRIALS = 100
  28. HYPERPARAM_SPACE = {
  29. "tfidf_min_df": (1, 20),
  30. "tfidf_max_df": (0.3, 1.0),
  31. "nb_type": ("ComplementNB", "MultinomialNB"),
  32. "nb_alpha": (1e-6, 10),
  33. }
  34. def cross_val_scores(kf, clf, X, y):
  35. f1s = []
  36. accuracies = []
  37. for i, (train_index, test_index) in enumerate(kf.split(X, y)):
  38. X_train, X_test = X[train_index], X[test_index]
  39. y_train, y_test = y[train_index], y[test_index]
  40. clf.fit(X_train, y_train)
  41. y_pred = clf.predict(X_test)
  42. f1s.append(f1_score(y_test, y_pred, average="weighted"))
  43. accuracies.append(accuracy_score(y_test, y_pred))
  44. f1s = np.array(f1s)
  45. accuracies = np.array(accuracies)
  46. return f1s.mean(), accuracies.mean()
  47. class Objective:
  48. def __init__(self, df, kfold_params, tfidf_min_df, tfidf_max_df, nb_type, nb_alpha):
  49. self.kf = StratifiedKFold(**kfold_params)
  50. self.min_df_range = tfidf_min_df
  51. self.max_df_range = tfidf_max_df
  52. self.nbs = nb_type
  53. self.alpha_range = nb_alpha
  54. self.df = df
  55. self.tokenizer = make_tokenizer(Tokenizer.from_file(TOKENIZER_PATH))
  56. def __call__(self, trial):
  57. tfidf_params = {
  58. "min_df": trial.suggest_int("tfidf__min_df", *self.min_df_range),
  59. "max_df": trial.suggest_loguniform("tfidf__max_df", *self.max_df_range),
  60. "smooth_idf": True,
  61. "tokenizer": self.tokenizer,
  62. }
  63. code_blocks_tfidf = tfidf_fit_transform(self.df[CODE_COLUMN], tfidf_params)
  64. X, y = code_blocks_tfidf, self.df[TARGET_COLUMN].values
  65. nb_params = {
  66. "alpha": trial.suggest_loguniform("nb__alpha", *self.alpha_range)
  67. }
  68. nb_type = trial.suggest_categorical("nb__nb_type", self.nbs)
  69. if nb_type == "ComplementNB":
  70. clf = ComplementNB(**nb_params)
  71. else:
  72. clf = MultinomialNB(**nb_params)
  73. f1_mean, _ = cross_val_scores(self.kf, clf, X, y)
  74. return f1_mean
  75. def select_hyperparams(df, kfold_params, cntvec_path, model_path):
  76. """
  77. Uses optuna to find hyperparams that maximize F1 score
  78. :param df: labelled dataset
  79. :param kfold_params: parameters for sklearn's KFold
  80. :param tfidf_dir: where to save trained tf-idf
  81. :return: dict with parameters and metrics
  82. """
  83. study = optuna.create_study(direction="maximize", study_name="svm with kernels")
  84. objective = Objective(df, kfold_params, **HYPERPARAM_SPACE)
  85. study.optimize(objective, n_trials=N_TRIALS)
  86. best_tfidf_params = {
  87. "smooth_idf": True,
  88. "tokenizer": make_tokenizer(Tokenizer.from_file(TOKENIZER_PATH)),
  89. }
  90. best_nb_params = dict()
  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 == "nb":
  96. best_nb_params[param_name] = value
  97. code_blocks_tfidf = tfidf_fit_transform(df[CODE_COLUMN], best_tfidf_params)
  98. X, y = code_blocks_tfidf, df[TARGET_COLUMN].values
  99. nb_type = best_nb_params["nb_type"]
  100. best_nb_params.pop("nb_type")
  101. if nb_type == "ComplementNB":
  102. clf = ComplementNB(**best_nb_params)
  103. else:
  104. clf = MultinomialNB(**best_nb_params)
  105. best_nb_params["nb_type"] = nb_type
  106. f1_mean, accuracy_mean = cross_val_scores(objective.kf, clf, X, y)
  107. clf.fit(X, y)
  108. pickle.dump(clf, open(model_path, "wb"))
  109. best_tfidf_params["tokenizer"] = "BPE"
  110. metrics = dict(test_f1_score=f1_mean, test_accuracy=accuracy_mean)
  111. return best_tfidf_params, best_nb_params, metrics
  112. if __name__ == "__main__":
  113. df = load_data(DATASET_PATH)
  114. print(df.columns)
  115. nrows = df.shape[0]
  116. print("loaded")
  117. kfold_params = {
  118. "n_splits": 6,
  119. "random_state": RANDOM_STATE,
  120. "shuffle": True,
  121. }
  122. data_meta = {
  123. "DATASET_PATH": DATASET_PATH,
  124. "nrows": nrows,
  125. "label": TAGS_TO_PREDICT,
  126. "model": MODEL_DIR,
  127. "script_dir": __file__,
  128. }
  129. print("selecting hyperparameters")
  130. cntvec_params, nb_params, metrics = select_hyperparams(df, kfold_params, COUNTVEC_DIR, MODEL_DIR)
  131. print("hyperparams:", "\ncountvec", cntvec_params, "\nmodel", nb_params)
  132. print("metrics:", metrics)
  133. print("finished")
Tip!

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

Comments

Loading...