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

main.py 6.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
147
148
149
150
151
152
153
154
155
156
157
158
159
  1. #!/usr/bin/env python3
  2. """
  3. Modified liberally from https://dagshub.com/docs/experiment-tutorial/2-data-versioning/
  4. The goal of this repository is not to learn how to create an NLP classifier but to learn how to use DVC, therefore the ML code is unimportant.
  5. The training process has been seperated into distinct stages in order to demonstrate DVC's pipeline and experiment-tracking features.
  6. """
  7. import sys
  8. import yaml
  9. import pickle
  10. import pandas as pd
  11. import scipy.sparse as sp
  12. from sklearn.model_selection import train_test_split
  13. from sklearn.feature_extraction.text import TfidfVectorizer
  14. from sklearn.linear_model import SGDClassifier
  15. from sklearn.metrics import roc_auc_score, average_precision_score, accuracy_score, precision_score, recall_score, f1_score
  16. _params = None
  17. def read_param(name, filename="params.yaml"):
  18. global _params
  19. if _params == None:
  20. _params = yaml.safe_load(open(filename))
  21. obj = _params
  22. while "." in name:
  23. key, name = name.split(".", 1)
  24. obj = obj[key]
  25. return obj[name]
  26. def split(dataset_path=read_param("paths.dataset"),
  27. train_df_path=read_param("paths.train_df"),
  28. test_df_path=read_param("paths.test_df"),
  29. random_state=read_param("split.seed")):
  30. print(f"Loading {dataset_path}")
  31. df = pd.read_csv(dataset_path)
  32. df['MachineLearning'] = df['Tags'].str.contains('machine-learning').fillna(False)
  33. train_df, test_df = train_test_split(df, random_state=random_state, stratify=df['MachineLearning'])
  34. print(f"Saving {train_df_path}, {test_df_path}")
  35. train_df.to_csv(train_df_path)
  36. test_df.to_csv(test_df_path)
  37. def featurize(train_df_path=read_param("paths.train_df"),
  38. test_df_path=read_param("paths.test_df"),
  39. train_df_featurized_path=read_param("paths.train_df_featurized"),
  40. test_df_featurized_path=read_param("paths.test_df_featurized")):
  41. def feature_engineering(df):
  42. """Stolen directly from DAGsHub tutorial"""
  43. df['CreationDate'] = pd.to_datetime(df['CreationDate'])
  44. df['CreationDate_Epoch'] = df['CreationDate'].astype('int64') // 10 ** 9
  45. df = df.drop(columns=['Id', 'Tags'])
  46. df['Title_Len'] = df.Title.str.len()
  47. df['Body_Len'] = df.Body.str.len()
  48. # Drop the correlated features
  49. df = df.drop(columns=['FavoriteCount'])
  50. df['Text'] = df['Title'].fillna('') + ' ' + df['Body'].fillna('')
  51. return df
  52. print(f"Featurizing {train_df_path} to {train_df_featurized_path}")
  53. feature_engineering(pd.read_csv(train_df_path)).to_csv(train_df_featurized_path)
  54. print(f"Featurizing {test_df_path} to {test_df_featurized_path}")
  55. feature_engineering(pd.read_csv(test_df_path)).to_csv(test_df_featurized_path)
  56. def tfidf(train_df_featurized_path=read_param("paths.train_df_featurized"),
  57. test_df_featurized_path=read_param("paths.test_df_featurized"),
  58. train_tfidf_path=read_param("paths.train_tfidf"),
  59. test_tfidf_path=read_param("paths.test_tfidf"),
  60. tfidf_path=read_param("paths.tfidf"),
  61. max_features=read_param("tfidf.max_features")):
  62. print(f"Loading {train_df_featurized_path} and {test_df_featurized_path}")
  63. train_df = pd.read_csv(train_df_featurized_path)
  64. test_df = pd.read_csv(test_df_featurized_path)
  65. print(f"Training TF-IDF vectorizer with max_features={max_features}")
  66. tfidf = TfidfVectorizer(max_features=max_features)
  67. tfidf.fit(train_df['Text'])
  68. print(f"Transforming {train_df_featurized_path} to {train_tfidf_path}")
  69. train_tfidf = tfidf.transform(train_df['Text'])
  70. sp.save_npz(train_tfidf_path, train_tfidf)
  71. print(f"Transforming {test_df_featurized_path} to {test_tfidf_path}")
  72. test_tfidf = tfidf.transform(test_df['Text'])
  73. sp.save_npz(test_tfidf_path, test_tfidf)
  74. print(f"Writing tfidf vectorizer to {tfidf_path}")
  75. pickle.dump(tfidf, open(tfidf_path, 'wb'))
  76. def _eval_model(model, X, y):
  77. """Stolen directly from DAGsHub tutorial"""
  78. y_proba = model.predict_proba(X)[:, 1]
  79. y_pred = model.predict(X)
  80. return {
  81. 'roc_auc': float(roc_auc_score(y, y_proba)),
  82. 'average_precision': float(average_precision_score(y, y_proba)),
  83. 'accuracy': float(accuracy_score(y, y_pred)),
  84. 'precision': float(precision_score(y, y_pred)),
  85. 'recall': float(recall_score(y, y_pred)),
  86. 'f1': float(f1_score(y, y_pred)),
  87. }
  88. def train(train_df_featurized_path=read_param("paths.train_df_featurized"),
  89. train_tfidf_path=read_param("paths.train_tfidf"),
  90. loss=read_param("train.loss"),
  91. random_state=read_param("train.seed"),
  92. model_path=read_param("paths.model"),
  93. train_metrics_path=read_param("paths.train_metrics")):
  94. print(f"Loading {train_df_featurized_path} and {train_tfidf_path}")
  95. train_df = pd.read_csv(train_df_featurized_path)
  96. train_tfidf = sp.load_npz(train_tfidf_path)
  97. print(f"Training SGDClassifier model with loss={loss}, random_state={random_state}")
  98. model = SGDClassifier(loss=loss, random_state=random_state)
  99. model.fit(train_tfidf, train_df['MachineLearning'])
  100. print(f"Writing model to {model_path}")
  101. pickle.dump(model, open(model_path, 'wb'))
  102. print(f"Calculating and saving metrics to {train_metrics_path}")
  103. metrics = _eval_model(model, train_tfidf, train_df['MachineLearning'])
  104. yaml.safe_dump(metrics, open(train_metrics_path, 'w'))
  105. def test(test_df_featurized_path=read_param("paths.test_df_featurized"),
  106. test_tfidf_path=read_param("paths.test_tfidf"),
  107. model_path=read_param("paths.model"),
  108. test_metrics_path=read_param("paths.test_metrics")):
  109. print(f"Loading {test_df_featurized_path} and {test_tfidf_path}")
  110. test_df = pd.read_csv(test_df_featurized_path)
  111. test_tfidf = sp.load_npz(test_tfidf_path)
  112. print(f"Loading model from {model_path}")
  113. model = pickle.load(open(model_path, 'rb'))
  114. print(f"Calculating and saving metrics to {test_metrics_path}")
  115. metrics = _eval_model(model, test_tfidf, test_df['MachineLearning'])
  116. yaml.safe_dump(metrics, open(test_metrics_path, 'w'))
  117. if __name__ == '__main__':
  118. import sys
  119. if len(sys.argv) < 2:
  120. sys.exit(f"Usage: python3 {sys.argv[0]} [split|featurize|tfidf|train|test]")
  121. elif sys.argv[1] == "split":
  122. split()
  123. elif sys.argv[1] == "featurize":
  124. featurize()
  125. elif sys.argv[1] == "tfidf":
  126. tfidf()
  127. elif sys.argv[1] == "train":
  128. train()
  129. elif sys.argv[1] == "test":
  130. test()
  131. else:
  132. sys.exit(f"Invalid operation {sys.argv[1]}\nUsage: python3 {sys.argv[0]} [split|tfidf|train|test]")
Tip!

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

Comments

Loading...