-
Notifications
You must be signed in to change notification settings - Fork 5
/
Eval_model.py
203 lines (195 loc) · 9.63 KB
/
Eval_model.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
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import time
import json
import logging
import numpy as np
import os.path as osp
from pycoco.bleu.bleu import Bleu
from pycoco.meteor.meteor import Meteor
from pycoco.rouge.rouge import Rouge
from pycoco.cider.cider import Cider
bad_endings = ['a','an','the','in','for','at','of','with','before','after','on','upon','near','to','is','are','am']
def count_bad(sen,max_step):
sen = sen.split(' ')
if len(sen) < max_step and sen[-1] in bad_endings:
return 1
else:
return 0
def evaluate(gt_file, re_file, logger=None):
"""
This function is reformed from MSCOCO evaluating code.
The reference sentences are read from gt_file,
the generated sentences to be evaluated are read from res_file
"""
gts = json.load(open(gt_file, 'r'))
scorers = [
(Bleu(4), ["Bleu_1", "Bleu_2", "Bleu_3", "Bleu_4"]),
(Meteor(), "METEOR"),
(Rouge(), "ROUGE_L"),
(Cider(), "CIDEr")
]
metrics = []
res = json.load(open(re_file, 'r'))
res = {c['image_id']: [c['caption']] for c in res}
gts = {k: v for k, v in zip(gts['image_ids'], gts['captions']) if k in res}
for scorer, method in scorers:
if logger is not None:
logger.info('computing %s score...' % (scorer.method()))
score, scores = scorer.compute_score(gts, res)
if type(method) == list:
for sc, scs, m in zip(score, scores, method):
if logger is not None:
logger.info("%s: %0.3f" % (m, sc))
metrics.extend(score)
else:
if logger is not None:
logger.info("%s: %0.3f" % (method, score))
metrics.append(score)
return metrics
import sys
import ngram_opts
from dataloader import *
opts = ngram_opts.parse_opt()
lr = 0.0005
opts.batch_size = 50
loader = KKDataLoader(opts)
vocabs = loader.get_vocab()
vocab = ['#END#']
for i in range(len(vocabs)):
ids = str(i+1)
vocab.append(vocabs[ids])
save_dir = 'eval'
model_type = opts.caption_model # fc or attention
rl_type = opts.rl_type # 'fourgram', 'trigram', 'rnnlm'
batch_size = opts.batch_size
image_dim = 2048
cell_size = 512
if rl_type == 'fourgram':
if model_type == 'att':
from caption_model.att import *
vocab_size = 9489
model = AttModel(batch_size=batch_size, image_dim=image_dim, vocab_size=vocab_size, cell_size=cell_size, lr=lr,
ngram=4, on_gpu=True)
model.load('fourgram_cider_model/att_model/model.best')
results = []
for kkk in range(5000 / opts.batch_size):
data = loader.get_batch('test')
tmp = [data['fc_feats'][np.arange(loader.batch_size) * loader.seq_per_img],
data['att_feats'][np.arange(loader.batch_size) * loader.seq_per_img]]
fc_feats, att_feats = tmp
image_id = [data['infos'][i]['id'] for i in range(batch_size)]
att_feats = att_feats.reshape(att_feats.shape[0], att_feats.shape[1] * att_feats.shape[2],att_feats.shape[3])
greedy_cap, greedy_res = model.inference(vocab, image_id, att_feats, manner='greedy', max_length=20)
results += greedy_res
else:
from caption_model.fc import *
vocab_size = 9489
model = FCModel(batch_size=batch_size, image_dim=image_dim, vocab_size=vocab_size, cell_size=cell_size, lr=lr,
ngram=4, on_gpu=True)
model.load('fourgram_cider_model/fc_model/model.best')
results = []
for kkk in range(5000 / opts.batch_size):
data = loader.get_batch('test')
tmp = [data['fc_feats'][np.arange(loader.batch_size) * loader.seq_per_img],
data['att_feats'][np.arange(loader.batch_size) * loader.seq_per_img]]
fc_feats, att_feats = tmp
image_id = [data['infos'][i]['id'] for i in range(batch_size)]
greedy_cap, greedy_res = model.inference(vocab, image_id, fc_feats, manner='greedy', max_length=20)
results += greedy_res
elif rl_type =='trigram':
if model_type == 'att':
from caption_model.att import *
vocab_size = 9489
model = AttModel(batch_size=batch_size, image_dim=image_dim, vocab_size=vocab_size, cell_size=cell_size, lr=lr,
ngram=3, on_gpu=True)
model.load('trigram_cider_model/att_model/model.best')
results = []
for kkk in range(5000 / opts.batch_size):
data = loader.get_batch('test')
tmp = [data['fc_feats'][np.arange(loader.batch_size) * loader.seq_per_img],
data['att_feats'][np.arange(loader.batch_size) * loader.seq_per_img]]
fc_feats, att_feats = tmp
image_id = [data['infos'][i]['id'] for i in range(batch_size)]
att_feats = att_feats.reshape(att_feats.shape[0], att_feats.shape[1] * att_feats.shape[2],att_feats.shape[3])
greedy_cap, greedy_res = model.inference(vocab, image_id, att_feats, manner='greedy', max_length=20)
results += greedy_res
else:
from caption_model.fc import *
vocab_size = 9489
model = FCModel(batch_size=batch_size, image_dim=image_dim, vocab_size=vocab_size, cell_size=cell_size, lr=lr,
ngram=3, on_gpu=True)
model.load('trigram_cider_model/fc_model/model.best')
results = []
for kkk in range(5000 / opts.batch_size):
data = loader.get_batch('test')
tmp = [data['fc_feats'][np.arange(loader.batch_size) * loader.seq_per_img],
data['att_feats'][np.arange(loader.batch_size) * loader.seq_per_img]]
fc_feats, att_feats = tmp
image_id = [data['infos'][i]['id'] for i in range(batch_size)]
greedy_cap, greedy_res = model.inference(vocab, image_id, fc_feats, manner='greedy', max_length=20)
results += greedy_res
elif rl_type =='rnnlm':
if model_type == 'att':
from caption_model.att import *
vocab_size = 9489
model = AttModel(batch_size=batch_size, image_dim=image_dim, vocab_size=vocab_size, cell_size=cell_size, lr=lr, on_gpu=True)
model.load('rnnlm_cider_model/att_model/model.best')
results = []
for kkk in range(5000 / opts.batch_size):
data = loader.get_batch('test')
tmp = [data['fc_feats'][np.arange(loader.batch_size) * loader.seq_per_img],
data['att_feats'][np.arange(loader.batch_size) * loader.seq_per_img]]
fc_feats, att_feats = tmp
image_id = [data['infos'][i]['id'] for i in range(batch_size)]
att_feats = att_feats.reshape(att_feats.shape[0], att_feats.shape[1] * att_feats.shape[2],att_feats.shape[3])
greedy_cap, greedy_res = model.inference(vocab, image_id, att_feats, manner='greedy', max_length=20)
results += greedy_res
else:
from caption_model.fc import *
vocab_size = 9489
model = FCModel(batch_size=batch_size, image_dim=image_dim, vocab_size=vocab_size, cell_size=cell_size, lr=lr,on_gpu=True)
model.load('rnnlm_cider_model/fc_model/model.best')
results = []
for kkk in range(5000 / opts.batch_size):
data = loader.get_batch('test')
tmp = [data['fc_feats'][np.arange(loader.batch_size) * loader.seq_per_img],
data['att_feats'][np.arange(loader.batch_size) * loader.seq_per_img]]
fc_feats, att_feats = tmp
image_id = [data['infos'][i]['id'] for i in range(batch_size)]
greedy_cap, greedy_res = model.inference(vocab, image_id, fc_feats, manner='greedy', max_length=20)
results += greedy_res
elif rl_type =='sc':
if model_type == 'att':
from caption_model.att import *
vocab_size = 9489
model = AttModel(batch_size=batch_size, image_dim=image_dim, vocab_size=vocab_size, cell_size=cell_size, lr=lr, on_gpu=True)
model.load('sc_cider_model/att_model/model.best')
results = []
for kkk in range(5000 / opts.batch_size):
data = loader.get_batch('test')
tmp = [data['fc_feats'][np.arange(loader.batch_size) * loader.seq_per_img],
data['att_feats'][np.arange(loader.batch_size) * loader.seq_per_img]]
fc_feats, att_feats = tmp
image_id = [data['infos'][i]['id'] for i in range(batch_size)]
att_feats = att_feats.reshape(att_feats.shape[0], att_feats.shape[1] * att_feats.shape[2],att_feats.shape[3])
greedy_cap, greedy_res = model.inference(vocab, image_id, att_feats, manner='greedy', max_length=20)
results += greedy_res
else:
from caption_model.fc import *
vocab_size = 9489
model = FCModel(batch_size=batch_size, image_dim=image_dim, vocab_size=vocab_size, cell_size=cell_size, lr=lr,on_gpu=True)
model.load('sc_cider_model/fc_model/model.best')
results = []
for kkk in range(5000 / opts.batch_size):
data = loader.get_batch('test')
tmp = [data['fc_feats'][np.arange(loader.batch_size) * loader.seq_per_img],
data['att_feats'][np.arange(loader.batch_size) * loader.seq_per_img]]
fc_feats, att_feats = tmp
image_id = [data['infos'][i]['id'] for i in range(batch_size)]
greedy_cap, greedy_res = model.inference(vocab, image_id, fc_feats, manner='greedy', max_length=20)
results += greedy_res
json.dump(results, open(osp.join(save_dir, 'result.json'), 'w'))
gt_file = osp.join('data/features', 'captions_test.json')
score = evaluate(gt_file=gt_file, re_file=osp.join(save_dir, 'result.json'))[-1]
bad_count = [count_bad(results[i]['caption']) for i in range(5000)]
total_bad_count = sum(bad_count)
print score , total_bad_count