forked from GaiYu0/multiset-loss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.py
50 lines (45 loc) · 1.08 KB
/
utilities.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
from pdb import set_trace as st
import torch as th
import torch.nn.functional as F
def onehot(labels, D, cuda=True):
# labels (N, 1)
labels = labels.cpu()
N = labels.size()[0]
result = th.zeros(N, D)
result.scatter_(1, labels, 1)
if cuda:
result = result.cuda()
return result
def onehot_sequence(labels, D, cuda=True):
# labels (N, T)
N, T = labels.size()
onehot_labels = []
for l in th.chunk(labels, T, 1):
onehot_label = onehot(l, D, cuda)
onehot_label = th.unsqueeze(onehot_label, 1)
onehot_labels.append(onehot_label)
onehot_labels = th.cat(onehot_labels, 1)
return onehot_labels
def n_matches(data, labels):
"""
Parameters
----------
data: (N, T, C)
labels: (N, T, C)
"""
_, data = th.max(data, 2)
data = th.squeeze(data, 2)
_, labels = th.max(labels, 2)
labels = th.squeeze(labels, 2)
indicator = th.prod(data == labels, 1).double()
n = th.sum(indicator)
n = n.data[0]
return n
def jsd(p, q):
""" Jensen-Shannon divergence.
p (N, D)
q (N, D)
"""
m = (p + q) / 2
div = F.kl_div(m, p) + F.kl_div(m, q)
return div