Update.
[pytorch.git] / mine_mnist.py
1 #!/usr/bin/env python
2
3 import math, sys, torch, torchvision
4
5 from torch import nn
6 from torch.nn import functional as F
7
8 ######################################################################
9
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
13
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
17
18 mu, std = train_input.mean(), train_input.std()
19 train_input.sub_(mu).div_(std)
20 test_input.sub_(mu).div_(std)
21
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 ])
25
26 ######################################################################
27
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.
31
32 def create_MNIST_pair_set(train = False):
33     ua, ub = [], []
34
35     if train:
36         input, target = train_input, train_target
37     else:
38         input, target = test_input, test_target
39
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))]
45         hs = x.size(0)//2
46         ua.append(x.narrow(0, 0, hs))
47         ub.append(x.narrow(0, hs, hs))
48
49     a = torch.cat(ua, 0)
50     b = torch.cat(ub, 0)
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])
55
56     return a, b, c
57
58 ######################################################################
59
60 class Net(nn.Module):
61     def __init__(self):
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)
67
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))
75         x = self.fc2(x)
76         return x
77
78 ######################################################################
79
80 nb_epochs, batch_size = 50, 100
81
82 model = Net()
83
84 print('nb_parameters %d' % sum(x.numel() for x in model.parameters()))
85
86 optimizer = torch.optim.Adam(model.parameters(), lr = 1e-3)
87
88 if torch.cuda.is_available():
89     model.cuda()
90     train_input, train_target = train_input.cuda(), train_target.cuda()
91     test_input, test_target = test_input.cuda(), test_target.cuda()
92
93 for e in range(nb_epochs):
94
95     input_a, input_b, count = create_MNIST_pair_set(train = True)
96
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()
101
102     input_br = input_b[torch.randperm(input_b.size(0))]
103
104     acc_mi = 0.0
105
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()
110         loss = - mi
111         acc_mi += mi.item()
112         optimizer.zero_grad()
113         loss.backward()
114         optimizer.step()
115
116     acc_mi /= (input_a.size(0) // batch_size)
117
118     print('%d %.04f %.04f' % (e, acc_mi / math.log(2), class_entropy / math.log(2)))
119
120     sys.stdout.flush()
121
122 ######################################################################
123
124 input_a, input_b, count = create_MNIST_pair_set(train = False)
125
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()
130
131     input_br = input_b[torch.randperm(input_b.size(0))]
132
133     acc_mi = 0.0
134
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()
139         acc_mi += mi.item()
140
141     acc_mi /= (input_a.size(0) // batch_size)
142
143 print('test %.04f %.04f'%(acc_mi / math.log(2), class_entropy / math.log(2)))
144
145 ######################################################################