-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
333 lines (281 loc) · 11.6 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
from collections import OrderedDict
from torch import nn
from utils.data import classes
import torch
import torch.nn.functional as F
import numpy as np
display = False
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(0)
torch.manual_seed(0)
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class UnFlatten(nn.Module):
def forward(self, input, size=1024):
return input.view(input.size(0), size, 1, 1)
class VAE(nn.Module):
"""
Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014
Adopted Pytorch implementation: https://github.com/sksq96/pytorch-vae
"""
def __init__(self, image_channels=3, h_dim=1024, z_dim=32):
# super(VAE, self).__init__()
# Refer to this post: https://discuss.pytorch.org/t/what-do-i-need-to-inherit-to-make-a-custom-nn-module/5896/2
super(type(self), self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(image_channels, 32, kernel_size=4, stride=2),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=4, stride=2),
nn.ReLU(),
nn.Conv2d(64, 128, kernel_size=4, stride=2),
nn.ReLU(),
nn.Conv2d(128, 256, kernel_size=4, stride=2),
nn.ReLU(),
Flatten()
)
self.fc1 = nn.Linear(h_dim, z_dim)
self.fc2 = nn.Linear(h_dim, z_dim)
self.fc3 = nn.Linear(z_dim, h_dim)
self.register_buffer('scene_dist', torch.zeros((len(classes), 2, z_dim)))
self.register_buffer('eps', torch.randn(z_dim))
# Sequential NN to handle Classification Task
self.classifier = nn.Sequential(OrderedDict([
('cls_fc1', nn.Linear(z_dim, len(classes)))
# ('relu', nn.ReLU()),
# ('cls_fc2', nn.Linear(31, 30)),
# ('activation', nn.LogSoftmax(dim=1)) # CrossEntropy applies logSoftmax expects fc
]))
self.decoder = nn.Sequential(
UnFlatten(),
nn.ConvTranspose2d(h_dim, 128, kernel_size=5, stride=2),
nn.ReLU(),
nn.ConvTranspose2d(128, 64, kernel_size=5, stride=2),
nn.ReLU(),
nn.ConvTranspose2d(64, 32, kernel_size=6, stride=2),
nn.ReLU(),
nn.ConvTranspose2d(32, image_channels, kernel_size=6, stride=2),
nn.Sigmoid(),
)
# Reparameterize based on Scene distribution
# TODO Does not generate scene image for comparison
def reparameterize(self, mu, logvar, labels):
stds = logvar.mul(0.5).exp_()
for label, mean, std in zip(labels, mu, stds):
# Add the current image with the corresponding scene distribution
# if label in scene_dist:
# Concatenate Mean and Std to Scene Distribution
label = label.item()
self.scene_dist[label][0] += mean
self.scene_dist[label][1] += std
# Image distribution information
if display:
print("Scene dist_shape", self.scene_dist[label].shape)
print(self.scene_dist[label])
print(f'{classes[label]} \t| {mean.type()} \t| {std.type()}')
# Caluclate latent space for each scene
z = mu + stds * self.eps
return z
def bottleneck(self, h, label):
mu, logvar = self.fc1(h), self.fc2(h)
z = self.reparameterize(mu, logvar, label)
return z, mu, logvar
def encode(self, x, label):
h = self.encoder(x)
z, mu, logvar = self.bottleneck(h, label)
return z, mu, logvar
def decode(self, z):
z = self.fc3(z)
z = self.decoder(z)
return z
def forward(self, x, label):
z, mu, logvar = self.encode(x, label)
class_pred = self.classifier(z)
z = self.decode(z)
return z, mu, logvar, class_pred
class VAE_BN(nn.Module):
"""
Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014 + Batch Normalization.
Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. 2015
"""
def __init__(self, image_channels=3, h_dim=1024, z_dim=32):
# super(VAE, self).__init__()
# Refer to this post: https://discuss.pytorch.org/t/what-do-i-need-to-inherit-to-make-a-custom-nn-module/5896/2
super(type(self), self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(image_channels, 32, kernel_size=4, stride=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=4, stride=2),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Conv2d(64, 128, kernel_size=4, stride=2),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Conv2d(128, 256, kernel_size=4, stride=2),
nn.BatchNorm2d(256),
nn.ReLU(),
Flatten()
)
self.fc1 = nn.Linear(h_dim, z_dim)
self.fc2 = nn.Linear(h_dim, z_dim)
self.fc3 = nn.Linear(z_dim, h_dim)
self.register_buffer('scene_dist', torch.zeros((len(classes), 2, z_dim)))
self.register_buffer('eps', torch.randn(z_dim))
# Sequential NN to handle Classification Task
self.classifier = nn.Sequential(OrderedDict([
('cls_fc1', nn.Linear(z_dim, len(classes)))
# ('relu', nn.ReLU()),
# ('cls_fc2', nn.Linear(31, 30)),
# ('activation', nn.LogSoftmax(dim=1)) # CrossEntropy applies logSoftmax expects fc
]))
self.decoder = nn.Sequential(
UnFlatten(),
nn.ConvTranspose2d(h_dim, 128, kernel_size=5, stride=2),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.ConvTranspose2d(128, 64, kernel_size=5, stride=2),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.ConvTranspose2d(64, 32, kernel_size=6, stride=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.ConvTranspose2d(32, image_channels, kernel_size=6, stride=2),
nn.BatchNorm2d(3),
nn.Sigmoid(),
)
# Reparameterize based on Scene distribution
# TODO Does not generate scene image for comparison
def reparameterize(self, mu, logvar, labels):
stds = logvar.mul(0.5).exp_()
for label, mean, std in zip(labels, mu, stds):
# Add the current image with the corresponding scene distribution
# if label in scene_dist:
# Concatenate Mean and Std to Scene Distribution
label = label.item()
self.scene_dist[label][0] += mean
self.scene_dist[label][1] += std
# Image distribution information
if display:
print("Scene dist_shape", self.scene_dist[label].shape)
print(self.scene_dist[label])
print(f'{classes[label]} \t| {mean.type()} \t| {std.type()}')
# Caluclate latent space for each scene
z = mu + stds * self.eps
return z
def bottleneck(self, h, label):
mu, logvar = self.fc1(h), self.fc2(h)
z = self.reparameterize(mu, logvar, label)
return z, mu, logvar
def encode(self, x, label):
h = self.encoder(x)
z, mu, logvar = self.bottleneck(h, label)
return z, mu, logvar
def decode(self, z):
z = self.fc3(z)
z = self.decoder(z)
return z
def forward(self, x, label):
z, mu, logvar = self.encode(x, label)
class_pred = self.classifier(z)
z = self.decode(z)
return z, mu, logvar, class_pred
class VAE_GN(nn.Module):
"""
Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014 + Batch Normalization.
Wu and He. Group normalization. 2018
"""
def __init__(self, image_channels=3, h_dim=1024, z_dim=32):
# super(VAE, self).__init__()
# Refer to this post: https://discuss.pytorch.org/t/what-do-i-need-to-inherit-to-make-a-custom-nn-module/5896/2
super(type(self), self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(image_channels, 32, kernel_size=4, stride=2),
nn.GroupNorm(4, 32),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=4, stride=2),
nn.GroupNorm(32, 64),
nn.ReLU(),
nn.Conv2d(64, 128, kernel_size=4, stride=2),
nn.GroupNorm(64, 128),
nn.ReLU(),
nn.Conv2d(128, 256, kernel_size=4, stride=2),
nn.GroupNorm(128, 256),
nn.ReLU(),
Flatten()
)
self.fc1 = nn.Linear(h_dim, z_dim)
self.fc2 = nn.Linear(h_dim, z_dim)
self.fc3 = nn.Linear(z_dim, h_dim)
self.register_buffer('scene_dist', torch.zeros((len(classes), 2, z_dim)))
self.register_buffer('eps', torch.randn(z_dim))
# Sequential NN to handle Classification Task
self.classifier = nn.Sequential(OrderedDict([
('cls_fc1', nn.Linear(z_dim, len(classes)))
# ('relu', nn.ReLU()),
# ('cls_fc2', nn.Linear(31, 30)),
# ('activation', nn.LogSoftmax(dim=1)) # CrossEntropy applies logSoftmax expects fc
]))
self.decoder = nn.Sequential(
UnFlatten(),
nn.ConvTranspose2d(h_dim, 128, kernel_size=5, stride=2),
nn.GroupNorm(64, 128),
nn.ReLU(),
nn.ConvTranspose2d(128, 64, kernel_size=5, stride=2),
nn.GroupNorm(32, 64),
nn.ReLU(),
nn.ConvTranspose2d(64, 32, kernel_size=6, stride=2),
nn.GroupNorm(4, 32),
nn.ReLU(),
nn.ConvTranspose2d(32, image_channels, kernel_size=6, stride=2),
nn.GroupNorm(1, 3),
nn.Sigmoid(),
)
# Reparameterize based on Scene distribution
# TODO Does not generate scene image for comparison
def reparameterize(self, mu, logvar, labels):
stds = logvar.mul(0.5).exp_()
for label, mean, std in zip(labels, mu, stds):
# Add the current image with the corresponding scene distribution
# if label in scene_dist:
# Concatenate Mean and Std to Scene Distribution
label = label.item()
self.scene_dist[label][0] += mean
self.scene_dist[label][1] += std
# Image distribution information
if display:
print("Scene dist_shape", self.scene_dist[label].shape)
print(self.scene_dist[label])
print(f'{classes[label]} \t| {mean.type()} \t| {std.type()}')
# Caluclate latent space for each scene
z = mu + stds * self.eps
return z
def bottleneck(self, h, label):
mu, logvar = self.fc1(h), self.fc2(h)
z = self.reparameterize(mu, logvar, label)
return z, mu, logvar
def encode(self, x, label):
h = self.encoder(x)
z, mu, logvar = self.bottleneck(h, label)
return z, mu, logvar
def decode(self, z):
z = self.fc3(z)
z = self.decoder(z)
return z
def forward(self, x, label):
z, mu, logvar = self.encode(x, label)
class_pred = self.classifier(z)
z = self.decode(z)
return z, mu, logvar, class_pred
# Reconstruction + KL divergence losses summed over all elements and batch
def SE_loss(recon_x, x, mu, logvar):
BCE = F.binary_cross_entropy_with_logits(recon_x, x, reduction='mean')
# see Appendix B from VAE paper:
# Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014
# 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
KLD = -0.5 * torch.mean(1 + logvar - mu.pow(2) - logvar.exp())
return BCE + KLD, BCE, KLD
def compare(x):
recon_x, _, _ = VAE(x)
return torch.cat([x, recon_x])