-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.py
207 lines (156 loc) · 4.67 KB
/
utils.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
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.optim as optim
from tqdm import tqdm
def get_best_device(fallback="cpu"):
return torch.device("cuda:0" if torch.cuda.is_available() else fallback)
def get_ccycle(n, cmap="jet"):
return [plt.get_cmap(cmap)(i) for i in np.linspace(0.0, 1.0, n)]
def scan(model, x_min, x_max, n=300, device=None):
x = torch.linspace(x_min, x_max, n, device=device)
if device:
model = model.to(device)
model.eval()
with torch.no_grad():
y = model(x.unsqueeze(1)).cpu().numpy()
x = x.cpu().numpy()
return x, y
def weighted_avg(x):
nom = 0
denom = 0
for n, v in x:
nom += n * v
denom += n
return nom / denom
def nop(*args, **kwargs):
pass
def train_epoch(
model, optimizer, *, train_dl, test_dl, loss_fct, error_fct=None, device=None
):
if error_fct is None:
error_fct = nop
loss_train = []
loss_test = []
error_train = []
error_test = []
model = model.to(device)
model.train()
for xy in train_dl:
optimizer.zero_grad()
xy = xy.to(device)
y_pred = model(xy[:, 0:1])
loss = loss_fct(y_pred, xy[:, 1])
n = y_pred.shape[0]
loss_value = loss.detach().cpu().item()
loss_train.append((n, loss_value))
if error_fct is not None:
error = error_fct(y_pred.detach(), xy[:, 1])
error_value = error.cpu().item()
error_train.append((n, error_value))
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
for xy in test_dl:
xy = xy.to(device)
y_pred = model(xy[:, 0:1])
loss = loss_fct(y_pred, xy[:, 1])
error = error_fct(y_pred.detach(), xy[:, 1])
n = y_pred.shape[0]
loss_value = loss.detach().cpu().item()
loss_test.append((n, loss_value))
if error_fct is not None:
error = error_fct(y_pred.detach(), xy[:, 1])
error_value = error.cpu().item()
error_test.append((n, error_value))
loss_train = weighted_avg(loss_train)
loss_test = weighted_avg(loss_test)
if error_fct is not None:
error_train = weighted_avg(error_train)
error_test = weighted_avg(error_test)
stats = {
"loss_train": loss_train,
"loss_test": loss_test,
"error_train": None if error_fct is None else error_train,
"error_test": None if error_fct is None else error_test,
}
return model, stats
def train(
*,
n_epochs,
model,
lr,
loss_fct,
error_fct,
train_dl,
test_dl,
scan_lim,
device=None
):
model = torch.jit.script(model)
optimizer = optim.Adam(model.parameters(), lr=lr)
loss_train = []
loss_test = []
error_train = []
error_test = []
xy = {"x": None, "y": None}
for _ in range(n_epochs):
model, loss = train_epoch(
model,
optimizer,
train_dl=train_dl,
test_dl=test_dl,
loss_fct=loss_fct,
error_fct=error_fct,
device=device,
)
loss_train.append(loss["loss_train"])
loss_test.append(loss["loss_test"])
error_train.append(loss["error_train"])
error_test.append(loss["error_test"])
x_min, x_max = scan_lim
x, y = scan(model, x_min=x_min, x_max=x_max, device=device)
xy["x"] = x
if xy["y"] is None:
xy["y"] = y[np.newaxis]
else:
xy["y"] = np.concatenate([xy["y"], y[np.newaxis]], axis=0)
return (
model,
{
"loss_train": loss_train,
"loss_test": loss_test,
"error_train": error_train,
"error_test": error_test,
},
xy,
)
def train_loop(f, *, n_samples, n_epochs, quiet=True):
loss_train = []
loss_test = []
error_train = []
error_test = []
x_scan = None
model = None
for _ in tqdm(range(n_samples), disable=quiet):
model, loss, xy = f(n_epochs=n_epochs)
loss_train.append(loss["loss_train"])
loss_test.append(loss["loss_test"])
error_train.append(loss["error_train"])
error_test.append(loss["error_test"])
y = xy["y"][np.newaxis]
if x_scan is None:
x_scan = {"x": xy["x"], "y": y}
else:
x_scan["y"] = np.concatenate([x_scan["y"], y], axis=0)
return (
model,
{
"loss_train": loss_train,
"loss_test": loss_test,
"error_train": error_train,
"error_test": error_test,
},
x_scan,
)