-
Notifications
You must be signed in to change notification settings - Fork 4
/
testing.py
69 lines (46 loc) · 1.75 KB
/
testing.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
from utils import ConvNet
from utils import CocoCaptions
import utils
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import numpy as np
import pickle
### Hyperparameters
BATCH_SIZE = utils.BATCH_SIZE
NUM_CLASSES = utils.NUM_CLASSES
test_dir = 'resized_val2017/'
ann_file_test = 'annotations/captions_val2017.json'
test_dataset = CocoCaptions(root=test_dir, annFile=ann_file_test, transform=transforms.ToTensor())
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=BATCH_SIZE,
shuffle=True)
MODEL_NAME = 'model.ckpt'
device = None
model = None
if torch.cuda.is_available():
device = torch.device('cuda:0')
model = ConvNet(NUM_CLASSES).to(device)
model.load_state_dict(torch.load(MODEL_NAME))
else:
device = 'cpu'
model = ConvNet(NUM_CLASSES).to(device)
model.load_state_dict(torch.load(MODEL_NAME, map_location=lambda storage, loc: storage))
### Test the model
predicted = []
actual = []
id_to_prediction_dict = {}
id_to_actual_dict = {}
for i, (image_ids, images, labels) in enumerate(test_loader):
images = images.to(device)
# Forward pass
outputs = model(images)
softmax = torch.nn.Softmax()
for j, scores in enumerate(softmax(outputs).tolist()):
id_to_prediction_dict[int(image_ids[j])] = [utils.int_to_emoji_dict[x] for x in np.argsort(scores)[::-1][:5]]
for j, label in enumerate(labels.tolist()):
id_to_actual_dict[int(image_ids[j])] = [utils.int_to_emoji_dict[x] for x in label]
with open('id_to_prediction_dict.pkl', 'wb') as f:
pickle.dump(id_to_prediction_dict, f)
with open('id_to_actual_dict.pkl', 'wb') as f:
pickle.dump(id_to_actual_dict, f)