-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLS_GAN.py
96 lines (86 loc) · 2.72 KB
/
LS_GAN.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
import torch
import torch.nn as nn
#Generator: G(z, y)
class Generator(nn.Module):
def __init__(self, noise_dim: int, image_dim: int, num_classes:int)->torch.Tensor:
"""
Parameters
----------
noise_dim : int
dimension of noise vector
image_dim : int
dimension of image e.g. 784 for MNIST
num_classes : int
number of classes e.g. 10 for MNIST
Returns
-------
forward : torch.Tensor
return a tensor of image
"""
super(Generator, self).__init__()
self.embed = nn.Embedding(num_classes, num_classes)
self.seq = nn.Sequential(
nn.Linear(noise_dim+num_classes, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 512),
nn.LeakyReLU(0.2),
nn.Linear(512, 1024),
nn.LeakyReLU(0.2),
nn.Linear(1024, image_dim),
nn.Tanh()
)
def forward(self, x: torch.Tensor, y: torch.Tensor)->torch.Tensor:
"""
x: noise vector
y: label
"""
y = self.embed(y)
x = torch.cat([x, y], dim=1)
return self.seq(x)
#Discriminator: D(x, y)
class Discriminator(nn.Module):
def __init__(self, image_dim: int, num_classes:int)->torch.Tensor:
"""
Parameters
----------
image_dim : int
dimension of image e.g. 784 for MNIST
num_classes : int
number of classes e.g. 10 for MNIST
Returns
-------
forward : torch.Tensor
return a tensor of image, shape (batch_size, 1)
"""
super(Discriminator, self).__init__()
self.embed = nn.Embedding(num_classes, num_classes)
self.seq = nn.Sequential(
nn.Linear(image_dim+num_classes, 512),
nn.LeakyReLU(0.2),
nn.Linear(512, 256),
nn.LeakyReLU(0.2),
nn.Linear(256, 1),
nn.Sigmoid()
)
def forward(self, x: torch.Tensor, y: torch.Tensor)->torch.Tensor:
"""
x: image
y: label
"""
y = self.embed(y)
x = torch.cat([x, y], dim=1)
return self.seq(x)
if __name__ == "__main__":
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
noise_dim = 100
image_dim = 784
num_classes = 10
batch_size = 128
noise = torch.randn(batch_size, noise_dim).to(device)
labels = torch.randint(0, num_classes, (batch_size,)).to(device)
G = Generator(noise_dim, image_dim, num_classes).to(device)
D = Discriminator(image_dim, num_classes).to(device)
gen_out = G(noise, labels)
dis_out = D(gen_out, labels)
print(gen_out.shape)
print(dis_out.shape)