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

training.py 5.3 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
  1. import dagshub
  2. import os
  3. import pandas as pd
  4. import yaml
  5. import re
  6. import numpy as np
  7. import joblib
  8. from scipy.sparse.dia import dia_matrix
  9. from sklearn.feature_extraction.text import TfidfVectorizer
  10. from sklearn.linear_model import SGDClassifier
  11. from sklearn.metrics import (
  12. roc_auc_score,
  13. average_precision_score,
  14. accuracy_score,
  15. precision_score,
  16. recall_score,
  17. f1_score,
  18. )
  19. with open(r"./general_params.yml") as f:
  20. params = yaml.safe_load(f)
  21. with open(r"./training_params.yml") as f:
  22. training_params = yaml.safe_load(f)
  23. NUM_COL_NAMES = ["title_len", "body_len", "hour", "minute", "dayofweek", "dayofyear"]
  24. CAT_COL_NAMES = [
  25. "has_thumbnail",
  26. "flair_Clickbait",
  27. "flair_Discussion",
  28. "flair_Inaccurate",
  29. "flair_Misleading",
  30. "flair_News",
  31. "flair_None",
  32. "flair_Project",
  33. "flair_Research",
  34. "flair_Shameless Self Promo",
  35. ]
  36. CHUNK_SIZE = params["chunk_size"]
  37. TARGET_LABEL = params["target_col"]
  38. MODEL_TYPE_TEXT = "model_text"
  39. MODEL_TYPE_NUM_CAT = "model_num_cat"
  40. MODEL_TYPE_OTHER = ""
  41. MODEL_TYPE = (
  42. MODEL_TYPE_TEXT
  43. if training_params["use_text_cols"]
  44. else MODEL_TYPE_NUM_CAT
  45. if training_params["use_number_category_cols"]
  46. else MODEL_TYPE_OTHER
  47. )
  48. local_path = "."
  49. train_df_path = "rML-train.csv"
  50. tfidf_path = "models/tfidf.pkl"
  51. model_path = "models/model.pkl"
  52. # ----- Helper Functions -----
  53. # A partial fit for the TfidfVectorizer courtesy @maxymoo on Stack Overflow
  54. # https://stackoverflow.com/questions/39109743/adding-new-text-to-sklearn-tfidif-vectorizer-python/39114555#39114555
  55. def partial_fit(self, X):
  56. # If this is the first iteration, use regular fit
  57. if not hasattr(self, "is_initialized"):
  58. self.fit(X)
  59. self.n_docs = len(X)
  60. self.is_initialized = True
  61. else:
  62. max_idx = max(self.vocabulary_.values())
  63. for a in X:
  64. # update vocabulary_
  65. if self.lowercase:
  66. a = str(a).lower()
  67. tokens = re.findall(self.token_pattern, a)
  68. for w in tokens:
  69. if w not in self.vocabulary_:
  70. max_idx += 1
  71. self.vocabulary_[w] = max_idx
  72. # update idf_
  73. df = (self.n_docs + self.smooth_idf) / np.exp(
  74. self.idf_ - 1
  75. ) - self.smooth_idf
  76. self.n_docs += 1
  77. df.resize(len(self.vocabulary_))
  78. for w in tokens:
  79. df[self.vocabulary_[w]] += 1
  80. idf = np.log((self.n_docs + self.smooth_idf) / (df + self.smooth_idf)) + 1
  81. self._tfidf._idf_diag = dia_matrix((idf, 0), shape=(len(idf), len(idf)))
  82. # Prepare a dictionary of either hyperparams or metrics for logging.
  83. def prepare_log(d, prefix=''):
  84. if prefix:
  85. prefix = f'{prefix}__'
  86. # Ensure all logged values are suitable for logging - complex objects aren't supported.
  87. def sanitize(value):
  88. return value if value is None or type(value) in [str, int, float, bool] else str(value)
  89. return {f'{prefix}{k}': sanitize(v) for k, v in d.items()}
  90. # ----- End Helper Functions -----
  91. class TextModel:
  92. def __init__(self, random_state=42):
  93. self.model = SGDClassifier(loss="log", random_state=random_state)
  94. print("Generate TFIDF features...")
  95. TfidfVectorizer.partial_fit = partial_fit
  96. self.tfidf = TfidfVectorizer(max_features=25000)
  97. for i, chunk in enumerate(
  98. pd.read_csv(os.path.join(remote_wfs, train_df_path), chunksize=CHUNK_SIZE)
  99. ):
  100. print(f"Training on chunk {i+1}...")
  101. self.tfidf.partial_fit(chunk["title_and_body"])
  102. print("TFIDF feature matrix created!")
  103. def train_on_chunk(self, chunk):
  104. df_y = chunk[TARGET_LABEL]
  105. tfidf_X = self.tfidf.transform(chunk["title_and_body"].values.astype('U'))
  106. self.model.partial_fit(tfidf_X, df_y, classes=np.array([0, 1]))
  107. def save_model(self, logger=None):
  108. joblib.dump(self.tfidf, os.path.join(local_path, tfidf_path))
  109. joblib.dump(self.model, os.path.join(local_path, model_path))
  110. # log params
  111. if logger:
  112. logger.log_hyperparams(prepare_log(self.tfidf.get_params(), 'tfidf'))
  113. logger.log_hyperparams(prepare_log(self.model.get_params(), 'model'))
  114. logger.log_hyperparams(model_class=type(self.model).__name__)
  115. def get_remote_gs_wfs():
  116. print("Retreiving location of remote working file system...")
  117. stream = os.popen("dvc remote list --local")
  118. output = stream.read()
  119. remote_wfs_loc = output.split("\t")[1].split("\n")[0]
  120. return remote_wfs_loc
  121. def load_and_train(remote_wfs, model_type=None, random_state=42):
  122. print("Initializing models...")
  123. if model_type == MODEL_TYPE_TEXT:
  124. model = TextModel(random_state=random_state)
  125. else:
  126. # TODO
  127. return
  128. print("Training model...")
  129. for i, chunk in enumerate(
  130. pd.read_csv(os.path.join(remote_wfs, train_df_path), chunksize=CHUNK_SIZE)
  131. ):
  132. print(f"Training on chunk {i+1}...")
  133. model.train_on_chunk(chunk)
  134. print("Saving models locally...")
  135. with dagshub.dagshub_logger() as logger:
  136. logger.log_hyperparams(feature_type='text')
  137. model.save_model(logger=logger)
  138. if __name__ == "__main__":
  139. remote_wfs = get_remote_gs_wfs()
  140. load_and_train(remote_wfs, MODEL_TYPE)
  141. print("Loading and training done!")
Tip!

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

Comments

Loading...