-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_manager.py
57 lines (42 loc) · 1.77 KB
/
run_manager.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
from tqdm import tqdm
class RunManager(object):
def __init__(self, model_manager, optimizer, loaders, criterion, device):
self.model_manager = model_manager
self.optimizer = optimizer
self.loaders = loaders
self.criterion = criterion
self.device = device
def train(self):
loss_ = 0.0
acc = 0.0
loader = self.loaders['train']
self.model_manager.set_train_mode()
self.optimizer.zero_grad()
for idx, (feat, _, label) in enumerate(tqdm(loader)):
output, loss = self.model_manager.forward(feat, label, self.criterion)
loss.backward()
loss_ += loss.item()
acc += 1 if output.argmax().item() == label.item() else 0
if (idx + 1) % int(len(loader)/3) == 0:
self.optimizer.step()
self.optimizer.zero_grad()
tqdm.write("Train [{}]/[{}]: {:.2f} -- {:.2f}".format(idx, len(loader), loss_ / idx, acc / idx))
def val(self, test):
loss_ = 0.0
acc = 0.0
if test:
loader = self.loaders['test']
else:
loader = self.loaders['val']
self.model_manager.set_eval_mode()
for idx, (feat, _, label) in enumerate(tqdm(loader)):
output, loss = self.model_manager.forward(feat, label, self.criterion)
loss_ += loss.item()
acc += 1 if output.argmax().item() == label.item() else 0
if test:
print("=" * 50)
print("=" * 10, "Test: {:.2f} -- {:.5f}".format(loss_ / len(loader), acc / len(loader)), "=" * 10)
print("=" * 50)
else:
tqdm.write("Validation: {:.2f} -- {:.5f}".format(loss_ / len(loader), acc / len(loader)))
return acc / len(loader)