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

train_model.py 7.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
  1. """
  2. import pandas as pd
  3. data_path = "./data/airline_sentiment_data.csv"
  4. data = pd.read_csv(data_path)
  5. print(data.head())
  6. print(data.airline_sentiment.value_counts())
  7. """
  8. import json
  9. import pandas as pd
  10. import random
  11. from tqdm import tqdm
  12. import os
  13. import yaml
  14. import mlflow
  15. import numpy as np
  16. from sklearn.model_selection import train_test_split
  17. from sklearn.metrics import f1_score
  18. from transformers import BertTokenizer
  19. from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
  20. from transformers import BertTokenizer, AutoModelForSequenceClassification, AdamW, get_linear_schedule_with_warmup
  21. import torch
  22. # Load the preprocessed data
  23. data_path = "./data/airline_sentiment_preprocessed_data.csv"
  24. # Load the airline sentiment dataset
  25. airline_data = pd.read_csv(data_path)
  26. # Create train and validation data sets
  27. # Create training and validation data
  28. X_train, X_val, y_train, y_val = train_test_split(airline_data.index.values,
  29. airline_data.label.values,
  30. test_size = 0.15,
  31. random_state = 2022,
  32. stratify = airline_data.label.values)
  33. # Create the data type columns
  34. airline_data.loc[X_train, 'data_type'] = 'train'
  35. airline_data.loc[X_val, 'data_type'] = 'val'
  36. """
  37. Get model tokenizer and encode data
  38. """
  39. # Get the FinBERT Tokenizer
  40. finbert_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
  41. # Encode the Training and Validation Data
  42. encoded_data_train = finbert_tokenizer.batch_encode_plus(
  43. airline_data[airline_data.data_type=='train'].text.values,
  44. return_tensors='pt',
  45. add_special_tokens=True,
  46. return_attention_mask=True,
  47. pad_to_max_length=True,
  48. max_length=150 # the maximum lenght observed in the headlines
  49. )
  50. encoded_data_val = finbert_tokenizer.batch_encode_plus(
  51. airline_data[airline_data.data_type=='val'].text.values,
  52. return_tensors='pt',
  53. add_special_tokens=True,
  54. return_attention_mask=True,
  55. pad_to_max_length=True,
  56. max_length=150 # the maximum lenght observed in the headlines
  57. )
  58. input_ids_train = encoded_data_train['input_ids']
  59. attention_masks_train = encoded_data_train['attention_mask']
  60. labels_train = torch.tensor(airline_data[airline_data.data_type=='train'].label.values)
  61. input_ids_val = encoded_data_val['input_ids']
  62. attention_masks_val = encoded_data_val['attention_mask']
  63. sentiments_val = torch.tensor(airline_data[airline_data.data_type=='val'].label.values)
  64. dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)
  65. dataset_val = TensorDataset(input_ids_val, attention_masks_val, sentiments_val)
  66. """
  67. Set Up the BERT pretrained model
  68. """
  69. model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased',
  70. num_labels=3,
  71. output_attentions=False,
  72. output_hidden_states=False)
  73. """
  74. Create Data Loaders
  75. """
  76. batch_size = 32
  77. dataloader_train = DataLoader(dataset_train,
  78. sampler=RandomSampler(dataset_train),
  79. batch_size=batch_size)
  80. dataloader_validation = DataLoader(dataset_val,
  81. sampler=SequentialSampler(dataset_val),
  82. batch_size=batch_size)
  83. """
  84. Create Optimizer and Scheduler
  85. """
  86. optimizer = AdamW(model.parameters(),lr=1e-5, eps=1e-8)
  87. epochs = 1
  88. scheduler = get_linear_schedule_with_warmup(optimizer,
  89. num_warmup_steps=0,
  90. num_training_steps=len(dataloader_train)*epochs)
  91. """
  92. Evaluation metrics
  93. """
  94. def f1_score_func(preds, labels):
  95. preds_flat = np.argmax(preds, axis=1).flatten()
  96. labels_flat = labels.flatten()
  97. return f1_score(labels_flat, preds_flat, average='weighted')
  98. """
  99. Training loop
  100. """
  101. seed_val = 2022
  102. random.seed(seed_val)
  103. np.random.seed(seed_val)
  104. torch.manual_seed(seed_val)
  105. torch.cuda.manual_seed_all(seed_val)
  106. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  107. model.to(device)
  108. def evaluate(dataloader_val):
  109. model.eval()
  110. loss_val_total = 0
  111. predictions, true_vals = [], []
  112. for batch in dataloader_val:
  113. batch = tuple(b.to(device) for b in batch)
  114. inputs = {'input_ids': batch[0],
  115. 'attention_mask': batch[1],
  116. 'labels': batch[2],
  117. }
  118. with torch.no_grad():
  119. outputs = model(**inputs)
  120. loss = outputs[0]
  121. logits = outputs[1]
  122. loss_val_total += loss.item()
  123. logits = logits.detach().cpu().numpy()
  124. label_ids = inputs['labels'].cpu().numpy()
  125. predictions.append(logits)
  126. true_vals.append(label_ids)
  127. loss_val_avg = loss_val_total/len(dataloader_val)
  128. predictions = np.concatenate(predictions, axis=0)
  129. true_vals = np.concatenate(true_vals, axis=0)
  130. return loss_val_avg, predictions, true_vals
  131. for epoch in tqdm(range(1, epochs+1)):
  132. model.train()
  133. loss_train_total = 0
  134. progress_bar = tqdm(dataloader_train, desc='Epoch {:1d}'.format(epoch), leave=False, disable=False)
  135. for batch in progress_bar:
  136. model.zero_grad()
  137. batch = tuple(b.to(device) for b in batch)
  138. inputs = {'input_ids': batch[0],
  139. 'attention_mask': batch[1],
  140. 'labels': batch[2],
  141. }
  142. outputs = model(**inputs)
  143. loss = outputs[0]
  144. loss_train_total += loss.item()
  145. loss.backward()
  146. torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
  147. optimizer.step()
  148. scheduler.step()
  149. progress_bar.set_postfix({'training_loss': '{:.3f}'.format(loss.item()/len(batch))})
  150. torch.save(model.state_dict(), f'finetuned_finBERT_epoch_{epoch}.model')
  151. loss_train_avg = loss_train_total/len(dataloader_train)
  152. val_loss, predictions, true_vals = evaluate(dataloader_validation)
  153. val_f1 = f1_score_func(predictions, true_vals)
  154. if __name__ == "__main__":
  155. credentials = yaml.safe_load(open("config.yaml"))["credentials"]
  156. mlflow_config = credentials["mlflow_credentials"]
  157. MLFLOW_TRACKING_URI= mlflow_config['MLFLOW_TRACKING_URI']
  158. MLFLOW_TRACKING_USERNAME = mlflow_config['MLFLOW_TRACKING_USERNAME']
  159. MLFLOW_TRACKING_PASSWORD = mlflow_config['MLFLOW_TRACKING_PASSWORD']
  160. # Metrics file
  161. meta_data = credentials["metadata_path"]
  162. metrics_file = meta_data["METRICS_FILE"]
  163. os.environ['MLFLOW_TRACKING_USERNAME'] = MLFLOW_TRACKING_USERNAME
  164. os.environ['MLFLOW_TRACKING_PASSWORD'] = MLFLOW_TRACKING_PASSWORD
  165. mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)
  166. with mlflow.start_run():
  167. # Load the metrics file
  168. with open(metrics_file) as metrics_info:
  169. metrics_values = json.load(metrics_info)
  170. # Track them with MLFlow
  171. mlflow.log_metric("Precision", metrics_values['precision'])
  172. mlflow.log_metric("Recall", metrics_values['recall'])
  173. mlflow.log_metric("F1-Score", metrics_values['f1-score'])
Tip!

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

Comments

Loading...