-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
125 lines (98 loc) · 3.04 KB
/
Copy pathutils.py
File metadata and controls
125 lines (98 loc) · 3.04 KB
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
import matplotlib.pyplot as plt
import numpy as np
from skimage.transform import pyramid_expand
from torch import backends, cat, cuda
from torch import device as torch_device
from torch import manual_seed
from torch.nn.utils.rnn import pad_sequence
# Constants
NORMALISE = True
MODEL_PARAMS = {
"vgg16": {
"encoder_channels": 512,
"features_dims": 9
},
"resnet50": {
"encoder_channels": 2048,
"features_dims": 10
},
"inception_v3": {
"encoder_channels": 2048,
"features_dims": 10
}
}
# Expectation and Standard Deviation over ImageNet
MAGIC_MU = [0.485, 0.456, 0.406]
MAGIC_SIGMA = [0.229, 0.224, 0.225]
# Set the seed for reproducibility
backends.cudnn.determinstic = True
if cuda.is_available():
DEVICE = torch_device('cuda:0')
cuda.manual_seed_all(42)
else:
DEVICE = torch_device('cpu')
manual_seed(42)
def collate(batch, pad_idx):
"""
Form batches of data.
:param batch: list of tuples (image, caption, image_name)
:param pad_idx: index of padding token
"""
images = [item[0].unsqueeze(0) for item in batch]
images = cat(images, dim=0)
captions = [item[1] for item in batch]
captions = pad_sequence(captions, batch_first=True, padding_value=pad_idx)
img_names = [item[2] for item in batch]
return images, captions, img_names
def show_image(img, normalise, title=None):
"""
Unormalise and show image.
:param img: image
:param normalise: whether to Un-normalise or not
:param title: title of the image
"""
img2 = np.copy(img) # copy image to prevent changing the original one
# Unnormalise
if normalise:
for i in range(3):
img2[i] *= MAGIC_SIGMA[i]
img2[i] += MAGIC_MU[i]
img2 = img2.transpose((1, 2, 0))
if title is not None:
plt.title(title)
plt.imshow(img2)
plt.show()
def plot_attention(img, caption, alphas, normalise=False):
"""
Plot the attention weights.
:param img: image
:param caption: caption
:param alphas: attention weights
:param normalise: whether to Un-normalise or not
:param features_dims: number of features dimensions
"""
# Unnormalise
if normalise:
for i in range(3):
img[i] *= MAGIC_SIGMA[i]
img[i] += MAGIC_MU[i]
img = img.numpy().transpose((1, 2, 0))
img_cpy = img
fig = plt.figure(figsize=(15, 15))
len_caption = len(caption)
features_dims = np.sqrt(alphas[0].shape[1]).astype(int)
for i in range(len_caption):
att = alphas[i].reshape(features_dims, features_dims)
att = pyramid_expand(att, upscale=24, sigma=8)
ax = fig.add_subplot(len_caption // 2, len_caption // 2, i + 1)
ax.set_title(caption[i])
img = ax.imshow(img_cpy)
ax.imshow(att, cmap='gray', alpha=0.7, extent=img.get_extent())
plt.tight_layout()
plt.show()
def plot_history(history):
plt.figure(figsize=(10, 7))
plt.plot(history)
plt.xlabel("iterations")
plt.ylabel("loss")
plt.show()