Initial commit.
authorFrancois Fleuret <francois@fleuret.org>
Wed, 14 Nov 2018 08:37:14 +0000 (09:37 +0100)
committerFrancois Fleuret <francois@fleuret.org>
Wed, 14 Nov 2018 08:37:14 +0000 (09:37 +0100)
mine_mnist.py [new file with mode: 0755]

diff --git a/mine_mnist.py b/mine_mnist.py
new file mode 100755 (executable)
index 0000000..f573b89
--- /dev/null
@@ -0,0 +1,105 @@
+#!/usr/bin/env python
+
+# @XREMOTE_HOST: elk.fleuret.org
+# @XREMOTE_EXEC: ~/conda/bin/python
+# @XREMOTE_PRE: ln -s ~/data/pytorch ./data
+# @XREMOTE_PRE: killall -q -9 python || echo "Nothing killed"
+
+import math, sys, torch, torchvision
+
+from torch import nn
+from torch.nn import functional as F
+
+######################################################################
+
+# Returns a pair of tensors (x, c), where x is a Nx2x28x28 containing
+# pairs of images of same classes (one per channel), and p is a 1d
+# long tensor with the count of pairs per class used
+
+def create_pair_set(used_classes, input, target):
+    u = []
+
+    for i in used_classes:
+        used_indices = torch.arange(input.size(0), device = target.device)\
+                            .masked_select(target == i.item())
+        x = input[used_indices]
+        x = x[torch.randperm(x.size(0))]
+        # Careful with odd numbers of samples in a class
+        x = x[0:2 * (x.size(0) // 2)].reshape(-1, 2, 28, 28)
+        u.append(x)
+
+    x = torch.cat(u, 0).contiguous()
+    c = torch.tensor([x.size(0) for x in u])
+
+    return x, c
+
+######################################################################
+
+class Net(nn.Module):
+    def __init__(self):
+        super(Net, self).__init__()
+        self.conv1 = nn.Conv2d(2, 32, kernel_size = 5)
+        self.conv2 = nn.Conv2d(32, 64, kernel_size = 5)
+        self.fc1 = nn.Linear(256, 200)
+        self.fc2 = nn.Linear(200, 1)
+
+    def forward(self, x):
+        x = F.relu(F.max_pool2d(self.conv1(x), kernel_size = 3))
+        x = F.relu(F.max_pool2d(self.conv2(x), kernel_size = 2))
+        x = x.view(x.size(0), -1)
+        x = F.relu(self.fc1(x))
+        x = self.fc2(x)
+        return x
+
+######################################################################
+
+train_set = torchvision.datasets.MNIST('./data/mnist/', train = True, download = True)
+train_input  = train_set.train_data.view(-1, 1, 28, 28).float()
+train_target = train_set.train_labels
+
+mu, std = train_input.mean(), train_input.std()
+train_input.sub_(mu).div_(std)
+
+######################################################################
+
+# The information bound is the log of the number of classes in there
+
+# used_classes = torch.tensor([ 0, 1, 3, 5, 6, 7, 8, 9])
+used_classes = torch.tensor([ 3, 4, 7, 0 ])
+
+nb_epochs, batch_size = 50, 100
+
+model = Net()
+optimizer = torch.optim.Adam(model.parameters(), lr = 1e-3)
+
+if torch.cuda.is_available():
+    model.cuda()
+    train_input, train_target = train_input.cuda(), train_target.cuda()
+
+for e in range(nb_epochs):
+    input, count = create_pair_set(used_classes, train_input, train_target)
+
+    class_proba = count.float()
+    class_proba /= class_proba.sum()
+    class_entropy = - (class_proba.log() * class_proba).sum().item()
+
+    input = input[torch.randperm(input.size(0))]
+    indep_input = input.clone()
+    indep_input[:, 1] = input[torch.randperm(input.size(0)), 1]
+
+    mi = 0.0
+
+    for batch, indep_batch in zip(input.split(batch_size), indep_input.split(batch_size)):
+        loss = - (model(batch).mean() - model(indep_batch).exp().mean().log())
+        mi -= loss.item()
+        optimizer.zero_grad()
+        loss.backward()
+        optimizer.step()
+
+    mi /= (input.size(0) // batch_size)
+
+    print('%d %.04f %.04f'%(e, mi / math.log(2), class_entropy / math.log(2)))
+
+    sys.stdout.flush()
+
+######################################################################