-
Notifications
You must be signed in to change notification settings - Fork 18
/
wgan_gp_gene.py
224 lines (194 loc) · 9.52 KB
/
wgan_gp_gene.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# Copyright (C) 2018 Anvita Gupta
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License, version 3,
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import torch
from torch import optim
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
from torch.autograd import Variable
from sklearn.preprocessing import OneHotEncoder
import os, math, glob, argparse
from utils.torch_utils import *
from utils.utils import *
import matplotlib.pyplot as plt
import utils.language_helpers
plt.switch_backend('agg')
import numpy as np
from models import *
class WGAN_LangGP():
def __init__(self, batch_size=64, lr=0.0001, num_epochs=80, seq_len = 156, data_dir='./data/random_dna_seqs.fa', \
run_name='test', hidden=512, d_steps = 10):
self.hidden = hidden
self.batch_size = batch_size
self.lr = lr
self.n_epochs = num_epochs
self.seq_len = seq_len
self.d_steps = d_steps
self.g_steps = 1
self.lamda = 10 #lambda
self.checkpoint_dir = './checkpoint/' + run_name + "/"
self.sample_dir = './samples/' + run_name + "/"
self.load_data(data_dir)
if not os.path.exists(self.checkpoint_dir): os.makedirs(self.checkpoint_dir)
if not os.path.exists(self.sample_dir): os.makedirs(self.sample_dir)
self.use_cuda = True if torch.cuda.is_available() else False
self.build_model()
def build_model(self):
self.G = Generator_lang(len(self.charmap), self.seq_len, self.batch_size, self.hidden)
self.D = Discriminator_lang(len(self.charmap), self.seq_len, self.batch_size, self.hidden)
if self.use_cuda:
self.G.cuda()
self.D.cuda()
print(self.G)
print(self.D)
self.G_optimizer = optim.Adam(self.G.parameters(), lr=self.lr, betas=(0.5, 0.9))
self.D_optimizer = optim.Adam(self.D.parameters(), lr=self.lr, betas=(0.5, 0.9))
def load_data(self, datadir):
max_examples = 1e6
lines, self.charmap, self.inv_charmap = utils.language_helpers.load_dataset(
max_length=self.seq_len,
max_n_examples=max_examples,
data_dir=datadir
)
self.data = lines
def save_model(self, epoch):
torch.save(self.G.state_dict(), self.checkpoint_dir + "G_weights_{}.pth".format(epoch))
torch.save(self.D.state_dict(), self.checkpoint_dir + "D_weights_{}.pth".format(epoch))
def load_model(self, directory = ''):
'''
Load model parameters from most recent epoch
'''
if len(directory) == 0:
directory = self.checkpoint_dir
list_G = glob.glob(directory + "G*.pth")
list_D = glob.glob(directory + "D*.pth")
if len(list_G) == 0:
print("[*] Checkpoint not found! Starting from scratch.")
return 1 #file is not there
G_file = max(list_G, key=os.path.getctime)
D_file = max(list_D, key=os.path.getctime)
epoch_found = int( (G_file.split('_')[-1]).split('.')[0])
print("[*] Checkpoint {} found at {}!".format(epoch_found, directory))
self.G.load_state_dict(torch.load(G_file))
self.D.load_state_dict(torch.load(D_file))
return epoch_found
def calc_gradient_penalty(self, real_data, fake_data):
alpha = torch.rand(self.batch_size, 1, 1)
alpha = alpha.view(-1,1,1)
alpha = alpha.expand_as(real_data)
alpha = alpha.cuda() if self.use_cuda else alpha
interpolates = alpha * real_data + ((1 - alpha) * fake_data)
interpolates = interpolates.cuda() if self.use_cuda else interpolates
interpolates = autograd.Variable(interpolates, requires_grad=True)
disc_interpolates = self.D(interpolates)
gradients = autograd.grad(outputs=disc_interpolates, inputs=interpolates,
grad_outputs=torch.ones(disc_interpolates.size()).cuda() \
if self.use_cuda else torch.ones(disc_interpolates.size()),
create_graph=True, retain_graph=True)[0]
gradients = gradients.contiguous().view(self.batch_size, -1)
gradients_norm = torch.sqrt(torch.sum(gradients ** 2, dim=1) + 1e-12)
#gradient_penalty = ((gradients.norm(2, dim=1).norm(2,dim=1) - 1) ** 2).mean() * self.lamda
return self.lamda * ((gradients_norm - 1) ** 2).mean()
def disc_train_iteration(self, real_data):
self.D_optimizer.zero_grad()
fake_data = self.sample_generator(self.batch_size)
d_fake_pred = self.D(fake_data)
d_fake_err = d_fake_pred.mean()
d_real_pred = self.D(real_data)
d_real_err = d_real_pred.mean()
gradient_penalty = self.calc_gradient_penalty(real_data, fake_data)
d_err = d_fake_err - d_real_err + gradient_penalty
d_err.backward()
self.D_optimizer.step()
return d_fake_err.data, d_real_err.data, gradient_penalty.data
def sample_generator(self, num_sample):
z_input = Variable(torch.randn(num_sample, 128))
if self.use_cuda: z_input = z_input.cuda()
generated_data = self.G(z_input)
return generated_data
def gen_train_iteration(self):
self.G.zero_grad()
z_input = to_var(torch.randn(self.batch_size, 128))
g_fake_data = self.G(z_input)
dg_fake_pred = self.D(g_fake_data)
g_err = -torch.mean(dg_fake_pred)
g_err.backward()
self.G_optimizer.step()
return g_err
def train_model(self, load_dir):
init_epoch = self.load_model(load_dir)
total_iterations = 4000
losses_f = open(self.checkpoint_dir + "losses.txt",'a+')
d_fake_losses, d_real_losses, grad_penalties = [],[],[]
G_losses, D_losses, W_dist = [],[],[]
table = np.arange(len(self.charmap)).reshape(-1, 1)
one_hot = OneHotEncoder()
one_hot.fit(table)
counter = 0
for epoch in range(self.n_epochs):
n_batches = int(len(self.data)/self.batch_size)
for idx in range(n_batches):
_data = np.array(
[[self.charmap[c] for c in l] for l in self.data[idx*self.batch_size:(idx+1)*self.batch_size]],
dtype='int32'
)
data_one_hot = one_hot.transform(_data.reshape(-1, 1)).toarray().reshape(self.batch_size, -1, len(self.charmap))
real_data = torch.Tensor(data_one_hot)
real_data = to_var(real_data)
d_fake_err, d_real_err, gradient_penalty = self.disc_train_iteration(real_data)
# Append things for logging
d_fake_np, d_real_np, gp_np = d_fake_err.cpu().numpy(), \
d_real_err.cpu().numpy(), gradient_penalty.cpu().numpy()
grad_penalties.append(gp_np)
d_real_losses.append(d_real_np)
d_fake_losses.append(d_fake_np)
D_losses.append(d_fake_np - d_real_np + gp_np)
W_dist.append(d_real_np - d_fake_np)
if counter % self.d_steps == 0:
g_err = self.gen_train_iteration()
G_losses.append((g_err.data).cpu().numpy())
if counter % 100 == 99:
self.save_model(i)
self.sample(i)
if counter % 10 == 9:
summary_str = 'Iteration [{}/{}] - loss_d: {}, loss_g: {}, w_dist: {}, grad_penalty: {}'\
.format(i, total_iterations, (d_err.data).cpu().numpy(),
(g_err.data).cpu().numpy(), ((d_real_err - d_fake_err).data).cpu().numpy(), gp_np)
print(summary_str)
losses_f.write(summary_str)
plot_losses([G_losses, D_losses], ["gen", "disc"], self.sample_dir + "losses.png")
plot_losses([W_dist], ["w_dist"], self.sample_dir + "dist.png")
plot_losses([grad_penalties],["grad_penalties"], self.sample_dir + "grad.png")
plot_losses([d_fake_losses, d_real_losses],["d_fake", "d_real"], self.sample_dir + "d_loss_components.png")
counter += 1
np.random.shuffle(self.data)
def sample(self, epoch):
z = to_var(torch.randn(self.batch_size, 128))
self.G.eval()
torch_seqs = self.G(z)
seqs = (torch_seqs.data).cpu().numpy()
decoded_seqs = [decode_one_seq(seq, self.inv_charmap)+"\n" for seq in seqs]
with open(self.sample_dir + "sampled_{}.txt".format(epoch), 'w+') as f:
f.writelines(decoded_seqs)
self.G.train()
def main():
parser = argparse.ArgumentParser(description='WGAN-GP for producing gene sequences.')
parser.add_argument("--run_name", default= "realProt_50aa", help="Name for output files (checkpoint and sample dir)")
parser.add_argument("--load_dir", default="", help="Option to load checkpoint from other model (Defaults to run name)")
args = parser.parse_args()
model = WGAN_LangGP(run_name=args.run_name)
model.train_model(args.load_dir)
if __name__ == '__main__':
main()