/
test.py
81 lines (62 loc) · 2.27 KB
/
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
import time
import os
from config import cfg
import torch
from network import Net
from dataloader import DatasetLoader
def evaluate(net, dataset, criterion=cfg.MODEL.CRITERION):
model = net.model
dataloaders = dataset.dataloaders
since = time.time()
avg_loss = 0
avg_acc = 0
test_loss = 0
test_acc = 0
test_batches = len(dataloaders[cfg.CONST.TEST])
print("Evaluating model")
print('-' * 10)
with torch.no_grad():
# Set to evaluation mode
model.eval()
# Validation loop
for i, (data, target) in enumerate(dataloaders[cfg.CONST.TEST]):
# Tensors to gpu
if cfg.CONST.USE_GPU:
data, target = data.cuda(), target.cuda()
# Forward pass
output = model(data)
# Validation loss
loss = criterion(output, target)
# Multiply average loss times the number of examples in batch
test_loss += loss.item() * data.size(0)
# Calculate validation accuracy
_, pred = torch.max(output, dim=1)
correct_tensor = pred.eq(target.data.view_as(pred))
accuracy = torch.mean(
correct_tensor.type(torch.FloatTensor))
# Multiply average accuracy times the number of examples
test_acc += accuracy.item() * data.size(0)
del data, target, output, pred, _, correct_tensor
torch.cuda.empty_cache()
# Calculate average losses
test_loss = test_loss / len(dataloaders[cfg.CONST.TEST].dataset)
# Calculate average accuracy
test_acc = test_acc / len(dataloaders[cfg.CONST.TEST].dataset)
elapsed_time = time.time() - since
print()
print("Evaluation completed in {:.0f}m {:.0f}s".format(elapsed_time // 60, elapsed_time % 60))
print("Avg loss (test): {:.4f}".format(100*test_loss))
print("Avg acc (test): {:.4f}".format(100*test_acc))
print('-' * 10)
def main():
dataset = DatasetLoader()
dataset.transform_load()
# create network, modify, and set parameters
net = Net(dataset)
net.build()
net.set_params()
if os.path.exists(cfg.MODEL.FILENAME):
net.model = torch.load(cfg.MODEL.FILENAME)
evaluate(net, dataset)
if __name__ == "__main__":
main()