本文整理汇总了Python中misc.utils.decode_sequence方法的典型用法代码示例。如果您正苦于以下问题:Python utils.decode_sequence方法的具体用法?Python utils.decode_sequence怎么用?Python utils.decode_sequence使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类misc.utils
的用法示例。
在下文中一共展示了utils.decode_sequence方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test
# 需要导入模块: from misc import utils [as 别名]
# 或者: from misc.utils import decode_sequence [as 别名]
def test(model, crit, dataset, vocab, opt):
model.eval()
loader = DataLoader(dataset, batch_size=opt["batch_size"], shuffle=True)
scorer = COCOScorer()
gt_dataframe = json_normalize(
json.load(open(opt["input_json"]))['sentences'])
gts = convert_data_to_coco_scorer_format(gt_dataframe)
results = []
samples = {}
for data in loader:
# forward the model to get loss
fc_feats = data['fc_feats'].cuda()
labels = data['labels'].cuda()
masks = data['masks'].cuda()
video_ids = data['video_ids']
# forward the model to also get generated samples for each image
with torch.no_grad():
seq_probs, seq_preds = model(
fc_feats, mode='inference', opt=opt)
sents = utils.decode_sequence(vocab, seq_preds)
for k, sent in enumerate(sents):
video_id = video_ids[k]
samples[video_id] = [{'image_id': video_id, 'caption': sent}]
with suppress_stdout_stderr():
valid_score = scorer.score(gts, samples, samples.keys())
results.append(valid_score)
print(valid_score)
if not os.path.exists(opt["results_path"]):
os.makedirs(opt["results_path"])
with open(os.path.join(opt["results_path"], "scores.txt"), 'a') as scores_table:
scores_table.write(json.dumps(results[0]) + "\n")
with open(os.path.join(opt["results_path"],
opt["model"].split("/")[-1].split('.')[0] + ".json"), 'w') as prediction_results:
json.dump({"predictions": samples, "scores": valid_score},
prediction_results)
示例2: test
# 需要导入模块: from misc import utils [as 别名]
# 或者: from misc.utils import decode_sequence [as 别名]
def test(model, crit, dataset, vocab, opt):
model.eval()
loader = DataLoader(dataset, batch_size=opt["batch_size"], shuffle=False)
scorer = COCOScorer()
gt_dataframe = json_normalize(
json.load(open(opt["input_json"]))['sentences'])
gts = convert_data_to_coco_scorer_format(gt_dataframe)
#results = []
samples = {}
for index, data in enumerate(loader):
print 'batch: '+str((index+1)*opt["batch_size"])
# forward the model to get loss
fc_feats = Variable(data['fc_feats'], volatile=True).cuda()
labels = Variable(data['labels'], volatile=True).long().cuda()
masks = Variable(data['masks'], volatile=True).cuda()
video_ids = data['video_ids']
# forward the model to also get generated samples for each image
seq_probs, seq_preds = model(
fc_feats, mode='inference', opt=opt)
# print(seq_preds)
sents = utils.decode_sequence(vocab, seq_preds)
for k, sent in enumerate(sents):
video_id = video_ids[k]
samples[video_id] = [{'image_id': video_id, 'caption': sent}]
# break
with suppress_stdout_stderr():
valid_score = scorer.score(gts, samples, samples.keys())
#results.append(valid_score)
#print(valid_score)
if not os.path.exists(opt["results_path"]):
os.makedirs(opt["results_path"])
result = OrderedDict()
result['checkpoint'] = opt["saved_model"][opt["saved_model"].rfind('/')+1:]
score_sum = 0
for key, value in valid_score.items():
score_sum += float(value)
result['sum'] = str(score_sum)
#result = OrderedDict(result, **valid_score)
result = OrderedDict(result.items() + valid_score.items())
print result
if not os.path.exists(opt["results_path"]):
os.makedirs(opt["results_path"])
with open(os.path.join(opt["results_path"], "scores.txt"), 'a') as scores_table:
scores_table.write(json.dumps(result) + "\n")
with open(os.path.join(opt["results_path"],
opt["model"].split("/")[-1].split('.')[0] + ".json"), 'w') as prediction_results:
json.dump({"predictions": samples, "scores": valid_score},
prediction_results)