-
Notifications
You must be signed in to change notification settings - Fork 11
/
train.py
182 lines (146 loc) · 6.6 KB
/
train.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import torch
import torch.optim
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import numpy as np
import os
import argparse
from network import *
from utils import *
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str,
dest='config', help='to set the parameters')
parser.add_argument('--gpu', default=[0], nargs='+', type=int,
dest='gpu', help='the gpu used')
parser.add_argument('--pretrained', default=None,type=str,
dest='pretrained', help='the path of pretrained model')
parser.add_argument('--root', default=None, type=str,
dest='root', help='the root of images')
parser.add_argument('--train_dir', type=str,
dest='train_dir', help='the path of train file')
parser.add_argument('--save_dir', default=None, type=str,
dest='save_dir', help='the path of save generate images')
return parser.parse_args()
def construct_model(args):
G = generator(z_size=config.z_size, out_size=config.channel_size, ngf=config.ngf).cuda()
print 'G network structure'
print G
D = discriminator(in_size=config.channel_size, ndf=config.ndf).cuda()
print 'D network structure'
print D
return G, D
def train_net(G, D, args, config):
cudnn.benchmark = True
traindir = args.train_dir
if not os.path.exists(args.save_dir):
os.makedirs(args.save_dir)
if config.dataset == 'mnist':
train_loader = torch.utils.data.DataLoader(
datasets.MNIST(traindir, True,
transforms.Compose([transforms.Scale(config.image_size),
transforms.ToTensor(),
transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)),
]), download=True),
batch_size=config.batch_size, shuffle=True,
num_workers=config.workers, pin_memory=True)
elif config.dataset == 'celebA':
train_loader = torch.utils.data.DataLoader(
MydataFolder(traindir,
transform=transforms.Compose([transforms.Scale(config.image_size),
transforms.ToTensor(),
transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)),
])),
batch_size=config.batch_size, shuffle=True,
num_workers=config.workers, pin_memory=True)
else:
return
# setup loss function
criterion = nn.BCELoss().cuda()
# setup optimizer
optimizerD = torch.optim.Adam(D.parameters(), lr=config.base_lr, betas=(config.beta1, 0.999))
optimizerG = torch.optim.Adam(G.parameters(), lr=config.base_lr, betas=(config.beta1, 0.999))
# setup some varibles
batch_time = AverageMeter()
data_time = AverageMeter()
D_losses = AverageMeter()
G_losses = AverageMeter()
fixed_noise = torch.FloatTensor(8 * 8, config.z_size, 1, 1).normal_(0, 1)
fixed_noise = Variable(fixed_noise.cuda(), volatile=True)
end = time.time()
D.train()
G.train()
D_loss_list = []
G_loss_list = []
for epoch in range(config.epoches):
for i, (input, _) in enumerate(train_loader):
'''
Update D network: maximize log(D(x)) + log(1 - D(G(z)))
'''
data_time.update(time.time() - end)
batch_size = input.size(0)
input_var = Variable(input.cuda())
# Train discriminator with real data
label_real = torch.ones(batch_size)
label_real_var = Variable(label_real.cuda())
D_real_result = D(input_var).squeeze()
D_real_loss = criterion(D_real_result, label_real_var)
# Train discriminator with fake data
label_fake = torch.zeros(batch_size)
label_fake_var = Variable(label_fake.cuda())
noise = torch.randn((batch_size, config.z_size)).view(-1, config.z_size, 1, 1)
noise_var = Variable(noise.cuda())
G_result = G(noise_var)
D_fake_result = D(G_result).squeeze()
D_fake_loss = criterion(D_fake_result, label_fake_var)
# Back propagation
D_train_loss = D_real_loss + D_fake_loss
D_losses.update(D_train_loss.data[0])
D.zero_grad()
D_train_loss.backward()
optimizerD.step()
'''
Update G network: maximize log(D(G(z)))
'''
noise = torch.randn((batch_size, config.z_size)).view(-1, config.z_size, 1, 1)
noise_var = Variable(noise.cuda())
G_result = G(noise_var)
D_fake_result = D(G_result).squeeze()
G_train_loss = criterion(D_fake_result, label_real_var)
G_losses.update(G_train_loss.data[0])
# Back propagation
D.zero_grad()
G.zero_grad()
G_train_loss.backward()
optimizerG.step()
batch_time.update(time.time() - end)
end = time.time()
if (i + 1) % config.display == 0:
print_log(epoch + 1, config.epoches, i + 1, len(train_loader), config.base_lr,
config.display, batch_time, data_time, D_losses, G_losses)
batch_time.reset()
data_time.reset()
elif (i + 1) == len(train_loader):
print_log(epoch + 1, config.epoches, i + 1, len(train_loader), config.base_lr,
(i + 1) % config.display, batch_time, data_time, D_losses, G_losses)
batch_time.reset()
data_time.reset()
D_loss_list.append(D_losses.avg)
G_loss_list.append(G_losses.avg)
D_losses.reset()
G_losses.reset()
# plt the generate images and loss curve
plot_result(G, fixed_noise, config.image_size, epoch + 1, args.save_dir, is_gray=(config.channel_size == 1))
plot_loss(D_loss_list, G_loss_list, epoch + 1, config.epoches, args.save_dir)
# save the D and G.
save_checkpoint({'epoch': epoch, 'state_dict': D.state_dict(),}, os.path.join(args.save_dir, 'D_epoch_{}'.format(epoch)))
save_checkpoint({'epoch': epoch, 'state_dict': G.state_dict(),}, os.path.join(args.save_dir, 'G_epoch_{}'.format(epoch)))
create_gif(config.epoches, args.save_dir)
if __name__ == '__main__':
os.environ['CUDA_VISIBLE_DEVICES'] = '3'
args = parse()
config = Config(args.config)
G, D = construct_model(config)
train_net(G, D, args, config)