3 import math, sys, torch, torchvision
6 from torch.nn import functional as F
8 ######################################################################
10 train_set = torchvision.datasets.MNIST('./data/mnist/', train = True, download = True)
11 train_input = train_set.train_data.view(-1, 1, 28, 28).float()
12 train_target = train_set.train_labels
14 test_set = torchvision.datasets.MNIST('./data/mnist/', train = False, download = True)
15 test_input = test_set.test_data.view(-1, 1, 28, 28).float()
16 test_target = test_set.test_labels
18 mu, std = train_input.mean(), train_input.std()
19 train_input.sub_(mu).div_(std)
20 test_input.sub_(mu).div_(std)
22 used_MNIST_classes = torch.tensor([ 0, 1, 3, 5, 6, 7, 8, 9])
23 # used_MNIST_classes = torch.tensor([ 0, 9, 7 ])
24 # used_MNIST_classes = torch.tensor([ 3, 4, 7, 0 ])
26 ######################################################################
28 # Returns a triplet of tensors (a, b, c), where a and b contain each
29 # half of the samples, with a[i] and b[i] of same class for any i, and
30 # c is a 1d long tensor with the count of pairs per class used.
32 def create_MNIST_pair_set(train = False):
36 input, target = train_input, train_target
38 input, target = test_input, test_target
40 for i in used_MNIST_classes:
41 used_indices = torch.arange(input.size(0), device = target.device)\
42 .masked_select(target == i.item())
43 x = input[used_indices]
44 x = x[torch.randperm(x.size(0))]
46 ua.append(x.narrow(0, 0, hs))
47 ub.append(x.narrow(0, hs, hs))
51 perm = torch.randperm(a.size(0))
52 a = a[perm].contiguous()
53 b = b[perm].contiguous()
54 c = torch.tensor([x.size(0) for x in ua])
58 ######################################################################
62 super(Net, self).__init__()
63 self.conv1 = nn.Conv2d(2, 32, kernel_size = 5)
64 self.conv2 = nn.Conv2d(32, 64, kernel_size = 5)
65 self.fc1 = nn.Linear(256, 200)
66 self.fc2 = nn.Linear(200, 1)
68 def forward(self, a, b):
69 # Make the two images a single two-channel image
70 x = torch.cat((a, b), 1)
71 x = F.relu(F.max_pool2d(self.conv1(x), kernel_size = 3))
72 x = F.relu(F.max_pool2d(self.conv2(x), kernel_size = 2))
73 x = x.view(x.size(0), -1)
74 x = F.relu(self.fc1(x))
78 ######################################################################
80 nb_epochs, batch_size = 50, 100
84 print('nb_parameters %d' % sum(x.numel() for x in model.parameters()))
86 optimizer = torch.optim.Adam(model.parameters(), lr = 1e-3)
88 if torch.cuda.is_available():
90 train_input, train_target = train_input.cuda(), train_target.cuda()
91 test_input, test_target = test_input.cuda(), test_target.cuda()
93 for e in range(nb_epochs):
95 input_a, input_b, count = create_MNIST_pair_set(train = True)
97 # The information bound is the entropy of the class distribution
98 class_proba = count.float()
99 class_proba /= class_proba.sum()
100 class_entropy = - (class_proba.log() * class_proba).sum().item()
102 input_br = input_b[torch.randperm(input_b.size(0))]
106 for batch_a, batch_b, batch_br in zip(input_a.split(batch_size),
107 input_b.split(batch_size),
108 input_br.split(batch_size)):
109 mi = model(batch_a, batch_b).mean() - model(batch_a, batch_br).exp().mean().log()
112 optimizer.zero_grad()
116 acc_mi /= (input_a.size(0) // batch_size)
118 print('%d %.04f %.04f' % (e, acc_mi / math.log(2), class_entropy / math.log(2)))
122 ######################################################################
124 input_a, input_b, count = create_MNIST_pair_set(train = False)
126 for e in range(nb_epochs):
127 class_proba = count.float()
128 class_proba /= class_proba.sum()
129 class_entropy = - (class_proba.log() * class_proba).sum().item()
131 input_br = input_b[torch.randperm(input_b.size(0))]
135 for batch_a, batch_b, batch_br in zip(input_a.split(batch_size),
136 input_b.split(batch_size),
137 input_br.split(batch_size)):
138 mi = model(batch_a, batch_b).mean() - model(batch_a, batch_br).exp().mean().log()
141 acc_mi /= (input_a.size(0) // batch_size)
143 print('test %.04f %.04f'%(acc_mi / math.log(2), class_entropy / math.log(2)))
145 ######################################################################