-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
637 lines (528 loc) · 16.3 KB
/
main.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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
import time
from collections import defaultdict
from functools import partial
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyro
import pyro.distributions as dist
import pyro.infer
import pyro.optim
import torch
from pyro_specification import compute_f, guide, model
def my_loss(
model,
guide,
*args,
loss_fun,
max_loss=1e30,
max_repeats=10,
num_particles=3,
**kwargs,
):
"""Custom estimator for the ELBO that uses the median, rather than mean."""
def get_loss():
loss = loss_fun(model, guide, *args, **kwargs)
repeats = 0
while torch.abs(loss) > max_loss or torch.isnan(loss):
loss = loss_fun(model, guide, *args, **kwargs)
repeats += 1
if repeats > max_repeats:
raise ValueError("Too many repeats")
return loss
losses = torch.stack([get_loss() for i in range(num_particles)])
return torch.median(losses, dim=0)[0]
def run_svi(
model,
guide,
optim,
loss,
num_iterations,
input,
interval=100,
to_print=None,
seed=49380,
):
"""Run Pyro's SVI."""
pyro.set_rng_seed(seed)
pyro.clear_param_store()
svi = pyro.infer.SVI(
model=model,
guide=guide,
optim=optim,
loss=loss,
)
losses = []
times = []
time_elapsed = 0
try:
for step in range(1, num_iterations + 1): # Consider running for more steps.
start_time = time.time()
loss = svi.step(**input)
end_time = time.time()
losses.append(loss)
time_elapsed = time_elapsed + end_time - start_time
times.append(time_elapsed)
if step % interval == 0:
if to_print:
print(to_print)
print(f"Iteration: {step},\t Total time: {time_elapsed:.2f}s")
print(
f"Median ELBO loss within last {interval} steps: {np.median(losses[step - interval:])}"
)
print()
except Exception as e:
print(e)
print("Exception occured!")
losses = np.array(losses)
times = np.array(times)
return (losses, times)
# some conveniance functions
def slice_dict(dictionary, sub_key):
return {key: value[sub_key] for key, value in dictionary.items()}
def infinite_range():
num = 1
while True:
yield num
num += 1
ordinal = (
lambda n: "%d%s "
% (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10 :: 4])
if n > 1
else ""
)
def main():
# set font-size for matplotlib
plt.rcParams.update({"font.size": 22})
### import the data
print("importing the data...")
dataset = "ma_simulation"
dataset_names = {
"ma_simulation": "MA Simulation",
"sunspots": "Sunspots Dataset",
}
dataset_name = dataset_names[dataset]
df = pd.read_csv(f"data/{dataset}.csv")
df.columns = ["X"]
data = torch.from_numpy(np.array(df["X"]))
periodogram = torch.from_numpy(
np.array(pd.read_csv(f"data/{dataset}_periodogram.csv")["x"])[0:-1]
/ (2 * np.pi)
)
omegas = torch.from_numpy(
np.array(pd.read_csv(f"data/{dataset}_frequency.csv")["x"])[0:-1] / np.pi
)
omegas_np = omegas.detach().numpy() * np.pi
input = {
"periodogram": periodogram,
"omegas": omegas,
"data": data,
"L": 20,
"MIN_K": 20,
"MAX_K": 200,
"STEP_K": 5,
}
### plot the data
fig_width, fig_height = 16 * 1.5, 9 * 1.5
fig, ax = plt.subplots()
ax.plot(
np.arange(1700, 1700 + len(data))
if dataset == "sunspots"
else np.arange(len(data)),
df,
label=f"{dataset_name}",
linewidth=4,
)
ax.grid(which="major")
ax.grid(which="minor", linestyle="--", alpha=0.5)
ax.set_xlabel("Index" if dataset == "ma_simulation" else "Year")
ax.set_ylabel(
"value"
if dataset == "ma_simulation"
else "De-Meaned Sqrt. of the Number of Sunspots"
)
fig.set_size_inches(fig_width, fig_height)
filename = f"images/{dataset}_data.png"
fig.savefig(filename)
plt.close(fig)
### sample from the prior
print("sampling from the prior...")
prior_samples = np.array([model(**input).numpy() for _ in range(3000)])
### run the inference process
print("running the inference process...")
interval = 100
num_particles = 5
num_iterations = 1000
seeds = np.arange(10)
optim = pyro.optim.AdagradRMSProp({"eta": 1, "t": 1 / 2})
loss = partial(
my_loss,
loss_fun=pyro.infer.Trace_ELBO().differentiable_loss,
num_particles=num_particles,
)
results_by_seed = {}
for seed in seeds:
losses, times = run_svi(
model,
guide,
input=input,
optim=optim,
loss=loss,
num_iterations=num_iterations,
interval=interval,
seed=seed,
)
results_by_seed[seed] = (
losses,
times,
{
param: pyro.param(param)
for param in [
"alpha_V",
"beta_V",
"alpha_Z",
"beta_Z",
"alpha_tau",
"beta_tau",
"ps_K",
]
},
)
# Transform the results into a data frame
results_by_seed_df = pd.DataFrame.from_dict(
results_by_seed, orient="index", columns=["losses", "times", "parameters"]
)
# filter out runs that did not complete
results_by_seed_df = results_by_seed_df[
list(map(lambda x: len(x) == num_iterations, results_by_seed_df.losses))
]
# sort the results by their final ELBO
results_by_seed_df["final loss"] = list(
map(lambda x: x[-1], results_by_seed_df.losses)
)
results_by_seed_df.sort_values("final loss", inplace=True)
### Sample from the approximated posterior
print("sampling from the posterior...")
num_samples = 3000
pyro.set_rng_seed(1654)
samples_by_seed = {}
for seed, row in results_by_seed_df.iterrows():
samples_by_seed[seed] = [
guide(**input, **row.parameters) for _ in range(num_samples)
]
def samples_into_tensor_dict(samples):
samples_dict = defaultdict(lambda: [])
samples_list = defaultdict(lambda: [])
for sample in samples:
for key, value in sample.items():
samples_dict[key].append(value)
samples_list[key].append(value.detach().numpy())
samples_dict["f"].append(compute_f(**input, **sample))
samples_list["f"].append(compute_f(**input, **sample).detach().numpy())
return {
key: torch.stack(value) for key, value in samples_dict.items()
}, samples_list
samples_list_by_seed = {}
for seed, samples in samples_by_seed.items():
samples_by_seed[seed], samples_list_by_seed[seed] = samples_into_tensor_dict(
samples
)
# create a pandas dataframe to hold the samples
samples_df_by_seed = {
seed: pd.DataFrame.from_dict(samples_list)
for seed, samples_list in samples_list_by_seed.items()
}
# store the approximated spectral densities separately
spds_by_seed = {}
for seed, samples_df in samples_df_by_seed.items():
spds_by_seed[seed] = torch.tensor(samples_df.f.to_list())
def mean_k(ps_K, MIN_K, MAX_K, STEP_K, **kwargs):
LEN_K = int(np.ceil((MAX_K - MIN_K) / STEP_K))
return torch.sum(ps_K * (torch.arange(LEN_K) * STEP_K + MIN_K))
def expected_value_parameters(
alpha_V, beta_V, alpha_Z, beta_Z, alpha_tau, beta_tau, ps_K
):
"""Compute the expected value approximation."""
V = dist.Beta(alpha_V, beta_V).mean
Z = dist.Beta(alpha_Z, beta_Z).mean
tau = dist.Gamma(alpha_tau, beta_tau).mean
K = mean_k(ps_K, **input).to(torch.long)
return {"V": V, "Z": Z, "tau": tau, "K": K}
### load the MCMC estimate and true posterior, if available
mcmc_spd = np.genfromtxt(f"data/{dataset}_mcmc.csv", delimiter=",", skip_header=1)
N = len(mcmc_spd)
omegas_mcmc = np.linspace(0, np.pi, num=N)
true_psd = None
if dataset == "ma_simulation":
true_psd = np.genfromtxt(
f"data/{dataset}_true_psd.csv", delimiter=",", skip_header=1
)
print("creating plots...")
### plot the prior
fig, ax = plt.subplots()
colors = infinite_range()
ax.plot(
omegas_np,
periodogram.detach().numpy(),
color=f"C{next(colors)}",
label="Periodogram",
linewidth=4,
)
ax.plot(
omegas_mcmc,
mcmc_spd,
color=f"C{next(colors)}",
label="MCMC Estimate",
linewidth=4,
)
# plot the mean / median of the samples of the prior
ax.plot(
omegas_np,
np.mean(prior_samples, axis=0),
color=f"C{next(colors)}",
label="Point-Wise Mean of Prior Samples",
linewidth=4,
)
ax.plot(
omegas_np,
np.median(prior_samples, axis=0),
color=f"C{next(colors)}",
label="Point-Wise Median of Prior Samples",
linewidth=4,
)
if true_psd is not None:
ax.plot(
omegas_mcmc,
true_psd,
color=f"C{next(colors)}",
label="True Spectral Density",
linewidth=4,
)
ax.set_yscale("log")
ax.grid(which="major")
fig.legend()
ax.set_xlabel("Frequency")
ax.set_ylabel("Value")
fig.set_size_inches(fig_width, fig_height)
filename = f"images/{dataset}_prior.png"
fig.savefig(filename)
plt.close(fig)
### plot the expected value approximation
num_seeds = 5
fig, ax = plt.subplots()
colors = infinite_range()
ax.plot(
omegas_np,
periodogram.detach().numpy(),
color=f"C{next(colors)}",
label="Periodogram",
linewidth=4,
)
ax.plot(
omegas_mcmc,
mcmc_spd,
color=f"C{next(colors)}",
label="MCMC Estimate",
linewidth=4,
)
# plot the expected value approximation
for index, parameters in enumerate(results_by_seed_df.parameters):
if index > num_seeds - 1:
break
approximation_parameters = expected_value_parameters(**parameters)
if approximation_parameters is None:
continue
ax.plot(
omegas_np,
compute_f(**approximation_parameters, **input).detach().numpy(),
color=f"C{next(colors)}",
label=f"{ordinal(index+1)}Largest Final ELBO",
linewidth=4,
)
if true_psd is not None:
ax.plot(
omegas_mcmc,
true_psd,
color=f"C{next(colors)}",
label="True Spectral Density",
linewidth=4,
)
ax.set_yscale("log")
ax.grid(which="major")
lines, labels = ax.get_legend_handles_labels()
fig.legend(lines, labels, loc="center")
ax.set_xlabel("Frequency")
ax.set_ylabel("Value")
fig.set_size_inches(fig_width, fig_height)
filename = f"images/{dataset}_expected_value_spds_best_seeds.png"
fig.savefig(filename)
plt.close(fig)
### plot some samples from the posterior with the best final ELBO
fig, ax = plt.subplots()
colors = infinite_range()
spds = spds_by_seed[list(spds_by_seed.keys())[0]]
ax.plot(
omegas_np,
periodogram.detach().numpy(),
color=f"C{next(colors)}",
label="Periodogram",
linewidth=4,
)
ax.plot(
omegas_mcmc,
mcmc_spd,
color=f"C{next(colors)}",
label="MCMC Estimate",
linewidth=4,
)
for index, psd in enumerate(spds[:5]):
ax.plot(
omegas_np,
psd,
color=f"C{next(colors)}",
label=f"Sample {index+1}",
linewidth=4,
)
if true_psd is not None:
ax.plot(
omegas_mcmc,
true_psd,
color=f"C{next(colors)}",
label="True Spectral Density",
linewidth=4,
)
ax.set_yscale("log")
ax.grid(which="major")
lines, labels = ax.get_legend_handles_labels()
fig.legend(lines, labels, loc="lower right")
ax.set_xlabel("Frequency")
ax.set_ylabel("Value")
fig.set_size_inches(fig_width, fig_height)
filename = f"images/{dataset}_spds_one_seed.png"
fig.savefig(filename)
plt.close(fig)
### plot the mean of all sample approximation, by seed
num_seeds = 5
fig, ax = plt.subplots()
colors = infinite_range()
ax.plot(
omegas_np,
periodogram.detach().numpy(),
color=f"C{next(colors)}",
label="Periodogram",
linewidth=4,
)
ax.plot(
omegas_mcmc,
mcmc_spd,
color=f"C{next(colors)}",
label="MCMC Estimate",
linewidth=4,
)
for index, spds in enumerate(spds_by_seed.values()):
if index >= num_seeds:
break
ax.plot(
omegas_np,
torch.mean(spds, dim=-2).detach().numpy(),
color=f"C{next(colors)}",
label=f"{ordinal(index+1)}Largest Final ELBO",
linewidth=4,
)
if true_psd is not None:
ax.plot(
omegas_mcmc,
true_psd,
color=f"C{next(colors)}",
label="True Spectral Density",
linewidth=4,
)
ax.set_yscale("log")
ax.grid(which="major")
lines, labels = ax.get_legend_handles_labels()
fig.legend(lines, labels, loc="lower right")
ax.set_xlabel("Frequency")
ax.set_ylabel("Value")
fig.set_size_inches(fig_width, fig_height)
filename = f"images/{dataset}_mean_spd_best_seeds.png"
fig.savefig(filename)
plt.close(fig)
### plot the median of all sample approximations, by seed
num_seeds = 5
fig, ax = plt.subplots()
colors = infinite_range()
ax.plot(
omegas_np,
periodogram.detach().numpy(),
color=f"C{next(colors)}",
label="Periodogram",
linewidth=4,
)
ax.plot(
omegas_mcmc,
mcmc_spd,
color=f"C{next(colors)}",
label="MCMC Estimate",
linewidth=4,
)
for index, spds in enumerate(spds_by_seed.values()):
if index >= num_seeds:
break
ax.plot(
omegas_np,
torch.median(spds, dim=-2)[0].detach().numpy(),
color=f"C{next(colors)}",
label=f"{ordinal(index+1)}Largest Final ELBO",
linewidth=4,
)
if true_psd is not None:
ax.plot(
omegas_mcmc,
true_psd,
color=f"C{next(colors)}",
label="True Spectral Density",
linewidth=4,
)
ax.set_yscale("log")
ax.grid(which="major")
fig.legend(loc="lower right")
ax.set_xlabel("Frequency")
ax.set_ylabel("Value")
fig.set_size_inches(fig_width, fig_height)
filename = f"images/{dataset}_median_spd_best_seeds.png"
fig.savefig(filename)
plt.close(fig)
### plot the convergence of the inference process
smoothing_number = "100"
smoothing_unit = "ms"
colors = infinite_range()
fig, ax = plt.subplots()
for index, result in results_by_seed_df.reset_index().iterrows():
diagnostics = pd.DataFrame({"elbo": result.losses, "time": result.times})
diagnostics["time"] = pd.to_datetime(
(diagnostics["time"] * 10**9).astype(int)
)
diagnostics.set_index("time", inplace=True)
elbo_by_time = (
-diagnostics["elbo"].rolling(f"{smoothing_number}{smoothing_unit}").median()
)
ax.plot(
elbo_by_time,
color=f"C{next(colors)}",
label=f"{ordinal(index+1)}Largest ELBO",
linewidth=4,
)
ax.set_yscale("symlog")
ax.grid(which="major")
ax.grid(which="minor", linestyle="--", alpha=0.5)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%M:%S"))
ax.legend()
ax.set_xlabel("Processing Time (min:s)")
ax.set_ylabel(f"Median ELBO within ${smoothing_number}\,${smoothing_unit}")
fig.set_size_inches(fig_width, fig_height)
filename = f"images/{dataset}_convergence.png"
fig.savefig(filename)
plt.close(fig)
if __name__ == "__main__":
main()