Update.
[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 || true
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 (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.
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)
32     x = x[torch.randperm(x.size(0))]
33     c = torch.tensor([x.size(0) for x in u])
34
35     return x.narrow(1, 0, 1).contiguous(), x.narrow(1, 1, 1).contiguous(), c
36
37 ######################################################################
38
39 class Net(nn.Module):
40     def __init__(self):
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)
46
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))
53         x = self.fc2(x)
54         return x
55
56 ######################################################################
57
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
61
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
65
66 mu, std = train_input.mean(), train_input.std()
67 train_input.sub_(mu).div_(std)
68 test_input.sub_(mu).div_(std)
69
70 ######################################################################
71
72 # The information bound is the log of the number of classes in there
73
74 # used_classes = torch.tensor([ 0, 1, 3, 5, 6, 7, 8, 9])
75 used_classes = torch.tensor([ 3, 4, 7, 0 ])
76
77 nb_epochs, batch_size = 50, 100
78
79 model = Net()
80 optimizer = torch.optim.Adam(model.parameters(), lr = 1e-3)
81
82 if torch.cuda.is_available():
83     model.cuda()
84     train_input, train_target = train_input.cuda(), train_target.cuda()
85     test_input, test_target = test_input.cuda(), test_target.cuda()
86
87 for e in range(nb_epochs):
88
89     input_a, input_b, count = create_pair_set(used_classes, train_input, train_target)
90
91     class_proba = count.float()
92     class_proba /= class_proba.sum()
93     class_entropy = - (class_proba.log() * class_proba).sum().item()
94
95     input_br = input_b[torch.randperm(input_b.size(0))]
96
97     acc_mi = 0.0
98
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         mi = model(batch_a, batch_b).mean() - model(batch_a, batch_br).exp().mean().log()
103         loss = - mi
104         acc_mi += mi.item()
105         optimizer.zero_grad()
106         loss.backward()
107         optimizer.step()
108
109     acc_mi /= (input_a.size(0) // batch_size)
110
111     print('%d %.04f %.04f'%(e, acc_mi / math.log(2), class_entropy / math.log(2)))
112
113     sys.stdout.flush()
114
115 ######################################################################
116
117 input_a, input_b, count = create_pair_set(used_classes, test_input, test_target)
118
119 for e in range(nb_epochs):
120     class_proba = count.float()
121     class_proba /= class_proba.sum()
122     class_entropy = - (class_proba.log() * class_proba).sum().item()
123
124     input_br = input_b[torch.randperm(input_b.size(0))]
125
126     acc_mi = 0.0
127
128     for batch_a, batch_b, batch_br in zip(input_a.split(batch_size),
129                                           input_b.split(batch_size),
130                                           input_br.split(batch_size)):
131         loss = - (model(batch_a, batch_b).mean() - model(batch_a, batch_br).exp().mean().log())
132         acc_mi -= loss.item()
133
134     acc_mi /= (input_a.size(0) // batch_size)
135
136 print('test %.04f %.04f'%(acc_mi / math.log(2), class_entropy / math.log(2)))
137
138 ######################################################################