forked from interseismic/PhaseLink
-
Notifications
You must be signed in to change notification settings - Fork 1
/
phaselink_train.py
428 lines (343 loc) · 14.7 KB
/
phaselink_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
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#! /bin/env python
import numpy as np
import os
import torch
import torch.utils.data
import sys
import json
import pickle
n_epochs = 20
class MyDataset(torch.utils.data.Dataset):
def __init__(self, data, target, transform=None):
self.data = torch.from_numpy(data).float()
self.target = torch.from_numpy(target).long()
self.transform = transform
def __getitem__(self, index):
x = self.data[index]
y = self.target[index]
if self.transform:
x = self.transform(x)
return x, y
def __len__(self):
return len(self.data)
class StackedGRU(torch.nn.Module):
def __init__(self):
super(StackedGRU, self).__init__()
self.hidden_size = 128
self.fc1 = torch.nn.Linear(5, 32)
self.fc2 = torch.nn.Linear(32, 32)
self.fc3 = torch.nn.Linear(32, 32)
self.fc4 = torch.nn.Linear(2*128, 1)
self.gru1 = torch.nn.GRU(32, self.hidden_size, \
batch_first=True, bidirectional=True)
self.gru2 = torch.nn.GRU(self.hidden_size*2, self.hidden_size, \
batch_first=True, bidirectional=True)
self.sigmoid = torch.nn.Sigmoid()
#self.dropout = torch.nn.Dropout(p=0.25)
def forward(self, inp):
out = self.fc1(inp)
out = torch.nn.functional.relu(out)
out = self.fc2(out)
out = torch.nn.functional.relu(out)
out = self.fc3(out)
out = torch.nn.functional.relu(out)
out = self.gru1(out)
h_t = out[0]
out = self.gru2(h_t)
h_t = out[0]
out = self.fc4(h_t)
out = self.sigmoid(out)
return out
class Encoder(torch.nn.Module):
def __init__(self, input_size, hidden_size):
super(Encoder, self).__init__()
self.hidden_size = hidden_size
self.gru = torch.nn.GRU(input_size, self.hidden_size)
def forward(self, input):
output, hidden = self.gru(input)
return output, hidden
class AttnDecoder(torch.nn.Module):
def __init__(self, input_size, hidden_size, output_size,
max_length):
super(AttnDecoder, self).__init__()
self.hidden_size = hidden_size
self.output_size = output_size
self.max_length = max_length
# Layers
self.attn = torch.nn.Linear(self.hidden_size + 1, self.max_length)
self.attn_combine = torch.nn.Linear(self.hidden_size + 1,
self.hidden_size)
self.gru = torch.nn.GRU(self.hidden_size, self.hidden_size)
self.out = torch.nn.Linear(self.hidden_size, self.output_size)
def forward(self, input, hidden, encoder_outputs):
import torch.nn.functional as F
cat_inp = torch.cat((input, hidden), 2)
attn_weights = F.softmax(self.attn(cat_inp), dim=2)
attn_applied = torch.bmm(attn_weights.permute(1,0,2),
encoder_outputs.permute(1,0,2))
output = torch.cat((input.permute(1,0,2), attn_applied), 2)
output = self.attn_combine(output)
output = F.relu(output).permute(1,0,2)
output, hidden = self.gru(output, hidden)
output = self.out(output)
output = torch.sigmoid(output)
return output, hidden
class AttnModel():
def __init__(self, encoder, decoder, enc_optimizer, dec_optimizer,
model_path):
self.encoder = encoder
self.decoder = decoder
self.enc_optimizer = enc_optimizer
self.dec_optimizer = dec_optimizer
self.model_path = model_path
def train(self, train_loader, val_loader, n_epochs):
from torch.autograd import Variable
import time
loss = torch.nn.BCELoss()
n_batches = len(train_loader)
training_start_time = time.time()
SOS_token = 0
for epoch in range(n_epochs):
running_loss = 0.0
running_acc = 0
running_val_acc = 0
print_every = n_batches // 10
start_time = time.time()
total_train_loss = 0
total_val_loss = 0
total_val_acc = 0
running_sample_count = 0
loss_value = 0
for i, data in enumerate(train_loader, 0):
# Get inputs/outputs and wrap in variable object
inputs, labels = data
inputs = inputs.to(device).permute(1, 0, 2)
labels = labels.to(device)
# Set gradients for all parameters to zero
self.enc_optimizer.zero_grad()
self.dec_optimizer.zero_grad()
# Forward pass
encoder_outputs, encoder_hidden = self.encoder(inputs)
decoder_hidden = encoder_hidden
decoder_input = torch.zeros((1, inputs.shape[1], 1),
device=device)
outputs = torch.zeros(labels.shape, device=device)
for j in range(labels.shape[0]):
decoder_output, decoder_hidden = self.decoder(
decoder_input, decoder_hidden, encoder_outputs)
loss_value += loss(decoder_output, labels[:,j].float())
decoder_input = labels[:,j][None,:,None].float().detach()
decoder_output = decoder_output.detach()
outputs[:,j] = decoder_output.squeeze().detach()
# Backward pass
outputs = outputs.view(-1)
labels = labels.view(-1)
loss_value.backward(retain_graph=True)
# Update parameters
self.enc_optimizer.step()
self.dec_optimizer.step()
# Print statistics
running_loss += loss_value.data.item()
total_train_loss += loss_value.data.item()
# Calculate categorical accuracy
pred = torch.round(outputs).long()
running_acc += (pred == labels).sum().item()
running_sample_count += len(labels)
# Print every 10th batch of an epoch
if (i + 1) % (print_every + 1) == 0:
print("Epoch {}, {:d}% \t train_loss: {:.4e} "
"train_acc: {:4.2f}% took: {:.2f}s".format(
epoch + 1, int(100 * (i + 1) / n_batches),
running_loss / print_every,
100*running_acc / running_sample_count,
time.time() - start_time))
# Reset running loss and time
running_loss = 0.0
start_time = time.time()
running_sample_count = 0
y_pred_all, y_true_all = [], []
for inputs, labels in val_loader:
# Wrap tensors in Variables
inputs = inputs.cuda(device)
labels = labels.cuda(device)
# Forward pass only
val_outputs = self.network(inputs)
val_outputs = val_outputs.view(-1)
labels = labels.view(-1)
val_loss = loss(val_outputs, labels.float())
total_val_loss += val_loss.data.item()
# Calculate categorical accuracy
pred = torch.round(val_outputs).long()
running_val_acc += (pred == labels).sum().item()
running_sample_count += len(labels)
y_pred_all.append(pred.cpu().numpy().flatten())
y_true_all.append(labels.cpu().numpy().flatten())
y_pred_all = np.concatenate(y_pred_all)
y_true_all = np.concatenate(y_true_all)
from sklearn.metrics import classification_report
print(classification_report(y_true_all, y_pred_all))
total_val_loss /= len(val_loader)
total_val_acc = running_val_acc / running_sample_count
print(
"Validation loss = {:.4e} acc = {:4.2f}%".format(
total_val_loss,
100*total_val_acc))
torch.save({
'epoch': epoch,
'model_state_dict': self.network.state_dict(),
'optimizer_state_dict': self.optimizer.state_dict(),
'loss': total_val_loss,
}, '%s/model_%03d_%f.pt' % (self.model_path, epoch, total_val_loss))
print(
"Training finished, took {:.2f}s".format(
time.time() -
training_start_time))
class Model():
def __init__(self, network, optimizer, model_path):
self.network = network
self.optimizer = optimizer
self.model_path = model_path
def train(self, train_loader, val_loader, n_epochs):
from torch.autograd import Variable
import time
loss = torch.nn.BCELoss()
n_batches = len(train_loader)
training_start_time = time.time()
for epoch in range(n_epochs):
running_loss = 0.0
running_acc = 0
running_val_acc = 0
print_every = n_batches // 10
start_time = time.time()
total_train_loss = 0
total_val_loss = 0
total_val_acc = 0
running_sample_count = 0
for i, data in enumerate(train_loader, 0):
# Get inputs/outputs and wrap in variable object
inputs, labels = data
inputs = inputs.to(device)
labels = labels.to(device)
# Set gradients for all parameters to zero
self.optimizer.zero_grad()
# Forward pass
outputs = self.network(inputs)
# Backward pass
outputs = outputs.view(-1)
labels = labels.view(-1)
loss_value = loss(outputs, labels.float())
loss_value.backward()
# Update parameters
self.optimizer.step()
# Print statistics
running_loss += loss_value.data.item()
total_train_loss += loss_value.data.item()
# Calculate categorical accuracy
pred = torch.round(outputs).long()
running_acc += (pred == labels).sum().item()
running_sample_count += len(labels)
# Print every 10th batch of an epoch
if (i + 1) % (print_every + 1) == 0:
print("Epoch {}, {:d}% \t train_loss: {:.4e} "
"train_acc: {:4.2f}% took: {:.2f}s".format(
epoch + 1, int(100 * (i + 1) / n_batches),
running_loss / print_every,
100*running_acc / running_sample_count,
time.time() - start_time))
# Reset running loss and time
running_loss = 0.0
start_time = time.time()
running_sample_count = 0
y_pred_all, y_true_all = [], []
for inputs, labels in val_loader:
# Wrap tensors in Variables
inputs = inputs.cuda(device)
labels = labels.cuda(device)
# Forward pass only
val_outputs = self.network(inputs)
val_outputs = val_outputs.view(-1)
labels = labels.view(-1)
val_loss = loss(val_outputs, labels.float())
total_val_loss += val_loss.data.item()
# Calculate categorical accuracy
pred = torch.round(val_outputs).long()
running_val_acc += (pred == labels).sum().item()
running_sample_count += len(labels)
y_pred_all.append(pred.cpu().numpy().flatten())
y_true_all.append(labels.cpu().numpy().flatten())
y_pred_all = np.concatenate(y_pred_all)
y_true_all = np.concatenate(y_true_all)
from sklearn.metrics import classification_report
print(classification_report(y_true_all, y_pred_all))
total_val_loss /= len(val_loader)
total_val_acc = running_val_acc / running_sample_count
print(
"Validation loss = {:.4e} acc = {:4.2f}%".format(
total_val_loss,
100*total_val_acc))
torch.save({
'epoch': epoch,
'model_state_dict': self.network.state_dict(),
'optimizer_state_dict': self.optimizer.state_dict(),
'loss': total_val_loss,
}, '%s/model_%03d_%f.pt' % (self.model_path, epoch, total_val_loss))
print(
"Training finished, took {:.2f}s".format(
time.time() -
training_start_time))
def predict(self, data_loader):
from torch.autograd import Variable
import time
for inputs, labels in val_loader:
# Wrap tensors in Variables
inputs, labels = Variable(
inputs.cuda(device)), Variable(
labels.cuda(device))
# Forward pass only
val_outputs = self.network(inputs)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("phaselink_train config_json")
sys.exit()
with open(sys.argv[1], "r") as f:
params = json.load(f)
device = torch.device(params["device"])
X = np.load(params["training_dset_X"])
Y = np.load(params["training_dset_Y"])
print(X.shape, Y.shape)
print(np.where(Y==1)[0].size, "1 labels")
print(np.where(Y==0)[0].size, "0 labels")
dataset = MyDataset(X, Y)
n_samples = len(dataset)
indices = list(range(n_samples))
n_test = int(0.1*X.shape[0])
validation_idx = np.random.choice(indices, size=n_test, replace=False)
train_idx = list(set(indices) - set(validation_idx))
from torch.utils.data.sampler import SubsetRandomSampler
train_sampler = SubsetRandomSampler(train_idx)
validation_sampler = SubsetRandomSampler(validation_idx)
train_loader = torch.utils.data.DataLoader(
dataset,
batch_size=32,
shuffle=False,
sampler=train_sampler
)
val_loader = torch.utils.data.DataLoader(
dataset,
batch_size=32,
shuffle=False,
sampler=validation_sampler
)
stackedgru = StackedGRU()
#stackedgru = torch.nn.DataParallel(StackedGRU(), device_ids=['cuda:2', 'cuda:3', 'cuda:4'])
stackedgru = stackedgru.cuda(device)
optimizer = torch.optim.Adam(stackedgru.parameters())
#enc = Encoder(input_size=4, hidden_size=64).cuda(device)
#dec = AttnDecoder(input_size=4, hidden_size=64, output_size=1,
# max_length=500).cuda(device)
#enc_opt = torch.optim.Adam(enc.parameters())
#dec_opt = torch.optim.Adam(dec.parameters())
model = Model(stackedgru, optimizer, \
model_path='./models_saved/stacked_gru/')
#model = AttnModel(enc, dec, enc_opt, dec_opt, \
model.train(train_loader, val_loader, n_epochs)