3 # @XREMOTE_HOST: elk.fleuret.org
4 # @XREMOTE_EXEC: ~/conda/bin/python
5 # @XREMOTE_PRE: ln -s ~/data/pytorch ./data
6 # @XREMOTE_PRE: killall -q -9 python || echo "Nothing killed"
8 import math, sys, torch, torchvision
11 from torch.nn import functional as F
13 ######################################################################
15 # Returns a pair of tensors (x, c), where x is a Nx2x28x28 containing
16 # pairs of images of same classes (one per channel), and p is a 1d
17 # long tensor with the count of pairs per class used
19 def create_pair_set(used_classes, input, target):
22 for i in used_classes:
23 used_indices = torch.arange(input.size(0), device = target.device)\
24 .masked_select(target == i.item())
25 x = input[used_indices]
26 x = x[torch.randperm(x.size(0))]
27 # Careful with odd numbers of samples in a class
28 x = x[0:2 * (x.size(0) // 2)].reshape(-1, 2, 28, 28)
31 x = torch.cat(u, 0).contiguous()
32 c = torch.tensor([x.size(0) for x in u])
36 ######################################################################
40 super(Net, self).__init__()
41 self.conv1 = nn.Conv2d(2, 32, kernel_size = 5)
42 self.conv2 = nn.Conv2d(32, 64, kernel_size = 5)
43 self.fc1 = nn.Linear(256, 200)
44 self.fc2 = nn.Linear(200, 1)
47 x = F.relu(F.max_pool2d(self.conv1(x), kernel_size = 3))
48 x = F.relu(F.max_pool2d(self.conv2(x), kernel_size = 2))
49 x = x.view(x.size(0), -1)
50 x = F.relu(self.fc1(x))
54 ######################################################################
56 train_set = torchvision.datasets.MNIST('./data/mnist/', train = True, download = True)
57 train_input = train_set.train_data.view(-1, 1, 28, 28).float()
58 train_target = train_set.train_labels
60 mu, std = train_input.mean(), train_input.std()
61 train_input.sub_(mu).div_(std)
63 ######################################################################
65 # The information bound is the log of the number of classes in there
67 # used_classes = torch.tensor([ 0, 1, 3, 5, 6, 7, 8, 9])
68 used_classes = torch.tensor([ 3, 4, 7, 0 ])
70 nb_epochs, batch_size = 50, 100
73 optimizer = torch.optim.Adam(model.parameters(), lr = 1e-3)
75 if torch.cuda.is_available():
77 train_input, train_target = train_input.cuda(), train_target.cuda()
79 for e in range(nb_epochs):
80 input, count = create_pair_set(used_classes, train_input, train_target)
82 class_proba = count.float()
83 class_proba /= class_proba.sum()
84 class_entropy = - (class_proba.log() * class_proba).sum().item()
86 input = input[torch.randperm(input.size(0))]
87 indep_input = input.clone()
88 indep_input[:, 1] = input[torch.randperm(input.size(0)), 1]
92 for batch, indep_batch in zip(input.split(batch_size), indep_input.split(batch_size)):
93 loss = - (model(batch).mean() - model(indep_batch).exp().mean().log())
99 mi /= (input.size(0) // batch_size)
101 print('%d %.04f %.04f'%(e, mi / math.log(2), class_entropy / math.log(2)))
105 ######################################################################