-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
196 lines (149 loc) · 5.71 KB
/
util.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
from typing import Any, Callable, Optional
import torch
import numpy as np
from pytorch_lightning.metrics.metric import Metric
from torch_geometric.utils import dense_to_sparse, get_laplacian, to_dense_adj
def get_L(W):
edge_index, edge_weight = dense_to_sparse(W)
edge_index, edge_weight = get_laplacian(edge_index, edge_weight)
adj = to_dense_adj(edge_index, edge_attr=edge_weight)[0]
return adj
def get_L_ASTGCN(W):
edge_index, edge_weight = dense_to_sparse(W)
edge_index, edge_weight = get_laplacian(edge_index, edge_weight, normalization="rw")
adj = to_dense_adj(edge_index, edge_attr=edge_weight)[0]
return adj
def masked_mse(preds, labels, null_val=np.nan):
if np.isnan(null_val):
mask = ~torch.isnan(labels)
else:
mask = (labels!=null_val)
mask = mask.float()
mask /= torch.mean((mask))
mask = torch.where(torch.isnan(mask), torch.zeros_like(mask), mask)
loss = (preds-labels)**2
loss = loss * mask
loss = torch.where(torch.isnan(loss), torch.zeros_like(loss), loss)
return torch.mean(loss)
def masked_rmse(preds, labels, null_val=np.nan):
return torch.sqrt(masked_mse(preds=preds, labels=labels, null_val=null_val))
def masked_mae(preds, labels, null_val=np.nan):
if np.isnan(null_val):
mask = ~torch.isnan(labels)
else:
mask = (labels!=null_val)
mask = mask.float()
mask /= torch.mean((mask))
mask = torch.where(torch.isnan(mask), torch.zeros_like(mask), mask)
loss = torch.abs(preds-labels)
loss = loss * mask
loss = torch.where(torch.isnan(loss), torch.zeros_like(loss), loss)
return torch.mean(loss)
def masked_mape(preds, labels, null_val=np.nan):
if np.isnan(null_val):
mask = ~torch.isnan(labels)
else:
mask = (labels!=null_val)
mask = mask.float()
mask /= torch.mean((mask))
mask = torch.where(torch.isnan(mask), torch.zeros_like(mask), mask)
loss = torch.abs(preds-labels)/labels
loss = loss * mask
loss = torch.where(torch.isnan(loss), torch.zeros_like(loss), loss)
return torch.mean(loss)
def metric(pred, real):
mae = masked_mae(pred, real, 0.0).item()
mape = masked_mape(pred, real, 0.0).item()
rmse = masked_rmse(pred, real, 0.0).item()
return np.round(mae, 4), np.round(mape, 4), np.round(rmse, 4)
class LightningMetric(Metric):
def __init__(
self,
compute_on_step: bool = True,
dist_sync_on_step: bool = False,
process_group: Optional[Any] = None,
dist_sync_fn: Callable = None,
):
super().__init__(
compute_on_step=compute_on_step,
dist_sync_on_step=dist_sync_on_step,
process_group=process_group,
dist_sync_fn=dist_sync_fn,
)
self.add_state("y_true", default=[], dist_reduce_fx=None)
self.add_state("y_pred", default=[], dist_reduce_fx=None)
def update(self, preds: torch.Tensor, target: torch.Tensor):
"""
Update state with predictions and targets.
Args:
preds: Predictions from model
target: Ground truth values
"""
self.y_pred.append(preds)
self.y_true.append(target)
def compute(self):
"""
Computes explained variance over state.
"""
y_pred = torch.cat(self.y_pred, dim=0)
y_true = torch.cat(self.y_true, dim=0)
feature_dim = y_pred.shape[-1]
pred_len = y_pred.shape[1]
# (16, 12, 38, 1)
y_pred = torch.reshape(y_pred.permute((0, 2, 1, 3)), (-1, pred_len, feature_dim))
y_true = torch.reshape(y_true.permute((0, 2, 1, 3)), (-1, pred_len, feature_dim))
# TODO: feature_dim, for multi-variable prediction, not only one.
y_pred = y_pred[..., 0]
y_true = y_true[..., 0]
metric_dict = {}
rmse_avg = []
mae_avg = []
mape_avg = []
for i in range(pred_len):
mae, mape, rmse = metric(y_pred[:, i], y_true[:, i])
idx = i + 1
metric_dict.update({'rmse_%s' % idx: rmse})
metric_dict.update({'mae_%s' % idx: mae})
metric_dict.update({'mape_%s' % idx: mape})
rmse_avg.append(rmse)
mae_avg.append(mae)
mape_avg.append(mape)
metric_dict.update({'rmse_avg': np.round(np.mean(rmse_avg), 4)})
metric_dict.update({'mae_avg': np.round(np.mean(mae_avg), 4)})
metric_dict.update({'mape_avg': np.round(np.mean(mape_avg), 4)})
return metric_dict
class StandardScaler():
def __init__(self, mean, std):
self.mean = mean
self.std = std
def transform(self, data):
return (data - self.mean) / self.std
def inverse_transform(self, data):
return (data * self.std) + self.mean
def cheb_polynomial(L_tilde, K):
'''
compute a list of chebyshev polynomials from T_0 to T_{K-1}
Parameters
----------
L_tilde: scaled Laplacian, np.ndarray, shape (N, N)
K: the maximum order of chebyshev polynomials
Returns
----------
cheb_polynomials: list(np.ndarray), length: K, from T_0 to T_{K-1}
'''
N = L_tilde.shape[0]
cheb_polynomials = [np.identity(N), L_tilde.copy()]
for i in range(2, K):
cheb_polynomials.append(2 * L_tilde * cheb_polynomials[i - 1] - cheb_polynomials[i - 2])
return cheb_polynomials
if __name__ == '__main__':
lightning_metric = LightningMetric()
batches = 10
for i in range(batches):
preds = torch.randn(32, 24, 38, 1)
target = preds + 0.15
rmse_batch = lightning_metric(preds, target)
print(f"Metrics on batch {i}: {rmse_batch}")
rmse_epoch = lightning_metric.compute()
print(f"Metrics on all data: {rmse_epoch}")
lightning_metric.reset()