-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
154 lines (114 loc) · 5.05 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
import os
from ray import tune
import torch
import time
import numpy as np
def train_model(net, optimizer, loss_fn, trainloader, validloader, scheduler, patience, max_epochs, verbose=1, device='cuda:0', one_hot=False, n_classes=50):
history = {
"best_valid_acc" : 0,
"best_valid_loss" : np.inf,
"init_lambd" : net.spectrogram_layer.lambd.item(),
"converged" : False,
}
best_valid_acc = 0
best_valid_loss = np.inf
patience_count = 0
for epoch in range(max_epochs):
net.train()
running_loss = 0.0
running_energy = 0.0
count = 0
for i, data in enumerate(trainloader):
t_tot1 = time.time()
inputs, labels = data
if one_hot:
# TODO: this won't work in general
labels = torch.nn.functional.one_hot(labels, n_classes).float()
t1 = time.time()
inputs, labels = inputs.to(device), labels.to(device)
t2 = time.time()
#print("time 1 = {}, batch = {}".format(t2-t1, i))
optimizer.zero_grad()
t1 = time.time()
logits, s = net(inputs)
t2 = time.time()
#print("time 2 = {}, batch = {}".format(t2-t1, i))
loss = loss_fn(logits, labels)# + aux_loss
loss.backward()
optimizer.step()
if verbose >= 2:
if i % 10 == 0:
print("max values: ", torch.max(logits, dim=1).values.cpu().detach().numpy())
print("batch loss = {}".format(loss.item()))
print("est. lambd = ", net.spectrogram_layer.lambd.item())
running_loss += loss.item()
running_energy += np.sum(s.cpu().detach().numpy())
count += 1
t_tot2 = time.time()
#print("time total = {}, batch = {}".format(t_tot2-t_tot1, i))
# step scheduler
scheduler.step()
train_loss = running_loss / count
train_energy = running_energy / count
if verbose >= 1:
print("epoch {}, train loss = {}".format(epoch, running_loss / count))
print("est. lambd = ", net.spectrogram_layer.lambd.item())
running_loss = 0.0
count = 0
running_acc = 0.0
net.eval()
for data in validloader:
inputs, labels = data
if one_hot:
# TODO: this won't work in general
labels = torch.nn.functional.one_hot(labels, n_classes).float()
inputs, labels = inputs.to(device), labels.to(device)
outputs, spectrograms = net(inputs)
loss = loss_fn(outputs, labels)
predictions = torch.argmax(outputs, axis=1)
if one_hot:
labels = torch.argmax(labels, axis=1)
accuracy = torch.mean((predictions == labels).float())
running_acc += accuracy.item()
running_loss += loss.item()
count += 1
valid_loss = running_loss / count
valid_acc = running_acc / count
# save epoch model
#with tune.checkpoint_dir(epoch) as checkpoint_dir:
# path = os.path.join(checkpoint_dir, "checkpoint")
# torch.save((net.state_dict(), optimizer.state_dict()), path)
if valid_loss < best_valid_loss: # < best_valid_loss:
# save best model
with tune.checkpoint_dir(0) as checkpoint_dir:
path = os.path.join(checkpoint_dir, "best_model")
torch.save((net.state_dict(), optimizer.state_dict()), path)
best_valid_acc = valid_acc
best_valid_loss = valid_loss
best_lambd_est = net.spectrogram_layer.lambd.item()
patience_count = 0
if verbose >= 1:
print("new best valid acc = {}, patience_count = {}".format(best_valid_acc, patience_count))
else:
patience_count += 1
# report results
tune.report(loss=train_loss, lambd_est=net.spectrogram_layer.lambd.item(), valid_loss=valid_loss, valid_acc=valid_acc, best_valid_acc=best_valid_acc, best_valid_loss=best_valid_loss, energy=train_energy, best_lambd_est=best_lambd_est)
if verbose >= 1:
print("epoch {}, valid loss = {}".format(epoch, valid_loss))
print("epoch {}, valid acc = {}".format(epoch, valid_acc))
# plot spectrogram
plt.imshow(np.flip(spectrograms[0,0,:,:].cpu().detach().numpy(), axis=0), aspect='auto')
plt.title("label = {}".format(labels.cpu().detach().numpy()[0]))
plt.show()
running_loss = 0.0
running_acc = 0.0
count = 0
if patience_count >= patience:
print("no more patience, break training loop ...")
history["converged"] = True
break
# save history
history["best_valid_acc"] = best_valid_acc
history["best_valid_loss"] = best_valid_loss
history["est_lambd"] = net.spectrogram_layer.lambd.item()
return net, history