forked from cdcepi/Flusight-forecast-data
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplot_scores.py
More file actions
340 lines (231 loc) · 8.22 KB
/
plot_scores.py
File metadata and controls
340 lines (231 loc) · 8.22 KB
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
# Ground truth is from covid-hospitalization-all-state-merged_vEW202210.csv
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import glob
from epiweeks import Week
from metrics import *
EPS = 1e-6
import matplotlib.pyplot as plt
import math
# In[2]:
# ground truth
df_ground_truth = pd.read_csv("ground_truth.csv")
# In[3]:
df_ground_truth.head()
df_grnd = df_ground_truth[["epiweek", "region", "cdc_flu_hosp"]]
df_grnd = df_grnd[df_grnd["epiweek"] >= 202201]
df_grnd = df_grnd.rename(
columns={"epiweek": "predicted_week", "cdc_flu_hosp": "value", "region": "location"}
)
df_grnd["location"] = df_grnd["location"].str.replace("X", "US")
df_grnd["location"] = df_grnd["location"].str.replace("TUS", "TX")
df_grnd = df_grnd.sort_values("location", kind="mergesort")
# df_grnd.head()
# In[4]:
file_dir = "./predictions.csv"
df_total = pd.read_csv(file_dir)
# In[5]:
df_total["model"].nunique()
df_final = df_total.copy()
all_model_names = np.array(df_final["model"].drop_duplicates())
# In[6]:
all_model_names = np.array(df_final["model"].drop_duplicates())
df_gt = df_final[df_final["model"] == "GT-FluFNP"]
# GT-FluFNP model hasn't predicted for some locations
all_regions = np.array(df_gt["location"].drop_duplicates())
regions_ground_truth = np.array(df_grnd["location"].drop_duplicates())
# In[7]:
df_point = df_final[df_final["type"] == "point"]
df_quant = df_final[df_final["type"] == "quantile"]
# In[8]:
weeks = np.array(df_point["forecast_week"].drop_duplicates())
max_week = df_grnd["predicted_week"].max()
# In[9]:
df_point["predicted_week"] = df_point["forecast_week"] + df_point["ahead"]
# Have ground truth only till week 10
df_point = df_point[df_point["predicted_week"] <= max_week]
# In[10]:
# Merging the two datasets on predicted week
df_newpoint = pd.merge(df_point, df_grnd, on="predicted_week")
# Removing all unnecessary merges
df_newpoint = df_newpoint[df_newpoint["location_x"] == df_newpoint["location_y"]]
# In[11]:
rmse_all = []
nrmse_all = []
model_all = []
mape_all = []
week_ahead = []
regions = []
# In[ ]:
for model in all_model_names:
for i in range(1, 5):
for region in all_regions:
sample = df_newpoint[
(df_newpoint["model"] == model)
& (df_newpoint["ahead"] == i)
& (df_newpoint["location_x"] == region)
]["value_x"].values
target = df_newpoint[
(df_newpoint["model"] == model)
& (df_newpoint["ahead"] == i)
& (df_newpoint["location_x"] == region)
]["value_y"].values
rmse_all.append(rmse(sample, target))
nrmse_all.append(norm_rmse(sample, target))
# Deal with inf values
target = np.array([EPS if x == 0 else x for x in target]).reshape(
(len(target), 1)
)
mape_all.append(mape(sample, target))
model_all.append(model)
week_ahead.append(i)
regions.append(region)
# In[ ]:
df_point_scores = pd.DataFrame.from_dict(
{
"Model": model_all,
"RMSE": rmse_all,
"NRMSE": nrmse_all,
"MAPE": mape_all,
"Weeks ahead": week_ahead,
"Location": regions,
}
)
# In[ ]:
df_point_scores.to_csv("point_scores.csv")
# In[12]:
# target is ground truth
df_quant = df_final[df_final["type"] == "quantile"]
# In[13]:
# norm_val = (df_quant['value']-df_quant['value'].min())/(df_quant['value'].max()-df_quant['value'].min())
norm_df_quant = df_quant.copy()
norm_df_quant["predicted_week"] = (
norm_df_quant["forecast_week"] + norm_df_quant["ahead"]
)
norm_df_quant = norm_df_quant[norm_df_quant["predicted_week"] <= max_week]
# In[64]:
week_ahead = []
regions = []
crps_all = []
ls_all = []
model_all = []
cs_all = []
# In[65]:
# Runtime warning - invalid value occurs during multiply -- ignore
import warnings
warnings.filterwarnings("ignore")
# In[66]:
# All models
count = 0
for model in all_model_names:
print("Compiling scores of model ", model)
print(f"Model {count}/{len(all_model_names)}")
count += 1
# All Weeks ahead
for i in range(1, 5):
print("Week ahead ", i)
# All regions
for region in all_regions:
# Dataset with information about Ground truth ('value_y') and predictions ('value_x')
target = df_newpoint[
(df_newpoint["model"] == model)
& (df_newpoint["ahead"] == i)
& (df_newpoint["location_x"] == region)
]
norm_model = norm_df_quant[
(norm_df_quant["model"] == model)
& (norm_df_quant["ahead"] == i)
& (norm_df_quant["location"] == region)
]
mean_ = []
std_ = []
var_ = []
tg_vals = []
pred_vals = []
weeks = np.array(target["forecast_week"].drop_duplicates())
if len(weeks) != 0:
for week in weeks:
# Append point predictions
point_val = target[(target["forecast_week"] == week)][
"value_x"
].values
mean_.append(point_val)
if len(point_val) == 0:
print(i, week, region, model)
# Append point pred as predictions
predval = target[(target["forecast_week"] == week)][
"value_y"
].values
pred_vals.append(predval)
# Append ground truth as target
tgval = target[(target["forecast_week"] == week)]["value_y"].values
tg_vals.append(tgval)
# Find std from quantiles
b = norm_model[
(norm_model["forecast_week"] == week)
& (norm_model["quantile"] == 0.75)
]["value"].values
a = norm_model[
(norm_model["forecast_week"] == week)
& (norm_model["quantile"] == 0.25)
]["value"].values
std = (b - a) / 1.35
var = std**2
std_.append(std)
var_.append(var)
std_ = np.array(std_)
var_ = np.array(var_)
pred_vals = np.array(pred_vals)
mean_ = np.array(mean_)
tg_vals = np.array(tg_vals)
if len(tg_vals) == 0:
print(
"No target found for week ahead ",
i,
" region ",
region,
"model ",
model,
)
#
# print(cr, ls)
# Calculate ls and crps
cr = crps(mean_, std_, tg_vals)
ls = log_score(mean_, std_, tg_vals, window = 0.1)
if(ls<-10):
ls = -10
# print(cr, ls, "hi")
auc, cs, _ = get_pr(mean_, std_**2, tg_vals)
# if(ls<-10 or math.isnan(ls)):
# ls = -10
# elif(ls>10):
# ls = 10
# if(math.isnan(cr)):
# cr = 0
crps_all.append(cr)
ls_all.append(ls)
# print(cs)
cs_all.append(cs)
else:
crps_all.append(np.nan)
ls_all.append(np.nan)
cs_all.append(np.nan)
week_ahead.append(i)
regions.append(region)
model_all.append(model)
# In[67]:
df_spread_scores = pd.DataFrame.from_dict(
{
"Model": model_all,
"Weeks ahead": week_ahead,
"Location": regions,
"LS": ls_all,
"CRPS": crps_all,
"CS": cs_all,
}
)
# In[68]:
df_spread_scores.isna().sum()
# In[70]:
df_spread_scores.to_csv("spread_scores.csv")