######################################################################
-# Returns a pair of tensors (a, b, c), where a and b are Nx1x28x28
-# tensors containing images, with a[i] and b[i] of same class for any
-# i, and c is a 1d long tensor with the count of pairs per class used.
+# Returns a pair of tensors (a, b, c), where a and b are tensors
+# containing each half of the samples, with a[i] and b[i] of same
+# class for any i, and c is a 1d long tensor with the count of pairs
+# per class used.
def create_pair_set(used_classes, input, target):
- u = []
+ ua, ub = [], []
for i in used_classes:
used_indices = torch.arange(input.size(0), device = target.device)\
.masked_select(target == i.item())
x = input[used_indices]
x = x[torch.randperm(x.size(0))]
- # Careful with odd numbers of samples in a class
- x = x[0:2 * (x.size(0) // 2)].reshape(-1, 2, 28, 28)
- u.append(x)
+ ua.append(x.narrow(0, 0, x.size(0)//2))
+ ub.append(x.narrow(0, x.size(0)//2, x.size(0)//2))
- x = torch.cat(u, 0)
- x = x[torch.randperm(x.size(0))]
- c = torch.tensor([x.size(0) for x in u])
+ a = torch.cat(ua, 0)
+ b = torch.cat(ub, 0)
+ perm = torch.randperm(a.size(0))
+ a = a[perm].contiguous()
+ b = b[perm].contiguous()
+ c = torch.tensor([x.size(0) for x in ua])
- return x.narrow(1, 0, 1).contiguous(), x.narrow(1, 1, 1).contiguous(), c
+ return a, b, c
######################################################################
input_br = input_b[torch.randperm(input_b.size(0))]
- mi = 0.0
+ acc_mi = 0.0
for batch_a, batch_b, batch_br in zip(input_a.split(batch_size),
input_b.split(batch_size),
input_br.split(batch_size)):
- loss = - (model(batch_a, batch_b).mean() - model(batch_a, batch_br).exp().mean().log())
- mi -= loss.item()
+ mi = model(batch_a, batch_b).mean() - model(batch_a, batch_br).exp().mean().log()
+ loss = - mi
+ acc_mi += mi.item()
optimizer.zero_grad()
loss.backward()
optimizer.step()
- mi /= (input_a.size(0) // batch_size)
+ acc_mi /= (input_a.size(0) // batch_size)
- print('%d %.04f %.04f'%(e, mi / math.log(2), class_entropy / math.log(2)))
+ print('%d %.04f %.04f'%(e, acc_mi / math.log(2), class_entropy / math.log(2)))
sys.stdout.flush()
input_br = input_b[torch.randperm(input_b.size(0))]
- mi = 0.0
+ acc_mi = 0.0
for batch_a, batch_b, batch_br in zip(input_a.split(batch_size),
input_b.split(batch_size),
input_br.split(batch_size)):
loss = - (model(batch_a, batch_b).mean() - model(batch_a, batch_br).exp().mean().log())
- mi -= loss.item()
+ acc_mi -= loss.item()
- mi /= (input_a.size(0) // batch_size)
+ acc_mi /= (input_a.size(0) // batch_size)
-print('test %.04f %.04f'%(mi / math.log(2), class_entropy / math.log(2)))
+print('test %.04f %.04f'%(acc_mi / math.log(2), class_entropy / math.log(2)))
######################################################################