f573b894634e439134e64ac46f019472bb8aab41
[pytorch.git] / mine_mnist.py
1 #!/usr/bin/env python
2
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"
7
8 import math, sys, torch, torchvision
9
10 from torch import nn
11 from torch.nn import functional as F
12
13 ######################################################################
14
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
18
19 def create_pair_set(used_classes, input, target):
20     u = []
21
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)
29         u.append(x)
30
31     x = torch.cat(u, 0).contiguous()
32     c = torch.tensor([x.size(0) for x in u])
33
34     return x, c
35
36 ######################################################################
37
38 class Net(nn.Module):
39     def __init__(self):
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)
45
46     def forward(self, x):
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))
51         x = self.fc2(x)
52         return x
53
54 ######################################################################
55
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
59
60 mu, std = train_input.mean(), train_input.std()
61 train_input.sub_(mu).div_(std)
62
63 ######################################################################
64
65 # The information bound is the log of the number of classes in there
66
67 # used_classes = torch.tensor([ 0, 1, 3, 5, 6, 7, 8, 9])
68 used_classes = torch.tensor([ 3, 4, 7, 0 ])
69
70 nb_epochs, batch_size = 50, 100
71
72 model = Net()
73 optimizer = torch.optim.Adam(model.parameters(), lr = 1e-3)
74
75 if torch.cuda.is_available():
76     model.cuda()
77     train_input, train_target = train_input.cuda(), train_target.cuda()
78
79 for e in range(nb_epochs):
80     input, count = create_pair_set(used_classes, train_input, train_target)
81
82     class_proba = count.float()
83     class_proba /= class_proba.sum()
84     class_entropy = - (class_proba.log() * class_proba).sum().item()
85
86     input = input[torch.randperm(input.size(0))]
87     indep_input = input.clone()
88     indep_input[:, 1] = input[torch.randperm(input.size(0)), 1]
89
90     mi = 0.0
91
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())
94         mi -= loss.item()
95         optimizer.zero_grad()
96         loss.backward()
97         optimizer.step()
98
99     mi /= (input.size(0) // batch_size)
100
101     print('%d %.04f %.04f'%(e, mi / math.log(2), class_entropy / math.log(2)))
102
103     sys.stdout.flush()
104
105 ######################################################################