forked from HasnainRaz/Fast-AgingGAN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
95 lines (72 loc) · 3.02 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
import torch.nn as nn
import torch.nn.functional as F
class ResidualBlock(nn.Module):
def __init__(self, in_features):
super(ResidualBlock, self).__init__()
conv_block = [nn.ReflectionPad2d(1),
nn.Conv2d(in_features, in_features, 3),
nn.BatchNorm2d(in_features),
nn.ReLU(),
nn.ReflectionPad2d(1),
nn.Conv2d(in_features, in_features, 3),
nn.BatchNorm2d(in_features)]
self.conv_block = nn.Sequential(*conv_block)
def forward(self, x):
return x + self.conv_block(x)
class Generator(nn.Module):
def __init__(self, ngf, n_residual_blocks=9):
super(Generator, self).__init__()
# Initial convolution block
model = [nn.ReflectionPad2d(3),
nn.Conv2d(3, ngf, 7),
nn.BatchNorm2d(ngf),
nn.ReLU()]
# Downsampling
in_features = ngf
out_features = in_features * 2
for _ in range(2):
model += [nn.Conv2d(in_features, out_features, 3, stride=2, padding=1),
nn.BatchNorm2d(out_features),
nn.ReLU()]
in_features = out_features
out_features = in_features * 2
# Residual blocks
for _ in range(n_residual_blocks):
model += [ResidualBlock(in_features)]
# Upsampling
out_features = in_features // 2
for _ in range(2):
model += [nn.ConvTranspose2d(in_features, out_features, 3, stride=2, padding=1, output_padding=1),
nn.BatchNorm2d(out_features),
nn.ReLU()]
in_features = out_features
out_features = in_features // 2
# Output layer
model += [nn.ReflectionPad2d(3),
nn.Conv2d(ngf, 3, 7),
nn.Tanh()]
self.model = nn.Sequential(*model)
def forward(self, x):
return self.model(x)
class Discriminator(nn.Module):
def __init__(self, ndf):
super(Discriminator, self).__init__()
# A bunch of convolutions one after another
model = [nn.Conv2d(3, ndf, 4, stride=2, padding=1),
nn.LeakyReLU(0.2, inplace=True)]
model += [nn.Conv2d(ndf, ndf * 2, 4, stride=2, padding=1),
nn.BatchNorm2d(ndf * 2),
nn.LeakyReLU(0.2, inplace=True)]
model += [nn.Conv2d(ndf * 2, ndf * 4, 4, stride=2, padding=1),
nn.InstanceNorm2d(ndf * 4),
nn.LeakyReLU(0.2, inplace=True)]
model += [nn.Conv2d(ndf * 4, ndf * 8, 4, padding=1),
nn.InstanceNorm2d(ndf * 8),
nn.LeakyReLU(0.2, inplace=True)]
# FCN classification layer
model += [nn.Conv2d(ndf * 8, 1, 4, padding=1)]
self.model = nn.Sequential(*model)
def forward(self, x):
x = self.model(x)
# Average pooling and flatten
return F.avg_pool2d(x, x.size()[2:]).view(x.size()[0], -1)