-
Notifications
You must be signed in to change notification settings - Fork 12
/
detector.py
1910 lines (1667 loc) · 95.8 KB
/
detector.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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Python 3.5.2 |Anaconda 4.2.0 (64-bit)|
# -*- coding: utf-8 -*-
"""
Last edited: 2017-09-13
Author: Jeremias Knoblauch ([email protected])
Forked by: Luke Shirley ([email protected])
Description: Implements the Detector, i.e. the key object in the Spatial BOCD
software. This object takes in the Data & its dimensions, the CP prior,
a set of probability models, the priors over this probability model collection,
and a model prior probability over each of the models in the collection.
"""
import numpy as np
import scipy
from scipy import misc
import time
from BVAR_NIG_DPD import BVARNIGDPD
from BVAR_NIG import BVARNIG
class Detector:
"""key object in the Spatial BOCD
software. This object takes in the Data & its dimensions, a set of
probability models and their priors, and a model prior probability
over each of the models in the collection/universe, and a CP prior.
Attributes:
data: float numpy array;
a SxS spatial lattice with T time points and thus of
dimension SxSxT
model_universe: ProbabilityModel numpy array;
the collection of models
that might fit a given segment. All children of the
ProbabilityModel parent class
model_prior: float numpy array;
a prior vector giving the prior belief for each entry
in the *model_universe* numpy array. If model_prior[i-1] = p,
then we have prior belief p that the i-th model is the generating
process for a given segment
cp_model: CpModel object;
the CP model, usually specified as a geometric distribution
over the time points.
Q: int;
the number of entries in the model_universe numpy array
T, S1, S2: int;
the dimensions of the spatial lattice (S1, S2) and the time (T),
provided that the data is not put in as data stream
predictive_probs: float numpy array;
stores the predictive probs at each time point for each lattice
point and for each potential model
growth_probs: float numpy array;
stores the probability of the run lengths being r = 1,2,..., t at
time point t.
cp_probs: float numpy array;
stores the probability of the run lengt being r=0 at time point t
evidence: float numpy array;
stores the evidence (posterior probability) of having observed
all values of the data up until time point t at each time point t
run_length_distr: float numpy array;
stores the run-length distribution for r=0,1,...,t at each time
point t.
"""
def __init__(self, data, model_universe, model_prior, cp_model,
S1, S2, T, exo_data=None, num_exo_vars=None, threshold=None,
store_rl = False, store_mrl = False, trim_type = "keep_K",
notifications = 50,
save_performance_indicators=False,
training_period = 200,
generalized_bayes_rld = False, #'kullback_leibler', 'power_divergence'
alpha_rld = None,
alpha_rld_learning = False,
alpha_param_learning = False,
alpha_param = None,
#SGD-updating of alpha_param and alpha_rld in case we use DPD
loss_der_rld_learning = None,
loss_param_learning = None,
step_size_rld_learning = None,
step_size_param_learning = None,
eps_param_learning = None,
alpha_param_opt_t=100,
alpha_rld_opt_t = 100):
#add arguments: save_negative_log_likelihood, training_period
"""construct the Detector with the multi-dimensional numpy array
*data*. E.g., if you have a SxS spatial lattice with T time points,
then *data* will be SxSxT. The argument *model_universe* will provide
you with a numpy array of ProbabilityModel objects, each of which is
associated with a model that could fit the data and allows for online
bayesian CP detection. The *model_prior* is a numpy array of floats,
summing to one such that the i-th entry corresponds to the prior belief
that the i-th model occurs in a segment. Lastly, *cp_model* is an
object of class CpModel that stores all properties about the CP prior,
i.e. the probability of one occuring at every time point.
"""
#DEBUG: initialize correctly
self.gradient = 0.0
"""store the inputs into object"""
self.data = data.reshape(T, S1*S2)
self.model_universe = model_universe
self.model_prior = model_prior
self.cp_model = cp_model
if isinstance(model_universe, list):
self.Q = int(len(model_universe))
else:
self.Q = model_universe.shape[0]
self.T, self.S1, self.S2 = T, S1, S2
self.threshold = threshold
self.store_rl, self.store_mrl = store_rl, store_mrl
self.not_all_initialized = True
#self.MAP_first_reached = True
self.m_star_old = 0
self.first_model_initialized = False
self.trim_type = trim_type #other option: "threshold"
self.notifications = notifications
self.save_performance_indicators = save_performance_indicators
self.training_period = training_period
self.negative_log_likelihood = []
self.negative_log_likelihood_fixed_pars = []
self.MSE = []
self.MAE = []
"""Take care of exogeneous variables"""
#DEBUG: At this point, assumes that we have an obs. for each location
# at later stage, might want to group areas and have only one
# exo observation per group per variable
if exo_data is not None:
self.exo_data = exo_data.reshape(T, S1*S2, num_exo_vars)
else:
self.exo_data = exo_data
self.num_exo_vars = num_exo_vars
"""create internal data structures for most recent computed objects"""
self.evidence = -np.inf
self.MAP = None
self.y_pred_mean = np.zeros(shape=(self.S1, self.S2))
self.y_pred_var = np.zeros(shape = (self.S1*self.S2, self.S1*self.S2))
"""create internal data structures for all computed objects"""
self.model_and_run_length_log_distr = (-np.inf *
np.ones(shape = (self.Q, self.T+1)))
self.storage_run_length_log_distr = [] #np.zeros(shape=(self.T+1, self.T+1))
self.storage_model_and_run_length_log_distr = []
self.storage_all_retained_run_lengths = []
self.storage_mean = np.zeros(shape = (self.T, self.S1, self.S2))
self.storage_var = np.zeros((self.T, self.S1*self.S2))
#np.zeros(shape = (self.T, self.S1*self.S2,
# self.S1*self.S2))
self.storage_log_evidence = -np.inf * np.ones(shape = self.T)
#DEBUG: I have changed code s.t. log_MAP_storage grows
#self.log_MAP_storage = -np.inf * np.ones(self.T)
#Note: has two entries at time t=1, for r = 0 and r>0
self.log_MAP_storage = np.array([0,0])#np.array([0,0])
self.CPs = [[]] * self.T
self.MAP_segmentation = [np.array([[],[]])]
#self.segment_log_densities = np.zeros(shape = (self.Q, self.T) )
"""store the smallest & largest lag length"""
self.smallest_lag_length = 99999
for model in self.model_universe:
if model.has_lags:
self.smallest_lag_length = min(self.smallest_lag_length,
model.lag_length)
else:
self.smallest_lag_length = 0
self.max_lag_length = 0
for model in self.model_universe:
if model.has_lags:
self.max_lag_length = max(self.max_lag_length,
model.lag_length)
"""STEP 3: If we are in a generalized Bayes setting, modify each model
object accordingly"""
"""STEP 3.1: If we use DPD for parameter inference and we want to
optimize the alpha paramter across all models, set the initial value
of alpha_param using either detector-input or the first model's val"""
self.alpha_param_learning = alpha_param_learning
if ((alpha_param is not None) and alpha_param_learning == "together"):
self.alpha_param = alpha_param
self.gradient_alpha_param_count = 0
self.gradient_alpha_param = 0
elif alpha_param_learning == "together":
self.alpha_param = self.model_universe[0].alpha_param
self.gradient_alpha_param_count = 0
self.gradient_alpha_param = 0
print("WARNING! You are using DPD for parameter inference " +
"and want to optimize alpha_param across all models, " +
"but you have not specified an initial value in the " +
"detector object. The alpha_param of the first " +
"model in the model universe was chosen instead")
"""STEP 3.2: Set whether we do alpha_param learning inside models.
Next, set alpha_param for all models that are DPD in case we do
joint optimization across all models. """
if ((alpha_param_learning == "individual") or
alpha_param_learning == "together"):
if alpha_param_learning == "individual":
self.gradient_alpha_param_count = np.zeros(self.Q)
self.gradient_alpha_param = np.zeros(self.Q)
"""Set the alpha_param learning attribute for DPD models"""
for model in self.model_universe:
if isinstance(model, BVARNIGDPD):
model.alpha_param_learning = True
"""Set the initial alpha_param value. This ensures that
the optimization step makes sense."""
if alpha_param_learning == "together":
model.alpha_param = self.alpha_param
self.alpha_param_opt_t = alpha_param_opt_t
self.alpha_rld_opt_t = alpha_rld_opt_t
self.alpha_opt_count = 0
"""STEP 3.3: Set all phantities relating to Run-length distribution
robustification using DPD"""
self.alpha_rld_learning = alpha_rld_learning
self.generalized_bayes_rld = generalized_bayes_rld
self.alpha_rld = alpha_rld
self.alpha_list = []
if generalized_bayes_rld == "power_divergence": #or generalized_bayes is True:
for model in self.model_universe:
model.generalized_bayes_rld = "power_divergence"
model.alpha_rld = self.alpha_rld
model.alpha_rld_learning = (
self.alpha_rld_learning)
self.jlp_scale = None #initialize the scaling of log probs
self.gradient_alpha_rld_count = 0
self.gradient_alpha_rld = 0
"""STEP 3.4: Read in all the SGD-related functions generating stepsize,
epsilon (for finite differences) and the loss function"""
"""STEP 3.4.1: Default choices for our functions"""
self.C = 1.0
if (loss_der_rld_learning is None):
loss_der_rld_learning = Detector.bounded_absolute_loss_derivative
elif (loss_der_rld_learning == "squared_loss" or
loss_der_rld_learning == "squared_loss_derivative"):
loss_der_rld_learning = Detector.squared_loss_derivative
elif (loss_der_rld_learning == "absolute_loss" or
loss_der_rld_learning == "absolute_loss_derivative"):
loss_der_rld_learning = Detector.absolute_loss_derivative
if loss_param_learning is None:
loss_param_learning = Detector.bounded_absolute_loss
elif loss_param_learning == "squared_loss":
loss_param_learning = Detector.squared_loss
elif loss_param_learning == "absolute_loss":
loss_param_learning = Detector.absolute_loss
if step_size_rld_learning is None:
step_size_rld_learning = Detector.step_size_gen_rld
if step_size_param_learning is None:
step_size_param_learning = Detector.step_size_gen_rld
if eps_param_learning is None:
eps_param_learning = Detector.eps_gen
"""STEP 3.4.2: Set the Detector attribute functions """
self.loss_der_rld_learning = loss_der_rld_learning
self.loss_param_learning = loss_param_learning
#DEBUG: Get some default functions here that make sense!
self.step_size_rld_learning = step_size_rld_learning
self.step_size_param_learning = step_size_param_learning
if step_size_param_learning is None:
self.step_size_param_learning = (
Detector.default_step_size_param_learning)
self.eps_param_learning = eps_param_learning
self.all_retained_run_lengths = np.array([], dtype=int)
def reinstantiate(self, new_model_universe):
"""clone this detector """
"""STEP 1: Copy all contents of this detector"""
data, model_universe = self.data, new_model_universe
model_prior, cp_model = self.model_prior, self.cp_model
S1, S2, T = self.S1, self.S2, self.T
exo_data, num_exo_vars = self.exo_data, self.num_exo_vars
threshold = self.threshold
store_rl, store_mrl = self.store_rl, self.store_mrl
trim_type, notifications = self.trim_type, self.notifications
save_performance_indicators = self.save_performance_indicators
training_period = self.training_period
#DEBUG: Needs updating.
"""STEP 2: Create the new detector, and return it"""
new_detector = Detector(data, model_universe, model_prior, cp_model,
S1, S2, T, exo_data, num_exo_vars, threshold,
store_rl, store_mrl, trim_type,
notifications,
save_performance_indicators,
training_period)
return new_detector
def run(self, start=None, stop=None):
"""Start running the Detector from *start* to *stop*, usually from
the first to the last observation (i.e. default).
"""
"""set start and stop if not supplied"""
if start is None:
start = 1
if stop is None:
stop = self.T
"""run the detector"""
time_start = time.clock()
time2 = 0.0
for t in range(start-1, stop-1):
if t % self.notifications == 0 and time2 != 0.0:
print("Processing observation #" + str(int(t)))
print("Last iteration took " + str(time.clock() - time2) +
" seconds")
time2 = time.clock()
self.next_run(self.data[t,:], t+1)
self.execution_time = time.clock() - time_start
def next_run(self, y, t):
"""for a new observation *y* at time *t*, run the entire algorithm
and compute all quantities at the ProbabilityModel object and the
Detector object layer necessary
NOTE: The data structures in the ProbabilityModel objects grow from
size t-1 (or t, for the sufficient statistics) to size t (or t+1)
during 'next_run'. #DEBUG: To be added: check if prior_mean, prior_var, ... are S1xS2. If
# they are not, assume that they are provided in vector and
# full covariance matrix form & compress them into internal form
"""
"""STEP 1: If t==1, initialize *joint_probabilities* and the
predictive distributions.
If t>1, update the *joint_probabilities* of (y_{1:t}, r_t =r|q_t =q)
for all q in the model universe as well as the predictive
distributions associated with each model.
Note: Calls functions 'update_joint_log_probabilities' and
'update_predictive_distributions'. The latter function is on
ProbabilityModel level, and calls 'evaluate_predictive_log_distr'
from the Model level. If we are interested in retrieving the
negative log likelihood, the
'one_step_ahead_predictive_log_probs' are also retrieved there."""
"""If we want the fixed-parameter NLL, we need to compute and store it
before we update the joint log prob"""
#if(self.save_performance_indicators and t>self.training_period):
#self.compute_negative_log_likelihood_fixed_pars(y,t) #these need to
#INSERT: alpha_param update here!
"""For all parameter-DPD models in our model universe, first update
their value of alpha_param"""
if self.max_lag_length + 3 < t and self.alpha_param_opt_t < t:
#only do if MAP has changed last iteration!
if t > 3:
if self.CPs[t-2][-1][0] != self.CPs[t-3][-1][0]:
self.alpha_opt_count = self.alpha_opt_count + 1
self.update_alpha_param(y,self.alpha_opt_count, True)
else:
self.update_alpha_param(y,self.alpha_opt_count, False)
self.update_all_joint_log_probabilities(y, t)
"""STEP 1+: If we want to save the negative log likelihood, do it here
because the run-length and model distro is not yet updated, but we
already have all the evaluated log probs y_t|y_{1:t-1},r_t-1,m_t-1"""
if(self.save_performance_indicators and t>self.training_period):
#DEBUG: Implement function
self.save_negative_log_likelihood(t)
#self.save_negative_log_likelihood_fixed_pars(t)
self.save_MSE(y,t)
"""STEP 2: Collect the model-specific evidences and update the overall
evidence by summing them up. 'update_evidence' is a simple wrapper
function for convenience"""
self.update_log_evidence()
"""STEP 3: Trim the run-length distributions in each model. Next,
update the distributions (q_t=q, r_t=r|y_{1:t}) for each
run-length r and each model in the model universe q, store the
result in *self.model_and_run_length_distr*"""
self.trim_run_length_log_distributions(t)
#self.update_model_and_run_length_log_distribution(t)
self.update_run_length_log_distribution(t) #this is stored on detector level
#and computed from the model objects
#DEBUG: This was meant to provide numerical stability, but doesn't work
# if (not self.not_all_initialized and
# self.generalized_bayes_rld == "power_divergence"):
# self.rescale_DPD_run_length_log_distribution(t) #avoid numerical issues
"""STEP 5: Using the results from STEP 3, obtain a prediction for the
next spatial lattice slice, which you preferably should either store,
output, or write to some location"""
if not self.not_all_initialized:
self.prediction_y(y, t)
self.storage(t)
"""STEP 8: Update alpha if you do power-divergence based inference.
Only start doing this once all models have been initialized"""
if ((not self.not_all_initialized) and
self.generalized_bayes_rld == "power_divergence" and
self.alpha_rld_learning and
self.alpha_rld_opt_t < t):
#only do this step if MAP CP has changed!
if t >= 3:
if self.CPs[t-2][-1][0] != self.CPs[t-3][-1][0]:
#alpha opt count already updated in param update
#self.alpha_opt_count = self.alpha_opt_count + 1
self.update_alpha_rld(y,self.alpha_opt_count,True)
else:
self.update_alpha_rld(y,self.alpha_opt_count,False)
"""STEP 4: Check if all models have been initialized. This only needs
to be checked for BVAR models. If they have all been initialized last
round (i.e., self.not_all_initialized = False), then there is never any
need to check in any of the succeeding rounds again"""
if self.not_all_initialized:
count_total, count_init = 0,0
for model in self.model_universe:
if model.has_lags:
if (t - model.lag_length >=1):
count_total += 1
count_init += 1
else:
count_total +=1
if count_total > count_init:
self.not_all_initialized = True
else:
self.not_all_initialized = False
"""STEP 6: Using the results from STEP 3, obtain a MAP for the
most likely segmentation & models per segment using the algorithm of
Fearnhead & Liu (2007)"""
#if not self.not_all_initialized:
self.MAP_estimate(t)
#NEEDS FURTHER INVESTIGATION
"""STEP 7: For each model in the model universe, update the priors to
be the posterior expectation/variance"""
if not self.not_all_initialized:
self.update_priors(t)
def rescale_DPD_run_length_log_distribution(self, t):
"""STEP 1: Compute the mean of all joint log probs (note that since
they are computed with the DPD, they will be positive!)"""
if self.jlp_scale is None:
log_scale_new = (np.max([model.joint_log_probabilities
for model in self.model_universe]) - 1)
# log_scale_new = max(1.0, scipy.misc.logsumexp([
# model.joint_log_probabilities
# for model in self.model_universe]) - 1)
rescaler_for_old_obs = None
else:
log_scale_old = self.jlp_scale
# max_ = (np.max([model.joint_log_probabilities
# for model in self.model_universe]) - 1)
min_ = (np.min([model.joint_log_probabilities
for model in self.model_universe]) - 1)
# mean_ = ((1.0/(self.Q + len(self.all_retained_run_lengths))) *
# scipy.misc.logsumexp([model.joint_log_probabilities
# for model in self.model_universe]))
# log_scale_new = scipy.misc.logsumexp(
# [model.joint_log_probabilities
# for model in self.model_universe])
log_scale_new = min_ #0.5 * max(max_-min_, 2) #min(log_scale_old,
# (np.max([model.joint_log_probabilities
# for model in self.model_universe]) - 1))
# log_scale_new = max(1.0, scipy.misc.logsumexp([model.joint_log_probabilities
# for model in self.model_universe]))
rescaler_for_old_obs = log_scale_old - log_scale_new
# -1 = nothing will be negative
# only applied to most recent obs = np.log(scale_old/scale_new)
self.jlp_scale = log_scale_new
# log_scale_new = scipy.misc.logsumexp([model.joint_log_probabilities
# for model in self.model_universe])
# """STEP 2: Use this mean to rescale all of them"""
#for model in self.model_universe:
#probabilitiy level call
#model.rescale_DPD_run_length_distribution(log_scale_new,
# None, #rescaler_for_old_obs, #rescaler_for_old_obs, #rescaler_for_old_obs,
# t)
def update_alpha_param(self, y, t, update=True):
"""Use the posterior expectation for alpha + eps and alpha - eps to
approximate the gradient for Loss(PredError(alpha)) w.r.t. alpha.
If alpha_param_learning = individual, then you optimize each DPD model
independently. If learning = together, optimize together"""
"""STEP 1: If we learn jointly over all DPD models, get their model
posterior probabilities s.t. we can get
E[y_t|y_1:t-1, alpha_t-1 + eps] = sum(
E[y_t|y_1:t-1, m_t-1, alpha_t-1 + eps]) *
P(m_t-1|y_1:t-1,alpha_t-1 + eps)
)
where we have stored P(m_t-1|y_1:t-1,alpha_t-1 + eps) from before"""
if self.alpha_param_learning == "together":
"""STEP 1A: If we optimize alpha_param over all models"""
#number_DPD_models = 0
eps = self.eps_gen(t-1) #as the eps is from the previous iteration
DPD_model_indices = []
list_model_log_evidences_p_eps = []
list_model_log_evidences_m_eps = []
list_post_mean_p_eps = []
list_post_mean_m_eps = []
"""STEP 1A.1: count number of DPD models and retrieve both their
model evidences and posterior expectations"""
for (m, model) in zip(range(0, self.Q), self.model_universe):
if isinstance(model, BVARNIGDPD):
"""retrieve P(m_t-1, y_1:t-1|alpha_t-1 +/- eps)"""
list_model_log_evidences_p_eps.append(
model.model_log_evidence_p_eps)
list_model_log_evidences_m_eps.append(
model.model_log_evidence_m_eps)
"""retrieve E[y_t|m_t-1, y_1:t-1, alpha_t-1 +/- eps]"""
list_post_mean_p_eps.append(model.
post_mean_p_eps)
list_post_mean_m_eps.append(model.
post_mean_m_eps)
"""get index of this DPD model"""
DPD_model_indices.append(m)
"""STEP 1A.2: compute the posterior means for alpha +/- eps"""
"""STEP 1A.2.1: Get the model posteriors for alpha +/- eps"""
total_evidence_p_eps = scipy.misc.logsumexp(
list_model_log_evidences_p_eps)
total_evidence_m_eps = scipy.misc.logsumexp(
list_model_log_evidences_m_eps)
model_posteriors_p_eps = np.exp(
np.array(list_model_log_evidences_p_eps)
- total_evidence_p_eps)
model_posteriors_m_eps = np.exp(
np.array(list_model_log_evidences_m_eps)
- total_evidence_m_eps)
"""STEP 1A.2.2: Get the posterior mean"""
post_mean_p_eps = (np.array(list_post_mean_p_eps)
* model_posteriors_p_eps[:,np.newaxis])
post_mean_m_eps = (np.array(list_post_mean_m_eps)
* model_posteriors_m_eps[:,np.newaxis])
"""STEP 1A.3: Compute predictive loss and take gradient step"""
#DEBUG: use more general loss functions
loss_p_eps = self.loss_param_learning(post_mean_p_eps -
y.flatten(), self.C)
loss_m_eps = self.loss_param_learning(post_mean_m_eps -
y.flatten(), self.C)
self.gradient_alpha_param = (self.gradient_alpha_param +
(loss_p_eps - loss_m_eps)/(2*eps))
#DEBUG: Use more general step sizes
self.gradient_alpha_param_count = (self.gradient_alpha_param_count
+ 1)
#bound alpha_param between pow(10,-10) and 10
if update:
step_size = self.step_size_param_learning(t)
#abs_increment = min(abs(step_size * self.gradient_alpha_param),
# 0.05)
abs_increment = min(0.1,
step_size *
(1.0/self.gradient_alpha_param_count)*
self.gradient_alpha_param)
self.alpha_param = min(
max(
pow(10,-10),
self.alpha_param -
abs_increment *
np.sign(self.gradient_alpha_param) #step_size * gradient_alpha_param
),
10.0
)
self.gradient_alpha_param = 0
self.gradient_alpha_param_count = 0
#print("detector alpha param", self.alpha_param)
"""STEP 1A.4: For each DPD model, update alpha_param"""
for m in DPD_model_indices:
self.model_universe[m].alpha_param = self.alpha_param
self.model_universe[m].alpha_param_list.append(
self.alpha_param)
elif self.alpha_param_learning == "individual":
"""STEP 1B: If we optimize alpha_param individually"""
for (m, model) in zip(range(0, self.Q), self.model_universe):
if isinstance(model, BVARNIGDPD):
#eps = self.eps_gen(t-1)
#DEBUG: use more general loss functions
loss_p_eps = np.sum(np.abs(model.post_mean_p_eps -
y.flatten()))
loss_m_eps = np.sum(np.abs(model.post_mean_m_eps -
y.flatten()))
self.gradient_alpha_param[m] = (self.gradient_alpha_param[m] +
(loss_p_eps - loss_m_eps)/
(2 * model.eps))
self.gradient_alpha_param_count[m] = (
self.gradient_alpha_param_count[m]+ 1)
#bound alpha_param between pow(10,-10) and 10
#scale the step size by model complexity to counteract
#higher variance for more complex models
if update:
#print("PARAM gradient size:", self.gradient_alpha_param[m]/self.gradient_alpha_param_count[m])
step_size = self.step_size_param_learning(t)
abs_increment = min(0.1,
step_size *
(1.0/self.gradient_alpha_param_count[m])*
self.gradient_alpha_param[m])
model.alpha_param = min(
max(
pow(10,-10),
model.alpha_param -
abs_increment *
np.sign(self.gradient_alpha_param[m]) #step_size * gradient_alpha_param
),
10.0
)
# model.alpha_param = min(
# max(
# pow(10,-10),
# model.alpha_param
# + step_size * (1.0/(model.num_regressors+1)) *
# self.gradient_alpha_param[m]
# ),
# 10.0
# )
#print("model alpha param", model.alpha_param)
model.alpha_param_list.append(model.alpha_param)
self.gradient_alpha_param[m] = 0
self.gradient_alpha_param_count[m] = 0
def update_run_length_log_distribution(self, t):
"""This function aggregates the models' individual model and run-length
log probability appropriately s.t. we end up with the proper run-length
log distribution for which the recursions are shown in Fearnhead & Liu"""
"""STEP 1: Get all growth probabilities & the CP probability"""
"""STEP 1.1: Get all models that have been initialized"""
indices_initialized_models = []
for (m, model) in zip(range(0, self.Q), self.model_universe):
"""if the model has no lags, give it 'lag 1'"""
if model.has_lags:
model_lag = model.lag_length
else:
model_lag = 0
"""if the model already contains joint_log_probabilities, use it"""
if model_lag < t: #debug: model_lag =< t?
indices_initialized_models.append(m)
num_initialized = int(len(indices_initialized_models))
"""Check if this is the first time we have an initialized model. If so,
we need to initialize the quantity self.run_length_log_distr. If we
have no initialized model yet, leave the function immediately"""
if (not self.first_model_initialized) and num_initialized > 0:
"""initialize run-length distro s.t. we can work with it"""
self.first_model_initialized = True
self.run_length_log_distr = 0 # log(1) = 0
elif (not self.first_model_initialized):
"""skip the rest of the function"""
return None
"""STEP 1.3: For all initialized models, retrieve the run lengths and
aggregate them all into *all_run_lengths*"""
has_both = False #boolean. If we have run lengths for t-1 and >t-1, flag
all_run_lengths = np.array([])
for model in self.model_universe[indices_initialized_models]:
"""Get all run lengths retained across models"""
all_run_lengths = np.union1d(all_run_lengths,
model.retained_run_lengths)
"""if we have the run-lengths for t-1 and >t-1, flag up and later
place one index twice into the all_run_lengths"""
if model.retained_run_lengths[-1] == model.retained_run_lengths[-2]:
has_both = True
"""Add run length for >t-1 if necessary"""
if has_both:
all_run_lengths = np.append(all_run_lengths, t)#all_run_lengths[-1])
"""make sure that the run-lengths we retain can be used to access
the array elements that we want."""
all_run_lengths = all_run_lengths.astype(int)
"""STEP 1.4: Create the model and run-length distr s.t. we have no
zero mass entries"""
length_rls = int(len(all_run_lengths))
model_rl_log_distributions = (-np.inf) * np.ones((
self.Q, length_rls))
"""STEP 1.5: loop over the initialized models, and fill in the model
and run-length distro"""
for index in indices_initialized_models:
model = self.model_universe[index]
"""get indices relative to all run lengths"""
model_indices_indicators_relative_to_all_run_lengths = np.in1d(
all_run_lengths, model.retained_run_lengths)
"""If the current model has retained run length r>t-1, set it
to t."""
if (model.retained_run_lengths[-1] == model.retained_run_lengths[-2]):
model_indices_indicators_relative_to_all_run_lengths[
-1] = True
"""get P(r_t,m_t|y_1:t) = P(r_t,m_t,y_1:t)/P(y_1:t)"""
model_rl_log_distributions[index,
model_indices_indicators_relative_to_all_run_lengths] = (
model.joint_log_probabilities - self.log_evidence )
#+ np.log(priors_initialized_models[m]))
"""STEP 1.4: we need to sum over the columns (i.e. the models).
One needs log sum exp for this, since all is stored in log form.
P(r_t|y_1:t) = \sum_m P(r_t,m_t|y_1:t)"""
run_length_log_distr = misc.logsumexp(
model_rl_log_distributions, axis=0)
"""STEP 2: Store to object, and if all run lengths are to be stored,
also store it to another object"""
self.model_and_run_length_log_distr = model_rl_log_distributions
self.run_length_log_distr = run_length_log_distr
self.all_retained_run_lengths = all_run_lengths
"""STEP 3: Store it if needed"""
if self.store_mrl or self.store_rl:
self.storage_all_retained_run_lengths.append(
self.all_retained_run_lengths)
if self.store_rl:
self.storage_run_length_log_distr.append(self.run_length_log_distr)
if self.store_mrl:
self.storage_model_and_run_length_log_distr.append(
self.model_and_run_length_log_distr)
#IMPLEMENTED FOR ALL SUBCLASSES IF predictive_probabilities WORK IN SUBLCASS
# update_joint_probabilities WORK
def update_all_joint_log_probabilities(self, y, t):
"""Let the individual objects in *model_universe* compute their growth
and CP probabilities, via 'update_joint_probabilities' in each.
The strucutre is: (1) update the joint log probs (or initialize the
model if first observation), which is done by calling probability model
functions, and (2) update the predictive probabilities using the
new observation y, which is done differently in each model object.
"""
"""STEP 0: Get which of the models are or will be
initialized at t for redistributing the model prior later. """
index_initialized = []
for (m,model) in zip(range(0,self.Q),self.model_universe):
if model.has_lags and ((t+1) - model.lag_length >= 1):
index_initialized.append(m)
elif not model.has_lags:
index_initialized.append(m)
prior_rescaling_factor = np.sum(self.model_prior[index_initialized])
#if not self.first_model_initialized:
#we need the initial run-length distro
"""If we need to do hyperparameter learning for the generalized
Bayesian case (e.g., learning alpha for Power divergence)"""
"""Initialize these quantities. If we enter the next if-statement, they
might be changed"""
log_model_posteriors_der_m = None
log_model_posteriors_der_sign_m = None
log_CP_evidence_der = None
log_CP_evidence_der_sign = None
if (self.generalized_bayes_rld == "power_divergence"
and self.alpha_rld_learning
and t>1):
#DEBUG: Need to be computed from all models
"""Compute the model posterior derivative w.r.t. alpha
(in log form)"""
"""Check if at least one model is already initialized"""
at_least_one_model_initialized = np.any([(model.has_lags and
((t) - model.lag_length)>1) or ( not model.has_lags )
for model in self.model_universe])
if at_least_one_model_initialized:
"""collect all derivatives of all models as well as the
joint probabilities of all models. Sum over models per run-
length afterwards"""
all_log_probs = -np.inf*np.ones(
(self.Q, np.size(self.all_retained_run_lengths)))
all_log_alpha_derivatives = -np.inf*np.ones(
(self.Q, np.size(self.all_retained_run_lengths)))
all_log_alpha_derivatives_sign = np.zeros(
(self.Q, np.size(self.all_retained_run_lengths)))
for m, model in zip(range(0,self.Q), self.model_universe):
#DEBUG: Unclear if the log derivatives joint log probs
# are going to be one entry too many (for r=0)
#DEBUG: Indexing!
"""Only retrieve quantities of models that have seen data
already"""
warmed_up = ((model.has_lags and ((t) - model.lag_length)>1) or
( not model.has_lags ))
if warmed_up:
"""get indices relative to all run lengths"""
model_indices_indicators_relative_to_all_run_lengths=(
np.in1d(self.all_retained_run_lengths,
model.retained_run_lengths))
if (model.retained_run_lengths[-1] ==
model.retained_run_lengths[-2]):
model_indices_indicators_relative_to_all_run_lengths[-1] = True
# print('rl', np.size(model_indices_indicators_relative_to_all_run_lengths))
# print(model_indices_indicators_relative_to_all_run_lengths)
# print(self.all_retained_run_lengths)
# print('jlp', np.size(model.joint_log_probabilities))
# print('alp', np.size(all_log_probs[m,:]))
#DEBUG: The initial log_alpha_derivative_joint_probs
# has to be in the right size relative to lag l.
#DEBUG: Initialized to None, so initialize it when you
# arrive here the first time by checking if = None
"""Check if they have been initialized already. If not,
we need to do that now"""
if (model.log_alpha_derivatives_joint_probabilities
is None):
num_needed = np.sum(
model_indices_indicators_relative_to_all_run_lengths)
model.log_alpha_derivatives_joint_probabilities = (
-np.inf * np.ones(num_needed))
model.log_alpha_derivatives_joint_probabilities_sign = (
np.ones(num_needed))
"""fill retrieved values into relevant position"""
all_log_alpha_derivatives[m,
model_indices_indicators_relative_to_all_run_lengths]=(
model.log_alpha_derivatives_joint_probabilities )
all_log_alpha_derivatives_sign[m,
model_indices_indicators_relative_to_all_run_lengths]=(
model.log_alpha_derivatives_joint_probabilities_sign)
#DEBUG: it seems that we don't have enough retained
# indices in the relative ones
all_log_probs[m,
model_indices_indicators_relative_to_all_run_lengths]=(
model.joint_log_probabilities)
"""sum over the models for each run-length, needed for the
derivative of P(m_t|m_t-1, r_t-1, y_1:t-1), see (4) in
handwritten notes. Dimension is Rx1"""
model_sums_derivatives, model_sums_derivatives_sign = (
scipy.misc.logsumexp(
a = all_log_alpha_derivatives,
b = all_log_alpha_derivatives_sign,
return_sign = True,
axis=0
))
model_sums = scipy.misc.logsumexp(
a = all_log_probs,
axis = 0
)
"""Get the two expressions that added together give you the
derivative of the joint probabilities in log-form"""
#Debug: In expr_1, we have MxR - M, make sure dimensions
# match. expr_2 has dimension R
#DEBUG: check expr_2 and fix the dimension
expr_1 = all_log_alpha_derivatives - model_sums
sign_1 = all_log_alpha_derivatives_sign
expr_2 = -2* model_sums + model_sums_derivatives + all_log_probs
sign_2 = (-1) * model_sums_derivatives_sign
#print("expr_1", expr_1)
#print("expr_2", expr_2)
# print("sign_1", sign_1.shape)
# print("sign_2", sign_2.shape)
expr, sign = scipy.misc.logsumexp(
a = np.array([expr_1, expr_2]),
b = np.array([sign_1, sign_2 *
np.ones(self.Q)[:,np.newaxis]]),
return_sign = True,
axis=0
)
#Note: We only have the growth-probabilities in here!
# the CP probability derivatives are computed below!
log_model_posteriors_der = expr
log_model_posteriors_der_sign = sign
"""Compute the CP evidence derivative w.r.t. alpha
(in log form). It turns out that the computation decomposes
s.t. we have
derivative(one-step-pred) * CP_evidence * q(m_t) +
one-step-pred * derivative(CP_evidence) * q(m_t).
Since we don't want to deal with the one-step-ahead
predictives here, all we need to do is compute
derivative(CP_evidence) and pass it on. The full
computation is then done when we update the probs."""
#DEBUG: Where does the evidence come from?
#DEBUG: Unclear what we compute here and inside probability_model!
_1, _2 = misc.logsumexp(
a = np.log(self.cp_model.hazard_vector(1, t)) +
all_log_alpha_derivatives, # +
#self.log_evidence,
b = all_log_alpha_derivatives_sign,
return_sign = True)
log_CP_evidence_der = _1
log_CP_evidence_der_sign = _2
# else:
# log_model_posteriors_der_m = None
# log_model_posteriors_der_sign_m = None
# log_CP_evidence_der = None
# log_CP_evidence_der_sign = None
#q = 0
for (m,model) in zip(range(0,self.Q),self.model_universe):
"""STEP 1: Check if it is the first observation, and initialize the
joint distributions in each model object if so"""
#DEBUG: t is t-1!
initialization_required = False
if model.has_lags and ((t) - model.lag_length == 1):
initialization_required = True
elif (not model.has_lags) and t == 1:
initialization_required = True
if initialization_required:
"""This command gives an initialization of (i) the
*joint_probabilities*, (ii) the predictive distributions (i.e.,
the sufficient statistics), and (iii) the *model_evidence*
of each model."""
"""NOTE: We need to initialize BVAR at time t-lag_length!"""
if model.has_lags or isinstance(model, BVARNIG):
"""If we have a BVAR model, we need to pass data of
sufficient lag length to the initialization."""
#DEBUG: exo_selection in correct dimension? What is dim of
# exo_data?
#DEBUG: exo data assumed to be contemporaneous!
"""STEP I: Get endogeneous data"""
X_endo = self.data[:model.lag_length+1,:]
Y_2 = self.data[model.lag_length+1,:]
"""STEP II: Get exogeneous data (if needed)"""
if model.exo_bool:
X_exo = self.exo_data[model.lag_length,
model.exo_selection,:]
X_exo_2 = self.exo_data[model.lag_length+1,
model.exo_selection,:]
else:
X_exo = X_exo_2 = None
"""STEP III: Use exo and endo data to initialize model"""
#new_prior = self.model_prior[m]/np.sum(self.)
model.initialization(X_endo, X_exo, Y_2, X_exo_2,
self.cp_model,
self.model_prior[m]/prior_rescaling_factor)
else:
"""Otherwise, just pass the first observation"""
#DEBUG: CONSTANT FITTING ADAPTION
# if isinstance(model, BVARNIG):
# """STEP I: Get endogeneous data"""
# X_endo = self.data[:model.lag_length+1,:]
# Y_2 = self.data[model.lag_length+1,:]
# """STEP II: Get exogeneous data (if needed)"""
# if model.exo_bool:
# X_exo = self.exo_data[model.lag_length,
# model.exo_selection,:]
# X_exo_2 = self.exo_data[model.lag_length+1,
# model.exo_selection,:]
# else:
# X_exo = X_exo_2 = None
# model.initialization(None, X_exo, Y_2, X_exo_2,
# self.cp_model,
# self.model_prior[m]/prior_rescaling_factor)
#else:
model.initialization(y, self.cp_model,
self.model_prior[m])
else:
"""Make sure that we only modify joint_log_probs & predictive
distributions for BVAR models for which t is large enough to
cover the lag length."""
#DEBUG: Use x_exo if BVAR
"""STEP 1: Within each ProbabilityModel object, compute its
joint probabilities, i.e. the growth- & CP-probabilities
associated with the model"""
#"""get P(r_t,m_t|y_1:t) = P(r_t,m_t,y_1:t)/P(y_1:t)"""
#model_rl_log_distributions[index,
# model_indices_indicators_relative_to_all_run_lengths] = (
# model.joint_log_probabilities -self.log_evidence )
# #+ np.log(priors_initialized_models[m]))