3 import sys, argparse, os, time
5 import torch, torchvision
7 from torch import optim, nn
8 from torch.nn import functional as F
12 ######################################################################
14 if torch.cuda.is_available():
15 device = torch.device('cuda')
17 device = torch.device('cpu')
19 ######################################################################
21 parser = argparse.ArgumentParser(description = 'Simple auto-encoder.')
23 parser.add_argument('--nb_epochs',
24 type = int, default = 25)
26 parser.add_argument('--batch_size',
27 type = int, default = 100)
29 parser.add_argument('--data_dir',
30 type = str, default = './data/')
32 parser.add_argument('--log_filename',
33 type = str, default = 'train.log')
35 parser.add_argument('--embedding_dim',
36 type = int, default = 16)
38 parser.add_argument('--nb_channels',
39 type = int, default = 32)
41 parser.add_argument('--force_train',
42 type = bool, default = False)
44 args = parser.parse_args()
46 log_file = open(args.log_filename, 'w')
48 ######################################################################
50 def log_string(s, color = None):
51 t = time.strftime("%Y-%m-%d_%H:%M:%S - ", time.localtime())
53 if log_file is not None:
54 log_file.write(t + s + '\n')
60 ######################################################################
62 class AutoEncoder(nn.Module):
63 def __init__(self, nb_channels, embedding_dim):
64 super(AutoEncoder, self).__init__()
66 self.encoder = nn.Sequential(
67 nn.Conv2d(1, nb_channels, kernel_size = 5), # to 24x24
68 nn.ReLU(inplace = True),
69 nn.Conv2d(nb_channels, nb_channels, kernel_size = 5), # to 20x20
70 nn.ReLU(inplace = True),
71 nn.Conv2d(nb_channels, nb_channels, kernel_size = 4, stride = 2), # to 9x9
72 nn.ReLU(inplace = True),
73 nn.Conv2d(nb_channels, nb_channels, kernel_size = 3, stride = 2), # to 4x4
74 nn.ReLU(inplace = True),
75 nn.Conv2d(nb_channels, embedding_dim, kernel_size = 4)
78 self.decoder = nn.Sequential(
79 nn.ConvTranspose2d(embedding_dim, nb_channels, kernel_size = 4),
80 nn.ReLU(inplace = True),
81 nn.ConvTranspose2d(nb_channels, nb_channels, kernel_size = 3, stride = 2), # from 4x4
82 nn.ReLU(inplace = True),
83 nn.ConvTranspose2d(nb_channels, nb_channels, kernel_size = 4, stride = 2), # from 9x9
84 nn.ReLU(inplace = True),
85 nn.ConvTranspose2d(nb_channels, nb_channels, kernel_size = 5), # from 20x20
86 nn.ReLU(inplace = True),
87 nn.ConvTranspose2d(nb_channels, 1, kernel_size = 5), # from 24x24
91 return self.encoder(x).view(x.size(0), -1)
94 return self.decoder(z.view(z.size(0), -1, 1, 1))
102 ######################################################################
104 train_set = torchvision.datasets.MNIST(args.data_dir + '/mnist/',
105 train = True, download = True)
106 train_input = train_set.data.view(-1, 1, 28, 28).float()
108 test_set = torchvision.datasets.MNIST(args.data_dir + '/mnist/',
109 train = False, download = True)
110 test_input = test_set.data.view(-1, 1, 28, 28).float()
112 ######################################################################
114 train_input, test_input = train_input.to(device), test_input.to(device)
116 mu, std = train_input.mean(), train_input.std()
117 train_input.sub_(mu).div_(std)
118 test_input.sub_(mu).div_(std)
120 model = AutoEncoder(args.nb_channels, args.embedding_dim)
121 optimizer = optim.Adam(model.parameters(), lr = 1e-3)
125 for epoch in range(args.nb_epochs):
127 for input in train_input.split(args.batch_size):
128 input = input.to(device)
129 z = model.encode(input)
130 output = model.decode(z)
131 loss = 0.5 * (output - input).pow(2).sum() / input.size(0)
133 optimizer.zero_grad()
137 acc_loss += loss.item()
139 log_string(f'acc_loss {epoch} {acc_loss}', 'blue')
141 ######################################################################
143 input = test_input[:256]
144 z = model.encode(input)
145 output = model.decode(z)
147 torchvision.utils.save_image(1 - input, 'ae-input.png', nrow = 16, pad_value = 0.8)
148 torchvision.utils.save_image(1 - output, 'ae-output.png', nrow = 16, pad_value = 0.8)
150 ######################################################################
152 input = train_input[:256]
153 z = model.encode(input)
154 mu, std = z.mean(0), z.std(0)
155 z = z.normal_() * std + mu
156 output = model.decode(z)
157 torchvision.utils.save_image(1 - output, 'ae-synth.png', nrow = 16, pad_value = 0.8)
159 ######################################################################