-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdcganModel.py
91 lines (76 loc) · 2.79 KB
/
dcganModel.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
# Discriminator & generator implementation from https://arxiv.org/abs/1511.06434
import torch
import torch.nn as nn
class Discriminator(nn.Module):
def __init__(self, channels_img, features_d):
super(Discriminator, self).__init__()
self.disc = nn.Sequential(
nn.Conv2d(
channels_img, features_d, kernel_size=4, stride=2, padding=1
),
nn.LeakyReLU(0.2),
self._block(features_d, features_d*2, 4, 2, 1), # 16x16
self._block(features_d*2, features_d*4, 4, 2, 1), # 8x8
self._block(features_d*4, features_d*8, 4, 2, 1), # 4x4
nn.Conv2d(features_d*8, 1, kernel_size=4,
stride=2, padding=0), # 1x1
nn.Sigmoid(),
)
def _block(self, in_channels, out_channels, kernel_size, stride, padding):
return nn.Sequential(
nn.Conv2d(
in_channels,
out_channels,
kernel_size,
stride,
padding,
bias=False,
),
nn.BatchNorm2d(out_channels),
nn.LeakyReLU(0.2),
)
def forward(self, x):
return self.disc(x)
class Generator(nn.Module):
def __init__(self, z_dim, channels_img, features_g):
super(Generator, self).__init__()
self.gen = nn.Sequential(
self._block(z_dim, features_g*16, 4, 1, 0), # N x f_g*16 x 4 x 4
self._block(features_g*16, features_g*8, 4, 2, 1), # 8x8
self._block(features_g*8, features_g*4, 4, 2, 1), # 16x16
self._block(features_g*4, features_g*2, 4, 2, 1), # 32x32
nn.ConvTranspose2d(
features_g*2, channels_img, kernel_size=4, stride=2, padding=1,
),
nn.Tanh(), # [-1, 1]
)
def _block(self, in_channels, out_channels, kernel_size, stride, padding):
return nn.Sequential(
nn.ConvTranspose2d(
in_channels,
out_channels,
kernel_size,
stride,
padding,
bias=False,
),
nn.BatchNorm2d(out_channels),
nn.ReLU(),
)
def forward(self, x):
return self.gen(x)
def initialize_weights(model):
for m in model.modules():
if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d, nn.BatchNorm2d)):
nn.init.normal_(m.weight.data, 0.0, 0.02)
def test():
N, in_channels, H, W = 8, 3, 64, 64
z_dim = 100
x = torch.randn((N, in_channels, H, W))
disc = Discriminator(in_channels, 8)
initialize_weights(disc)
assert disc(x).shape == (N, 1, 1, 1)
gen = Generator(z_dim, in_channels, 8)
z = torch.randn((N, z_dim, 1, 1))
assert gen(z).shape == (N, in_channels, H, W)
test()