-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcluster_gan_model.py
89 lines (72 loc) · 2.47 KB
/
cluster_gan_model.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
import torch
import torch.nn as nn
import torch.nn.functional as F
class Reshape(nn.Module):
def __init__(self, shape):
super(Reshape, self).__init__()
self.shape = shape
def forward(self, x):
return x.view(x.size(0), *self.shape)
class Generator(nn.Module):
def __init__(self, z_dim, num_class):
super(Generator, self).__init__()
prod = 128 * 7 * 7
self.net = nn.Sequential(
nn.Linear(z_dim + num_class, 1024),
nn.BatchNorm1d(1024),
nn.LeakyReLU(0.2),
nn.Linear(1024, prod),
nn.BatchNorm1d(prod),
nn.LeakyReLU(0.2),
Reshape((128, 7, 7)),
nn.ConvTranspose2d(128, 64, 4, stride=2, padding=1, bias=True),
nn.BatchNorm2d(64),
nn.LeakyReLU(0.2),
nn.ConvTranspose2d(64, 1, 4, stride=2, padding=1, bias=True),
nn.Sigmoid()
)
# init weights
def forward(self, z):
x = self.net(z)
return x.view(-1, 1, 28, 28)
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
prod = 128 * 5 * 5
self.net = nn.Sequential(
nn.Conv2d(1, 64, 4, stride=2, bias=True),
nn.LeakyReLU(0.2),
nn.Conv2d(64, 128, 4, stride=2, bias=True),
nn.LeakyReLU(0.2),
Reshape((prod,)),
nn.Linear(prod, 1024),
nn.LeakyReLU(0.2),
nn.Linear(1024, 1),
nn.Sigmoid(),
)
# init weights
def forward(self, x):
return self.net(x)
class Encoder(nn.Module):
def __init__(self, z_dim, num_class):
super(Encoder, self).__init__()
prod = 128 * 5 * 5
self.z_dim = z_dim
self.net = nn.Sequential(
nn.Conv2d(1, 64, 4, stride=2, bias=True),
nn.LeakyReLU(0.2),
nn.Conv2d(64, 128, 4, stride=2, bias=True),
nn.LeakyReLU(0.2),
Reshape((prod,)),
# Fully connected layers
torch.nn.Linear(prod, 1024),
nn.LeakyReLU(0.2),
torch.nn.Linear(1024, z_dim + num_class)
)
def forward(self, x):
z = self.net(x)
z = z.view(z.shape[0], -1)
z_n = z[:, :self.z_dim]
z_class_raw = z[:, self.z_dim:]
z_class = F.softmax(z_class_raw, dim=1)
return z_n, z_class, z_class_raw