-
Notifications
You must be signed in to change notification settings - Fork 0
/
GAN_MNIST.py
131 lines (110 loc) · 4.84 KB
/
GAN_MNIST.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
import os
import argparse
import torch
import numpy as np
from torch import nn
from torch.nn import BCELoss
from torch.optim import Adam
from torch.utils.data import DataLoader
from torchvision.transforms import transforms
from torchvision.datasets import MNIST
from torchvision.utils import save_image
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=200, help='number of training times')
parser.add_argument('--batch_size', type=int, default=256, help='batch size')
parser.add_argument('--latent_dim', type=int, default=100, help='dimensionality of the latent space')
parser.add_argument('--alpha', type=float, default=1.0, help='to adjust the lr of G')
parser.add_argument('--beta', type=float, default=1.0, help='to adjust the lr of C')
parser.add_argument('--image_size', type=tuple, default=(28, 28), help='size of input images')
parser.add_argument('--channels', type=int, default=1, help='channels of input images')
parser.add_argument('--save_intervals', type=int, default=100, help='intervals between saving models')
options = parser.parse_args([])
image_shape = (options.channels, options.image_size[0], options.image_size[1])
class Generator(nn.Module):
def __init__(self, in_feature):
super(Generator, self).__init__()
self.model = nn.Sequential(
nn.Linear(in_feature, 1024),
nn.ReLU(),
nn.Linear(1024, 512),
nn.ReLU(),
nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, 128),
nn.Dropout(0.5),
nn.Linear(128, 28 * 28),
nn.Tanh()
)
def forward(self, _x):
x = self.model(_x)
x = x.view(x.size(0), 1, 28, 28)
return x
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.model = nn.Sequential(
nn.Linear(int(np.prod(image_shape)), 1024),
nn.ReLU(),
nn.Linear(1024, 512),
nn.ReLU(),
nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, 1),
nn.Sigmoid()
)
def forward(self, _x):
x = _x.view(_x.size(0), -1)
return self.model(x)
if __name__ == '__main__':
os.makedirs('new_images', exist_ok=True)
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
generator = Generator(options.latent_dim).double()
discriminator = Discriminator().double()
loss_fn = BCELoss()
optimizer_generator = Adam(generator.parameters())
optimizer_discriminator = Adam(discriminator.parameters())
if torch.cuda.is_available():
generator = generator.cuda()
discriminator = discriminator.cuda()
# loss_fn = loss_fn.cuda()
dataloader = DataLoader(
MNIST(
"../data",
train=True,
download=True,
transform=transforms.Compose([
transforms.Resize(options.image_size),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5], std=[0.5]),
])
),
batch_size=options.batch_size,
shuffle=True
)
for epoch in range(options.epochs):
for idx, (images, _) in enumerate(dataloader):
if idx != len(dataloader) - 1:
valid = torch.ones((256, 1), dtype=torch.float64, requires_grad=False).cuda()
fake = torch.zeros((256, 1), dtype=torch.float64, requires_grad=False).cuda()
real_images = images.type(torch.float64).cuda()
optimizer_generator.zero_grad()
z = torch.tensor(np.random.normal(0, 1, (images.shape[0], options.latent_dim))).cuda()
generate_images = generator(z)
# train generator
gen_loss = loss_fn(discriminator(generate_images), valid)
gen_loss.backward()
optimizer_generator.step()
# train discriminator
optimizer_discriminator.zero_grad()
real_loss = loss_fn(discriminator(real_images), valid)
fake_loss = loss_fn(discriminator(generate_images.detach()), fake)
dis_loss = (real_loss + fake_loss) / 2
dis_loss.backward()
optimizer_discriminator.step()
print(
"[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]"
% (epoch, options.epochs, idx + 1, len(dataloader), dis_loss.item(), gen_loss.item())
)
batches_done = epoch * len(dataloader) + epoch
if batches_done % options.save_intervals == 0:
save_image(generate_images.data[:1024], "new_images/%d.png" % batches_done, nrow=32, normalize=True)