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 || true
8 import math, sys, torch, torchvision
11 from torch.nn import functional as F
13 ######################################################################
15 # Returns a pair of tensors (a, b, c), where a and b are Nx1x28x28
16 # tensors containing images, with a[i] and b[i] of same class for any
17 # i, and c is a 1d 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)
32 x = x[torch.randperm(x.size(0))]
33 c = torch.tensor([x.size(0) for x in u])
35 return x.narrow(1, 0, 1).contiguous(), x.narrow(1, 1, 1).contiguous(), c
37 ######################################################################
41 super(Net, self).__init__()
42 self.conv1 = nn.Conv2d(2, 32, kernel_size = 5)
43 self.conv2 = nn.Conv2d(32, 64, kernel_size = 5)
44 self.fc1 = nn.Linear(256, 200)
45 self.fc2 = nn.Linear(200, 1)
47 def forward(self, a, b):
48 x = torch.cat((a, b), 1)
49 x = F.relu(F.max_pool2d(self.conv1(x), kernel_size = 3))
50 x = F.relu(F.max_pool2d(self.conv2(x), kernel_size = 2))
51 x = x.view(x.size(0), -1)
52 x = F.relu(self.fc1(x))
56 ######################################################################
58 train_set = torchvision.datasets.MNIST('./data/mnist/', train = True, download = True)
59 train_input = train_set.train_data.view(-1, 1, 28, 28).float()
60 train_target = train_set.train_labels
62 test_set = torchvision.datasets.MNIST('./data/mnist/', train = False, download = True)
63 test_input = test_set.test_data.view(-1, 1, 28, 28).float()
64 test_target = test_set.test_labels
66 mu, std = train_input.mean(), train_input.std()
67 train_input.sub_(mu).div_(std)
68 test_input.sub_(mu).div_(std)
70 ######################################################################
72 # The information bound is the log of the number of classes in there
74 # used_classes = torch.tensor([ 0, 1, 3, 5, 6, 7, 8, 9])
75 used_classes = torch.tensor([ 3, 4, 7, 0 ])
77 nb_epochs, batch_size = 50, 100
80 optimizer = torch.optim.Adam(model.parameters(), lr = 1e-3)
82 if torch.cuda.is_available():
84 train_input, train_target = train_input.cuda(), train_target.cuda()
85 test_input, test_target = test_input.cuda(), test_target.cuda()
87 for e in range(nb_epochs):
89 input_a, input_b, count = create_pair_set(used_classes, train_input, train_target)
91 class_proba = count.float()
92 class_proba /= class_proba.sum()
93 class_entropy = - (class_proba.log() * class_proba).sum().item()
95 input_br = input_b[torch.randperm(input_b.size(0))]
99 for batch_a, batch_b, batch_br in zip(input_a.split(batch_size),
100 input_b.split(batch_size),
101 input_br.split(batch_size)):
102 loss = - (model(batch_a, batch_b).mean() - model(batch_a, batch_br).exp().mean().log())
104 optimizer.zero_grad()
108 mi /= (input_a.size(0) // batch_size)
110 print('%d %.04f %.04f'%(e, mi / math.log(2), class_entropy / math.log(2)))
114 ######################################################################
116 input_a, input_b, count = create_pair_set(used_classes, test_input, test_target)
118 for e in range(nb_epochs):
119 class_proba = count.float()
120 class_proba /= class_proba.sum()
121 class_entropy = - (class_proba.log() * class_proba).sum().item()
123 input_br = input_b[torch.randperm(input_b.size(0))]
127 for batch_a, batch_b, batch_br in zip(input_a.split(batch_size),
128 input_b.split(batch_size),
129 input_br.split(batch_size)):
130 loss = - (model(batch_a, batch_b).mean() - model(batch_a, batch_br).exp().mean().log())
133 mi /= (input_a.size(0) // batch_size)
135 print('test %.04f %.04f'%(mi / math.log(2), class_entropy / math.log(2)))
137 ######################################################################