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_num_cat.py 4.6 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
  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. TRAIN_TFIDF = training_params["use_text_cols"]
  39. TRAIN_NUM_CAT = training_params["use_number_category_cols"]
  40. local_path = "."
  41. train_df_path = "rML-train.csv"
  42. tfidf_path = "models/tfidf.pkl"
  43. clf_tfidf_path = "models/tfidf.pkl"
  44. clf_num_cat_path = "models/tfidf.pkl"
  45. # ----- Helper Functions -----
  46. # A partial fit for the TfidfVectorizer courtesy @maxymoo on Stack Overflow
  47. # https://stackoverflow.com/questions/39109743/adding-new-text-to-sklearn-tfidif-vectorizer-python/39114555#39114555
  48. def partial_fit(self, X):
  49. # If this is the first iteration, use regular fit
  50. if not hasattr(self, 'is_initialized'):
  51. self.fit(X)
  52. self.n_docs = len(X)
  53. self.is_initialized = True
  54. else:
  55. max_idx = max(self.vocabulary_.values())
  56. for a in X:
  57. # update vocabulary_
  58. if self.lowercase:
  59. a = str(a).lower()
  60. tokens = re.findall(self.token_pattern, a)
  61. for w in tokens:
  62. if w not in self.vocabulary_:
  63. max_idx += 1
  64. self.vocabulary_[w] = max_idx
  65. # update idf_
  66. df = (self.n_docs + self.smooth_idf) / np.exp(
  67. self.idf_ - 1
  68. ) - self.smooth_idf
  69. self.n_docs += 1
  70. df.resize(len(self.vocabulary_))
  71. for w in tokens:
  72. df[self.vocabulary_[w]] += 1
  73. idf = (
  74. np.log((self.n_docs + self.smooth_idf) / (df + self.smooth_idf)) + 1
  75. )
  76. self._tfidf._idf_diag = dia_matrix((idf, 0), shape=(len(idf), len(idf)))
  77. # ----- End Helper Functions -----
  78. def get_remote_gs_wfs():
  79. print("Retreiving location of remote working file system...")
  80. stream = os.popen("dvc remote list --local")
  81. output = stream.read()
  82. remote_wfs_loc = output.split("\t")[1].split("\n")[0]
  83. return remote_wfs_loc
  84. def load_and_train(remote_wfs, random_state=42):
  85. print("Initializing models...")
  86. if TRAIN_TFIDF:
  87. clf_tfidf = SGDClassifier(loss="log", random_state=random_state)
  88. print("Generate TFIDF features...")
  89. TfidfVectorizer.partial_fit = partial_fit
  90. tfidf = TfidfVectorizer(max_features=25000)
  91. for i, chunk in enumerate(
  92. pd.read_csv(os.path.join(remote_wfs, train_df_path), chunksize=CHUNK_SIZE)
  93. ):
  94. print(f"Training on chunk {i+1}...")
  95. tfidf.partial_fit(chunk["title_and_body"])
  96. print("TFIDF feature matrix created!")
  97. if TRAIN_NUM_CAT:
  98. num_cat_cols = NUM_COL_NAMES + CAT_COL_NAMES
  99. clf_num_cat = SGDClassifier(loss="log", random_state=random_state)
  100. print("Training model...")
  101. for i, chunk in enumerate(
  102. pd.read_csv(os.path.join(remote_wfs, train_df_path), chunksize=CHUNK_SIZE)
  103. ):
  104. print(f"Training on chunk {i+1}...")
  105. df_y = chunk[TARGET_LABEL]
  106. if TRAIN_TFIDF:
  107. tfidf_X = tfidf.transform(chunk["title_and_body"])
  108. clf_tfidf.partial_fit(tfidf_X, df_y, classes=np.array([0,1]))
  109. if TRAIN_NUM_CAT:
  110. num_cat_X = chunk[num_cat_cols]
  111. clf_num_cat.partial_fit(num_cat_X, df_y, classes=np.array([0,1]))
  112. print("Saving models locally...")
  113. save_data(tfidf, clf_tfidf, clf_num_cat)
  114. def save_data(tfidf=None, clf_tfidf=None, clf_num_cat=None):
  115. if TRAIN_TFIDF:
  116. joblib.dump(tfidf, os.path.join(local_path, tfidf_path))
  117. joblib.dump(clf_tfidf, os.path.join(local_path, clf_tfidf_path))
  118. if TRAIN_NUM_CAT:
  119. joblib.dump(clf_num_cat, os.path.join(local_path, clf_num_cat_path))
  120. if __name__ == "__main__":
  121. remote_wfs = get_remote_gs_wfs()
  122. load_and_train(remote_wfs)
  123. print("Loading and training done!")
Tip!

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

Comments

Loading...