-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathutils.py
38 lines (30 loc) · 1 KB
/
utils.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
import torch
class AverageMeter(object):
"""Taken from https://github.com/pytorch/examples/blob/master/imagenet/main.py"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(preds, targets, k):
batch_size = targets.size(0)
_, pred = preds.topk(k, 1, True, True)
correct = pred.eq(targets.view(-1, 1).expand_as(pred))
correct_total = correct.view(-1).float().sum()
return correct_total.item() * (100.0 / batch_size)
def calculate_caption_lengths(word_dict, captions):
lengths = 0
for caption_tokens in captions:
for token in caption_tokens:
if token in (word_dict['<start>'], word_dict['<eos>'], word_dict['<pad>']):
continue
else:
lengths += 1
return lengths