-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_test.py
321 lines (244 loc) · 11.5 KB
/
train_test.py
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import torch
import numpy as np
import json
import os
import datetime
class train_test_downstream():
def __init__(self, optimizer, criterion, device, config):
pass
self.optimizer = optimizer
self.criterion = criterion
self.device = device
self.config = config
def train(self, model, loader):
model.to(self.device)
model.train()
total_loss = 0.0
total_correct = 0
i = 0
for data_video, data_audio, label in loader:
i += 1
self.optimizer.zero_grad()
logits = model(data_video.to(self.device), data_audio.to(self.device))
pred = logits.argmax(dim=-1)
true = label.to(self.device)
correct = (pred == true).sum().item()
total_correct += correct
loss = self.criterion(logits, true)
loss.backward()
# for name, param in model.named_parameters():
# print(name)
# print(torch.norm(param.grad))
self.optimizer.step()
total_loss += loss.item()
# Clear GPU memory
del logits, pred, true
torch.cuda.empty_cache()
epoch_loss = total_loss / len(loader)
epoch_acc = total_correct / len(loader.dataset)
return model, epoch_loss, epoch_acc
@torch.no_grad()
def test(self, model, loader):
model.eval()
total_correct = 0
total_loss = 0.0
float_acc = 0.0
logits_all = []
for data_video, data_audio, label in loader:
logits = model(data_video.to(self.device), data_audio.to(self.device))
pred = logits.argmax(dim=-1)
true = label.to(self.device)
correct = (pred == true).sum().item()
total_correct += correct
loss = self.criterion(logits, true)
total_loss += loss.item()
# Clear GPU memory
del pred, logits, true
torch.cuda.empty_cache()
epoch_loss = total_loss / len(loader)
epoch_acc = total_correct / len(loader.dataset)
return epoch_loss, epoch_acc
def training(self, epochs, train_loader, test_loader, model):
valid_epoch_acc = 0
valid_epoch_loss = np.inf
best_train_acc = 0
best_model = None
print("number of parameters in the model:", sum(p.numel() for p in model.parameters() if p.requires_grad))
for epoch in range(1, epochs):
current_model, train_epoch_loss, train_epoch_acc = self.train(model, train_loader)
test_epoch_loss, test_epoch_acc = self.test(current_model, test_loader)
if train_epoch_acc >= best_train_acc:
best_model = current_model
best_epoch = epoch
best_train_loss = train_epoch_loss
best_train_acc = train_epoch_acc
valid_epoch_acc = test_epoch_acc
valid_epoch_loss = test_epoch_loss
progress_bar(epoch, epochs, train_epoch_loss, train_epoch_acc)
torch.save(best_model.state_dict(), self.config.OUTPUT_DIR + "/best_model.pt")
print(f"CURRENT ACCURACY: {valid_epoch_acc:.4f} - LOSS: {valid_epoch_loss:.4f}")
del model, train_loader, test_loader
torch.cuda.empty_cache()
return valid_epoch_acc, valid_epoch_loss
class train_test_downstream_regressive():
def __init__(self, optimizer, criterion, device, config):
pass
self.optimizer = optimizer
self.criterion = criterion
self.device = device
self.config = config
def train(self, model, loader):
model.to(self.device)
model.train()
total_loss = 0.0
total_correct = 0
i = 0
for data_video, data_text, label in loader:
i += 1
self.optimizer.zero_grad()
logits = model(data_video.to(self.device), data_text.to(self.device)).squeeze(-1)
pred = logits
true = label.to(self.device).to(torch.float32)
correct = (pred == true).sum().item()
total_correct += correct
loss = self.criterion(logits, true)
loss.backward()
# for name, param in model.named_parameters():
# print(name)
# print(torch.norm(param.grad))
self.optimizer.step()
total_loss += loss.item()
# Clear GPU memory
del logits, pred, true
torch.cuda.empty_cache()
epoch_loss = total_loss / len(loader)
epoch_acc = total_correct / len(loader.dataset)
return model, epoch_loss, epoch_acc
@torch.no_grad()
def test(self, model, loader):
model.eval()
total_correct = 0
total_loss = 0.0
float_acc = 0.0
logits_all = []
for data_video, data_audio, label in loader:
logits = model(data_video.to(self.device), data_audio.to(self.device)).squeeze(-1)
pred = logits.argmax(dim=-1)
true = label.to(self.device).to(torch.float32)
correct = (pred == true).sum().item()
total_correct += correct
loss = self.criterion(logits, true)
total_loss += loss.item()
# Clear GPU memory
del pred, logits, true
torch.cuda.empty_cache()
epoch_loss = total_loss / len(loader)
epoch_acc = total_correct / len(loader.dataset)
return epoch_loss, epoch_acc
def training(self, epochs, train_loader, test_loader, model):
valid_epoch_acc = 0
valid_epoch_loss = np.inf
best_train_acc = 0
best_model = None
print("number of parameters in the model:", sum(p.numel() for p in model.parameters() if p.requires_grad))
for epoch in range(1, epochs):
current_model, train_epoch_loss, train_epoch_acc = self.train(model, train_loader)
test_epoch_loss, test_epoch_acc = self.test(current_model, test_loader)
if train_epoch_acc >= best_train_acc:
best_model = current_model
best_epoch = epoch
best_train_loss = train_epoch_loss
best_train_acc = train_epoch_acc
valid_epoch_acc = test_epoch_acc
valid_epoch_loss = test_epoch_loss
progress_bar(epoch, epochs, train_epoch_loss, train_epoch_acc)
torch.save(best_model.state_dict(), self.config.OUTPUT_DIR + "/best_model.pt")
print(f"CURRENT ACCURACY: {valid_epoch_acc:.4f} - LOSS: {valid_epoch_loss:.4f}")
del model, train_loader, test_loader
torch.cuda.empty_cache()
return valid_epoch_acc, valid_epoch_loss
class train_test_contrastive():
"""
Trains and tests a machine learning model using a contrastive learning approach.
The `train_test_contrastive` class provides methods for training and testing a model on a dataset. The `train` method trains the model on a training dataset, while the `test` method evaluates the model on a test dataset. The `training` method orchestrates the training and testing process, keeping track of the best model and reporting the final accuracy and loss.
The class takes an optimizer and a device (e.g. CPU or GPU) as input, and uses them to train and test the model. The training process involves iterating over the training dataset, computing the loss, backpropagating the gradients, and updating the model parameters. The testing process involves evaluating the model on the test dataset and computing the loss and accuracy.
The `progress_bar` function is used to display the training progress during the training process.
"""
def __init__(self, optimizer, device, scheduler):
pass
self.optimizer = optimizer
self.device = device
self.scheduler = scheduler
def train(self, model, loader):
model.to(self.device)
model.train()
total_loss = 0.0
total_correct = 0
for data_video, data_audio, data_text in loader:
self.optimizer.zero_grad()
_, _, _, loss = model(data_video.to(self.device), data_audio.to(self.device), data_text.to(self.device))
loss.backward()
self.optimizer.step()
total_loss += loss.item()
# Clear GPU memory
del loss
torch.cuda.empty_cache()
self.scheduler.step(total_loss)
epoch_loss = total_loss / len(loader)
epoch_acc = total_correct / len(loader.dataset)
return model, epoch_loss, epoch_acc
@torch.no_grad()
def test(self, model, loader):
model.eval()
total_correct = 0
total_loss = 0.0
for data_video, data_audio, data_text, label in loader:
self.optimizer.zero_grad()
_, _, _, loss = model(data_video.to(self.device), data_audio.to(self.device), data_text.to(self.device))
total_loss += loss.item()
# Clear GPU memory
del loss
torch.cuda.empty_cache()
epoch_loss = total_loss / len(loader)
epoch_acc = total_correct / len(loader.dataset)
return epoch_loss, epoch_acc
def training(self, epochs, train_loader, model):
metrics = {
"Train": {
"Loss": [],
"Accuracy": [],
},
}
best_train_loss = np.inf
best_train_acc = 0
best_model = None
print("number of parameters in the model:", sum(p.numel() for p in model.parameters() if p.requires_grad))
for epoch in range(1, epochs):
current_model, train_epoch_loss, train_epoch_acc = self.train(model, train_loader)
if train_epoch_loss <= best_train_loss:
best_model = current_model
best_epoch = epoch
best_train_loss = train_epoch_loss
best_train_acc = train_epoch_acc
progress_bar(epoch, epochs, train_epoch_loss, train_epoch_acc)
# valid_epoch_loss, valid_epoch_acc, valid_epoch_float_acc, batch_logits = test(best_model, test_loader, device, criterion, target_attribute)
# print(
# f"TESTING {len(embed.keys[test_index])} SUBJECTS -> EPOCH: {best_epoch}, Loss: {valid_epoch_loss:.3f}, Accuracy: {valid_epoch_acc:.3f}, Float-acc: {valid_epoch_float_acc:.4f}"
# )
print(f"CURRENT ACCURACY: {best_train_acc:.4f} - LOSS: {best_train_loss:.4f}")
torch.save(best_model.state_dict(), "/var/data/student_home/agnelli/new_dataset/results/best_model_contrastive.pt")
metrics["Train"]["Loss"].append(best_train_loss)
metrics["Train"]["Accuracy"].append(best_train_acc)
del model, train_loader
torch.cuda.empty_cache()
if not os.path.exists(f"/var/data/student_home/agnelli/new_dataset/results"):
os.makedirs(f"/var/data/student_home/agnelli/new_dataset/results")
with open(f"/var/data/student_home/agnelli/new_dataset/results/_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.json", "w") as f:
json.dump(metrics, f, indent=4)
def progress_bar(current, total, loss, accuracy, bar_length=20):
progress = current / total
arrow_length = int(round(progress * bar_length))
arrow = "=" * arrow_length + ">"
spaces = " " * (bar_length - len(arrow))
percentage = progress * 100
print(f"[{arrow}{spaces}] {percentage:.2f}% - Epoch: {current:02d}, Loss: {loss:.4f}, Accuracy: {accuracy:.4f}", end="\r", flush=True)