3 import argparse, math, sys
4 from copy import deepcopy
6 import torch, torchvision
9 import torch.nn.functional as F
11 ######################################################################
13 if torch.cuda.is_available():
14 device = torch.device('cuda')
15 torch.backends.cudnn.benchmark = True
17 device = torch.device('cpu')
19 ######################################################################
21 parser = argparse.ArgumentParser(
22 description = 'An implementation of Mutual Information estimator with a deep model',
23 formatter_class = argparse.ArgumentDefaultsHelpFormatter
26 parser.add_argument('--data',
27 type = str, default = 'image_pair',
30 parser.add_argument('--seed',
31 type = int, default = 0,
32 help = 'Random seed (default 0, < 0 is no seeding)')
34 parser.add_argument('--mnist_classes',
35 type = str, default = '0, 1, 3, 5, 6, 7, 8, 9',
36 help = 'What MNIST classes to use')
38 ######################################################################
42 for k in range(target.max() + 1):
43 n = (target == k).sum().item()
44 if n > 0: probas.append(n)
45 probas = torch.tensor(probas).float()
46 probas /= probas.sum()
47 return - (probas * probas.log()).sum().item()
49 ######################################################################
51 args = parser.parse_args()
54 torch.manual_seed(args.seed)
56 used_MNIST_classes = torch.tensor(eval('[' + args.mnist_classes + ']'), device = device)
58 ######################################################################
60 train_set = torchvision.datasets.MNIST('./data/mnist/', train = True, download = True)
61 train_input = train_set.train_data.view(-1, 1, 28, 28).to(device).float()
62 train_target = train_set.train_labels.to(device)
64 test_set = torchvision.datasets.MNIST('./data/mnist/', train = False, download = True)
65 test_input = test_set.test_data.view(-1, 1, 28, 28).to(device).float()
66 test_target = test_set.test_labels.to(device)
68 mu, std = train_input.mean(), train_input.std()
69 train_input.sub_(mu).div_(std)
70 test_input.sub_(mu).div_(std)
72 ######################################################################
74 # Returns a triplet of tensors (a, b, c), where a and b contain each
75 # half of the samples, with a[i] and b[i] of same class for any i, and
76 # c is a 1d long tensor real classes
78 def create_image_pairs(train = False):
79 ua, ub, uc = [], [], []
82 input, target = train_input, train_target
84 input, target = test_input, test_target
86 for i in used_MNIST_classes:
87 used_indices = torch.arange(input.size(0), device = target.device)\
88 .masked_select(target == i.item())
89 x = input[used_indices]
90 x = x[torch.randperm(x.size(0))]
92 ua.append(x.narrow(0, 0, hs))
93 ub.append(x.narrow(0, hs, hs))
94 uc.append(target[used_indices])
99 perm = torch.randperm(a.size(0))
100 a = a[perm].contiguous()
101 b = b[perm].contiguous()
105 ######################################################################
107 # Returns a triplet a, b, c where a are the standard MNIST images, c
108 # the classes, and b is a Nx2 tensor, eith for every n:
110 # b[n, 0] ~ Uniform(0, 10)
111 # b[n, 1] ~ b[n, 0] + Uniform(0, 0.5) + c[n]
113 def create_image_values_pairs(train = False):
117 input, target = train_input, train_target
119 input, target = test_input, test_target
121 m = torch.zeros(used_MNIST_classes.max() + 1, dtype = torch.uint8, device = target.device)
122 m[used_MNIST_classes] = 1
124 used_indices = torch.arange(input.size(0), device = target.device).masked_select(m)
126 input = input[used_indices].contiguous()
127 target = target[used_indices].contiguous()
132 b = a.new(a.size(0), 2)
134 b[:, 1].uniform_(0.5)
135 b[:, 1] += b[:, 0] + target.float()
139 ######################################################################
141 def create_sequences_pairs(train = False):
142 nb, length = 10000, 1024
146 ha = torch.randint(nb_classes, (nb, ), device = device) + 1
147 # hb = torch.randint(nb_classes, (nb, ), device = device)
150 pos = torch.empty(nb, device = device).uniform_(0.0, 0.9)
151 a = torch.linspace(0, 1, length, device = device).view(1, -1).expand(nb, -1)
152 a = a - pos.view(nb, 1)
153 a = (a >= 0).float() * torch.exp(-a * math.log(2) / 0.1)
154 a = a * ha.float().view(-1, 1).expand_as(a) / (1 + nb_classes)
155 noise = a.new(a.size()).normal_(0, noise_level)
158 pos = torch.empty(nb, device = device).uniform_(0.5)
159 b1 = torch.linspace(0, 1, length, device = device).view(1, -1).expand(nb, -1)
160 b1 = b1 - pos.view(nb, 1)
161 b1 = (b1 >= 0).float() * torch.exp(-b1 * math.log(2) / 0.1)
162 pos = pos + hb.float() / (nb_classes + 1) * 0.5
163 b2 = torch.linspace(0, 1, length, device = device).view(1, -1).expand(nb, -1)
164 b2 = b2 - pos.view(nb, 1)
165 b2 = (b2 >= 0).float() * torch.exp(-b2 * math.log(2) / 0.1)
168 noise = b.new(b.size()).normal_(0, noise_level)
171 ######################################################################
172 # for k in range(10):
173 # file = open(f'/tmp/dat{k:02d}', 'w')
174 # for i in range(a.size(1)):
175 # file.write(f'{a[k, i]:f} {b[k,i]:f}\n')
178 ######################################################################
180 a = (a - a.mean()) / a.std()
181 b = (b - b.mean()) / b.std()
185 ######################################################################
187 class NetForImagePair(nn.Module):
189 super(NetForImagePair, self).__init__()
190 self.features_a = nn.Sequential(
191 nn.Conv2d(1, 16, kernel_size = 5),
192 nn.MaxPool2d(3), nn.ReLU(),
193 nn.Conv2d(16, 32, kernel_size = 5),
194 nn.MaxPool2d(2), nn.ReLU(),
197 self.features_b = nn.Sequential(
198 nn.Conv2d(1, 16, kernel_size = 5),
199 nn.MaxPool2d(3), nn.ReLU(),
200 nn.Conv2d(16, 32, kernel_size = 5),
201 nn.MaxPool2d(2), nn.ReLU(),
204 self.fully_connected = nn.Sequential(
210 def forward(self, a, b):
211 a = self.features_a(a).view(a.size(0), -1)
212 b = self.features_b(b).view(b.size(0), -1)
213 x = torch.cat((a, b), 1)
214 return self.fully_connected(x)
216 ######################################################################
218 class NetForImageValuesPair(nn.Module):
220 super(NetForImageValuesPair, self).__init__()
221 self.features_a = nn.Sequential(
222 nn.Conv2d(1, 16, kernel_size = 5),
223 nn.MaxPool2d(3), nn.ReLU(),
224 nn.Conv2d(16, 32, kernel_size = 5),
225 nn.MaxPool2d(2), nn.ReLU(),
228 self.features_b = nn.Sequential(
229 nn.Linear(2, 32), nn.ReLU(),
230 nn.Linear(32, 32), nn.ReLU(),
231 nn.Linear(32, 128), nn.ReLU(),
234 self.fully_connected = nn.Sequential(
240 def forward(self, a, b):
241 a = self.features_a(a).view(a.size(0), -1)
242 b = self.features_b(b).view(b.size(0), -1)
243 x = torch.cat((a, b), 1)
244 return self.fully_connected(x)
246 ######################################################################
248 class NetForSequencePair(nn.Module):
250 def feature_model(self):
251 return nn.Sequential(
252 nn.Conv1d(1, self.nc, kernel_size = 5),
253 nn.MaxPool1d(2), nn.ReLU(),
254 nn.Conv1d(self.nc, self.nc, kernel_size = 5),
255 nn.MaxPool1d(2), nn.ReLU(),
256 nn.Conv1d(self.nc, self.nc, kernel_size = 5),
257 nn.MaxPool1d(2), nn.ReLU(),
258 nn.Conv1d(self.nc, self.nc, kernel_size = 5),
259 nn.MaxPool1d(2), nn.ReLU(),
260 nn.Conv1d(self.nc, self.nc, kernel_size = 5),
261 nn.MaxPool1d(2), nn.ReLU(),
265 super(NetForSequencePair, self).__init__()
270 self.features_a = self.feature_model()
271 self.features_b = self.feature_model()
273 self.fully_connected = nn.Sequential(
274 nn.Linear(2 * self.nc, self.nh),
276 nn.Linear(self.nh, 1)
279 def forward(self, a, b):
280 a = a.view(a.size(0), 1, a.size(1))
281 a = self.features_a(a)
282 a = F.avg_pool1d(a, a.size(2))
284 b = b.view(b.size(0), 1, b.size(1))
285 b = self.features_b(b)
286 b = F.avg_pool1d(b, b.size(2))
288 x = torch.cat((a.view(a.size(0), -1), b.view(b.size(0), -1)), 1)
289 return self.fully_connected(x)
291 ######################################################################
293 if args.data == 'image_pair':
294 create_pairs = create_image_pairs
295 model = NetForImagePair()
296 elif args.data == 'image_values_pair':
297 create_pairs = create_image_values_pairs
298 model = NetForImageValuesPair()
299 elif args.data == 'sequence_pair':
300 create_pairs = create_sequences_pairs
301 model = NetForSequencePair()
303 raise Exception('Unknown data ' + args.data)
305 ######################################################################
307 nb_epochs, batch_size = 50, 100
309 print('nb_parameters %d' % sum(x.numel() for x in model.parameters()))
311 optimizer = torch.optim.Adam(model.parameters(), lr = 1e-3)
315 for e in range(nb_epochs):
317 input_a, input_b, classes = create_pairs(train = True)
319 input_br = input_b[torch.randperm(input_b.size(0))]
323 for batch_a, batch_b, batch_br in zip(input_a.split(batch_size),
324 input_b.split(batch_size),
325 input_br.split(batch_size)):
326 mi = model(batch_a, batch_b).mean() - model(batch_a, batch_br).exp().mean().log()
329 optimizer.zero_grad()
333 acc_mi /= (input_a.size(0) // batch_size)
335 print('%d %.04f %.04f' % (e + 1, acc_mi / math.log(2), entropy(classes) / math.log(2)))
339 ######################################################################
341 input_a, input_b, classes = create_pairs(train = False)
343 for e in range(nb_epochs):
344 input_br = input_b[torch.randperm(input_b.size(0))]
348 for batch_a, batch_b, batch_br in zip(input_a.split(batch_size),
349 input_b.split(batch_size),
350 input_br.split(batch_size)):
351 mi = model(batch_a, batch_b).mean() - model(batch_a, batch_br).exp().mean().log()
354 acc_mi /= (input_a.size(0) // batch_size)
356 print('test %.04f %.04f'%(acc_mi / math.log(2), entropy(classes) / math.log(2)))
358 ######################################################################