forked from tojiboyevf/image_captioning
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils_torch.py
More file actions
172 lines (141 loc) · 6.59 KB
/
utils_torch.py
File metadata and controls
172 lines (141 loc) · 6.59 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
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
import itertools
import os
import numpy as np
import torch
from PIL import Image
from nltk.translate.bleu_score import sentence_bleu
from tqdm.auto import tqdm
def check_create_dir(full_path):
if not os.path.isdir(full_path):
os.makedirs(full_path)
def get_picture_caption(idx, dataset, model, idx2word, beam_width=-1):
"""
GREEDY! beam_width is not used!!!
"""
im, cp, _ = dataset[idx]
capidx = model.sample(im.unsqueeze(0))[0].detach().cpu().numpy()
caption_pred = ''.join(list(itertools.takewhile(lambda word: word.strip() != '<end>',
map(lambda idx: idx2word[idx]+' ', iter(capidx))))[1:])
return caption_pred
def greedy_predictions_gen(encoding_dict, model, word2idx, idx2word, images, max_len,
startseq="<start>", endseq="<end>", device=torch.device('cpu')):
def greedy_search_predictions_util(image):
start_word = [startseq]
with torch.no_grad():
while True:
par_caps = torch.LongTensor([word2idx[i] for i in start_word])
par_caps = padding_tensor([par_caps], maxlen=max_len).to(device=device)
e = encoding_dict[image[len(images):]].unsqueeze(0)
preds = model(e, par_caps).cpu().numpy()
word_pred = idx2word[np.argmax(preds[0])] # [0] is for first elm of batch
start_word.append(word_pred)
if word_pred == endseq or len(start_word) > max_len:
break
return ' '.join(start_word[1:-1])
return greedy_search_predictions_util
def beam_search_predictions_gen(beam_index, encoding_dict, model, word2idx, idx2word, images, max_len,
startseq="<start>", endseq="<end>", device=torch.device('cpu')):
def beam_search_predictions_util(image):
start = [word2idx[startseq]]
start_word = [[start, 0.0]]
while len(start_word[0][0]) < max_len:
temp = []
for s in start_word:
with torch.no_grad():
par_caps = torch.LongTensor(s[0])
par_caps = padding_tensor([par_caps], maxlen=max_len).to(device=device)
e = encoding_dict[image[len(images):]].unsqueeze(0)
preds = model(e, par_caps).cpu().numpy()
word_preds = np.argsort(preds[0])[-beam_index:]
# Getting the top <beam_index>(n) predictions and creating a
# new list so as to put them via the model again
for w in word_preds:
next_cap, prob = s[0][:], s[1]
next_cap.append(w)
prob += preds[0][w]
temp.append([next_cap, prob])
start_word = temp
# Sorting according to the probabilities
start_word = sorted(start_word, reverse=False, key=lambda l: l[1])
# Getting the top words
start_word = start_word[-beam_index:]
start_word = start_word[-1][0]
intermediate_caption = [idx2word[i] for i in start_word]
final_caption = []
for i in intermediate_caption:
if i != endseq:
final_caption.append(i)
else:
break
final_caption = ' '.join(final_caption[1:])
return final_caption
return beam_search_predictions_util
def split_data(l, img, images):
temp = []
for i in img:
if i[len(images):] in l:
temp.append(i)
return temp
def get_bleu_score(img_to_caplist_dict, caption_gen_func, device=torch.device('cpu')):
bleu_score = 0.0
for k, v in tqdm(img_to_caplist_dict.items()):
candidate = caption_gen_func(k).split()
references = [s.split() for s in v]
bleu_score += sentence_bleu(references, candidate)
return bleu_score / len(img_to_caplist_dict)
def print_eval_metrics(img_cap_dict, encoding_dict, model, word2idx, idx2word, images, max_len,
device=torch.device('cpu')):
print('\t\tGreedy: ',
get_bleu_score(img_cap_dict, greedy_predictions_gen(encoding_dict=encoding_dict, model=model,
word2idx=word2idx, idx2word=idx2word,
images=images, max_len=max_len)))
for k in [3, 5, 7]:
print(f'\t\tBeam Search k={k}:', get_bleu_score(img_cap_dict,
beam_search_predictions_gen(beam_index=k,
encoding_dict=encoding_dict,
model=model,
word2idx=word2idx,
idx2word=idx2word,
images=images, max_len=max_len)))
def padding_tensor(sequences, maxlen):
"""
:param sequences: list of tensors
:param maxlen: fixed length of output tensors
:return:
"""
num = len(sequences)
# max_len = max([s.size(0) for s in sequences])
out_dims = (num, maxlen)
out_tensor = sequences[0].data.new(*out_dims).fill_(0)
for i, tensor in enumerate(sequences):
length = tensor.size(0)
out_tensor[i, :length] = tensor
return out_tensor
def words_from_tensors_fn(idx2word, max_len=40, startseq='<start>', endseq='<end>'):
def words_from_tensors(captions: np.array) -> list:
"""
:param captions: [b, max_len]
:return:
"""
captoks = []
for capidx in captions:
# capidx = [1, max_len]
captoks.append(list(itertools.takewhile(lambda word: word != endseq,
map(lambda idx: idx2word[idx], iter(capidx))))[1:])
return captoks
return words_from_tensors
def get_best_and_worst_quality_captions(dset, model, idx2word, metric):
maxs = 0
mins = 100
idmint = None
idmaxt = None
for idx in range(len(dset)):
generated_caption = get_picture_caption(idx, dset, model, idx2word)
score = metric([[i.split() for i in dset.get_image_captions(idx)[1]]], [generated_caption.split()], n=4)
if maxs < score:
maxs = score
idmaxt = idx
if mins > score:
mins = score
idmint = idx
return [idmaxt, idmint]