-
Notifications
You must be signed in to change notification settings - Fork 86
/
utils.py
213 lines (183 loc) · 7.61 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
208
209
210
211
212
213
import numpy as np
import torch
from torch.optim import Adam
from tqdm import tqdm
import pickle
def train(
model,
config,
train_loader,
valid_loader=None,
valid_epoch_interval=20,
foldername="",
):
optimizer = Adam(model.parameters(), lr=config["lr"], weight_decay=1e-6)
if foldername != "":
output_path = foldername + "/model.pth"
p1 = int(0.75 * config["epochs"])
p2 = int(0.9 * config["epochs"])
lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(
optimizer, milestones=[p1, p2], gamma=0.1
)
best_valid_loss = 1e10
for epoch_no in range(config["epochs"]):
avg_loss = 0
model.train()
with tqdm(train_loader, mininterval=5.0, maxinterval=50.0) as it:
for batch_no, train_batch in enumerate(it, start=1):
optimizer.zero_grad()
loss = model(train_batch)
loss.backward()
avg_loss += loss.item()
optimizer.step()
it.set_postfix(
ordered_dict={
"avg_epoch_loss": avg_loss / batch_no,
"epoch": epoch_no,
},
refresh=False,
)
if batch_no >= config["itr_per_epoch"]:
break
lr_scheduler.step()
if valid_loader is not None and (epoch_no + 1) % valid_epoch_interval == 0:
model.eval()
avg_loss_valid = 0
with torch.no_grad():
with tqdm(valid_loader, mininterval=5.0, maxinterval=50.0) as it:
for batch_no, valid_batch in enumerate(it, start=1):
loss = model(valid_batch, is_train=0)
avg_loss_valid += loss.item()
it.set_postfix(
ordered_dict={
"valid_avg_epoch_loss": avg_loss_valid / batch_no,
"epoch": epoch_no,
},
refresh=False,
)
if best_valid_loss > avg_loss_valid:
best_valid_loss = avg_loss_valid
print(
"\n best loss is updated to ",
avg_loss_valid / batch_no,
"at",
epoch_no,
)
if foldername != "":
torch.save(model.state_dict(), output_path)
def quantile_loss(target, forecast, q: float, eval_points) -> float:
return 2 * torch.sum(
torch.abs((forecast - target) * eval_points * ((target <= forecast) * 1.0 - q))
)
def calc_denominator(target, eval_points):
return torch.sum(torch.abs(target * eval_points))
def calc_quantile_CRPS(target, forecast, eval_points, mean_scaler, scaler):
target = target * scaler + mean_scaler
forecast = forecast * scaler + mean_scaler
quantiles = np.arange(0.05, 1.0, 0.05)
denom = calc_denominator(target, eval_points)
CRPS = 0
for i in range(len(quantiles)):
q_pred = []
for j in range(len(forecast)):
q_pred.append(torch.quantile(forecast[j : j + 1], quantiles[i], dim=1))
q_pred = torch.cat(q_pred, 0)
q_loss = quantile_loss(target, q_pred, quantiles[i], eval_points)
CRPS += q_loss / denom
return CRPS.item() / len(quantiles)
def calc_quantile_CRPS_sum(target, forecast, eval_points, mean_scaler, scaler):
eval_points = eval_points.mean(-1)
target = target * scaler + mean_scaler
target = target.sum(-1)
forecast = forecast * scaler + mean_scaler
quantiles = np.arange(0.05, 1.0, 0.05)
denom = calc_denominator(target, eval_points)
CRPS = 0
for i in range(len(quantiles)):
q_pred = torch.quantile(forecast.sum(-1),quantiles[i],dim=1)
q_loss = quantile_loss(target, q_pred, quantiles[i], eval_points)
CRPS += q_loss / denom
return CRPS.item() / len(quantiles)
def evaluate(model, test_loader, nsample=100, scaler=1, mean_scaler=0, foldername=""):
with torch.no_grad():
model.eval()
mse_total = 0
mae_total = 0
evalpoints_total = 0
all_target = []
all_observed_point = []
all_observed_time = []
all_evalpoint = []
all_generated_samples = []
with tqdm(test_loader, mininterval=5.0, maxinterval=50.0) as it:
for batch_no, test_batch in enumerate(it, start=1):
output = model.evaluate(test_batch, nsample)
samples, c_target, eval_points, observed_points, observed_time = output
samples = samples.permute(0, 1, 3, 2) # (B,nsample,L,K)
c_target = c_target.permute(0, 2, 1) # (B,L,K)
eval_points = eval_points.permute(0, 2, 1)
observed_points = observed_points.permute(0, 2, 1)
samples_median = samples.median(dim=1)
all_target.append(c_target)
all_evalpoint.append(eval_points)
all_observed_point.append(observed_points)
all_observed_time.append(observed_time)
all_generated_samples.append(samples)
mse_current = (
((samples_median.values - c_target) * eval_points) ** 2
) * (scaler ** 2)
mae_current = (
torch.abs((samples_median.values - c_target) * eval_points)
) * scaler
mse_total += mse_current.sum().item()
mae_total += mae_current.sum().item()
evalpoints_total += eval_points.sum().item()
it.set_postfix(
ordered_dict={
"rmse_total": np.sqrt(mse_total / evalpoints_total),
"mae_total": mae_total / evalpoints_total,
"batch_no": batch_no,
},
refresh=True,
)
with open(
foldername + "/generated_outputs_nsample" + str(nsample) + ".pk", "wb"
) as f:
all_target = torch.cat(all_target, dim=0)
all_evalpoint = torch.cat(all_evalpoint, dim=0)
all_observed_point = torch.cat(all_observed_point, dim=0)
all_observed_time = torch.cat(all_observed_time, dim=0)
all_generated_samples = torch.cat(all_generated_samples, dim=0)
pickle.dump(
[
all_generated_samples,
all_target,
all_evalpoint,
all_observed_point,
all_observed_time,
scaler,
mean_scaler,
],
f,
)
CRPS = calc_quantile_CRPS(
all_target, all_generated_samples, all_evalpoint, mean_scaler, scaler
)
CRPS_sum = calc_quantile_CRPS_sum(
all_target, all_generated_samples, all_evalpoint, mean_scaler, scaler
)
with open(
foldername + "/result_nsample" + str(nsample) + ".pk", "wb"
) as f:
pickle.dump(
[
np.sqrt(mse_total / evalpoints_total),
mae_total / evalpoints_total,
CRPS,
],
f,
)
print("RMSE:", np.sqrt(mse_total / evalpoints_total))
print("MAE:", mae_total / evalpoints_total)
print("CRPS:", CRPS)
print("CRPS_sum:", CRPS_sum)