######################################################################
-# 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
######################################################################