Repository navigation
Expand file tree
/
Copy pathalgorithms.py
More file actions
1697 lines (1360 loc) · 55 KB
/
Copy pathalgorithms.py
File metadata and controls
1697 lines (1360 loc) · 55 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
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
'''
Implements different algorithms for Approximate Bayesian
Computation.
@author Steven
'''
import sys
import numpy as np
import scipy.spatial as sp
from numpy import linalg
from abc import ABCMeta, abstractmethod
import matplotlib.pyplot as plt
import kernels
import kernel_methods as km
import distributions as distr
import data_manipulation as dm
from utils import logsumexp, conditional_error, \
get_bootstrap, get_weighted_bootstrap, get_bootstrap_ids, \
lowessNd
from problems import ABC_Problem
__all__ = ['Base_ABC',
'Base_MCMC_ABC',
'Reject_ABC',
'Marginal_ABC',
'Pseudo_Marginal_ABC',
'Base_SL_ABC',
'SL_ABC',
'KL_ABC',
'ASL_ABC',
'AKL_ABC',
'PKS_ABC',
'PSS_ABC']
class Base_ABC(object):
'''
Abstract base class for ABC algorithms.
'''
__metaclass__ = ABCMeta
def __init__(self, problem, verbose=False, save=True, data_dir=True,
**kwargs):
self.problem = problem
self.y_star = problem.y_star
self.y_dim = problem.y_dim
self.simulator = problem.simulator
self.prior = problem.prior
self.prior_args = problem.prior_args
self.statistics = problem.statistics
self.verbose = verbose
self.save = save
self.needed_params = []
self.current_sim_calls = 0
self.samples = []
self.stats = []
self.sim_calls = []
self.just_reset = False
self.data_dir = data_dir
def __repr__(self):
# This is used to create a data file for the results
s = type(self.problem).__name__ + '_' + type(self).__name__
for par in self.needed_params:
s += '_' + str(self.__dict__[par])
return s
def reset(self):
'''
Resets the internal lists. So that an new run from scratch can begin.
'''
self.current_sim_calls = 0
self.samples = []
self.stats = []
self.sim_calls = []
self.just_reset = True
def get_parameters(self):
'''
Returns the list of parameter values. Order is determined by
`self.needed_params`.
'''
return [self.__dict__[par] for par in self.needed_params]
def save_results(self):
'''
Saves the results of this algorithm.
Note: Should be called after a call to `run()`
'''
dm.save(self, data_dir=self.data_dir)
def verbosity(self, i, interval=10):
if self.verbose and i % interval == 0:
sys.stdout.write('\r%s iteration %d %d' %
(type(self).__name__, i, sum(self.sim_calls)))
sys.stdout.flush()
@abstractmethod
def run(self, num_samples, reset=True):
return NotImplemented
class Reject_ABC(Base_ABC):
'''
A simple rejection sampler.
'''
def __init__(self, problem, epsilon, **kwargs):
'''
Creates an instance of rejection ABC for the given problem.
Parameters
----------
problem : ABC_Problem instance
The problem to solve An instance of the ABC_Problem class.
epsilon : float
The error margin or epsilon-tube.
verbose : bool
If set to true iteration number as well as number of
simulation calls will be printed.
save : bool
If True will save the result to a (possibly exisisting)
database
'''
super(Reject_ABC, self).__init__(problem, **kwargs)
self.needed_params = ['epsilon']
self.epsilon = epsilon
def run(self, num_samples, reset=True):
'''
Runs the algorithm.
Parameters
----------
num_samples : int
number of samples to get
reset : bool
Whether the internal lists should be reset.
If false it continues where it stopped.
Default True.
'''
# Reset previous values
if reset:
self.reset()
for i in xrange(num_samples):
self.verbosity(i)
self.current_sim_calls = 0
error = self.epsilon + 1.0
while error > self.epsilon:
# Sample theta from the prior
theta = self.prior.rvs(*self.prior_args)
# Perform simulation
y = self.statistics(self.simulator(theta))
self.current_sim_calls += 1
# Calculate error
# TODO: Implement more comparison methods
error = linalg.norm(self.y_star - y)
if self.current_sim_calls % 1000 == 0:
print self.current_sim_calls, 'sim_calls done'
# Accept the sample
self.samples.append(theta)
self.stats.append(y)
self.sim_calls.append(self.current_sim_calls)
# Print a newline
if self.verbose:
print ''
if self.save:
self.save_results()
class Base_MCMC_ABC(Base_ABC):
'''
Abstract base class for MCMC ABC algorithms.
'''
__metaclass__ = ABCMeta
def __init__(self, problem, verbose=False, save=True, data_dir=True, **kwargs):
super(Base_MCMC_ABC, self).__init__(
problem, verbose, save, data_dir)
assert isinstance(problem, ABC_Problem), \
'Problem is not an instance of ABC_Problem'
self.proposal = problem.proposal
self.proposal_args = problem.proposal_args
self.use_log = problem.use_log
self.theta_init = problem.get_theta_init()
self.accepted = []
self.theta = self.theta_init
if self.use_log:
self.log_theta = np.log(self.theta)
self.just_reset = True
@abstractmethod
def mh_step(self):
'''
The Metropolis-Hastings step of the Markov Chain.
In this function the acceptance probability will be calculated and
the sample will be either rejected or accepted.
Returns
-------
sample_accepted : bool
Whether the sample was accepted
'''
return NotImplemented
def reset(self):
super(Base_MCMC_ABC, self).reset()
self.accepted = []
self.theta = self.problem.get_theta_init()
if self.use_log:
self.log_theta = np.log(self.theta)
def run(self, num_samples, reset=True):
'''
Runs the algorithm.
Parameters
----------
num_samples : int
number of samples to get
reset : bool
Whether the internal lists should be reset.
If false it continues where it stopped.
Default True.
'''
# Reset previous values if needed
if reset and not self.just_reset:
self.reset()
self.just_reset = False
for i in xrange(num_samples):
# Print information if needed
self.verbosity(i)
# Sample theta_p from proposal
if self.use_log:
self.theta_p = self.proposal.rvs(
self.log_theta, *self.proposal_args)
self.log_theta_p = np.log(self.theta_p)
else:
self.theta_p = self.proposal.rvs(
self.theta, *self.proposal_args)
# Calculate stationary parts of the acceptance probability
self.prior_logprob_p = self.prior.logpdf(
self.theta_p, *self.prior_args)
self.prior_logprob = self.prior.logpdf(
self.theta, *self.prior_args)
if self.use_log:
self.proposal_logprob = self.proposal.logpdf(
self.theta, self.log_theta_p, *self.proposal_args)
self.proposal_logprob_p = self.proposal.logpdf(
self.theta_p, self.log_theta, *self.proposal_args)
else:
self.proposal_logprob = self.proposal.logpdf(
self.theta, self.theta_p, *self.proposal_args)
self.proposal_logprob_p = self.proposal.logpdf(
self.theta_p, self.theta, *self.proposal_args)
# Perform the Metropolis-Hastings step
sample_accepted = self.mh_step()
if sample_accepted:
self.theta = self.theta_p
if self.use_log:
self.log_theta = self.log_theta_p
self.accepted.append(sample_accepted)
self.sim_calls.append(self.current_sim_calls)
self.samples.append(self.theta)
# Reset the number of simulation calls for the next iteration
self.current_sim_calls = 0
# Print a blank line if needed
if self.verbose:
print ''
# Store the results if necessary
if self.save:
self.save_results()
class Marginal_ABC(Base_MCMC_ABC):
'''
Marginal ABC
------------
Approximates the likelihood by a Monte Carlo estimate of the integral.
The marginal sampler re-estimates both the denominator as well as the
numerator each iteration, which in practice leads to better mixing.
'''
def __init__(self, problem, **params):
'''
Creates an instance of the marginal ABC algorithm described by Meeds
and Welling [1]_.
Parameters
----------
problem : An instance of (a subclass of) `ABC_Problem`.
The problem to solve.
epsilon : float
Error margin.
S : int
Number of simulations per iteration.
Optional Arguments
------------------
verbose : bool
The verbosity of the algorithm. If `True`, will print iteration
numbers and number of simulation calls. Default `False`.
save : bool
If `True`, results will be stored in a possibly existing database.
Default `True`.
References
----------
.. [1] GPS-ABC: Gaussian Process Surrogate Approximate Bayesian
Computation. E. Meeds and M. Welling.
http://arxiv.org/abs/1401.2838
'''
super(Marginal_ABC, self).__init__(problem, **params)
self.needed_params = ['epsilon', 'S']
assert set(self.needed_params).issubset(params.keys()), \
'Not enough parameters: Need {0}'.format(str(self.needed_params))
self.S = params['S']
self.epsilon = params['epsilon']
def mh_step(self):
diff = []
diff_p = []
# Get S samples and approximate marginal likelihood
for s in xrange(self.S):
new_x = self.statistics(self.simulator(self.theta))
new_x_p = self.statistics(self.simulator(self.theta_p))
self.current_sim_calls += 2
# Compute the P(y | x, theta) for these samples
u = linalg.norm(new_x - self.y_star) / self.epsilon
u_p = linalg.norm(new_x_p - self.y_star) / self.epsilon
diff.append(kernels.log_gaussian(u / self.epsilon))
diff_p.append(kernels.log_gaussian(u_p / self.epsilon))
diff_term = logsumexp(np.array(diff_p)) - logsumexp(np.array(diff))
# Calculate acceptance according to eq. 4
numer = self.prior_logprob_p + self.proposal_logprob
denom = self.prior_logprob + self.proposal_logprob_p
log_alpha = min(0.0, (numer - denom) + diff_term)
# Accept proposal with probability alpha
return distr.uniform.rvs(0, 1) <= np.exp(log_alpha)
class Pseudo_Marginal_ABC(Base_MCMC_ABC):
'''
Pseudo Marginal ABC
-------------------
Approximates the likelihood by a Monte Carlo estimate of the integral.
The pseudo marginal sampler only re-estimates the numerator each iteration.
The denominator is carried over from the previous iteration. This is in
practice slower in mixing, but achieves lower bias.
'''
def __init__(self, problem, **params):
'''
Creates an instance of the pseudo-marginal ABC algorithm described by
Meeds and Welling [1]_.
Parameters
----------
problem : An instance of (a subclass of) `ABC_Problem`.
The problem to solve.
epsilon : float
Error margin.
S : int
Number of simulations per iteration.
Optional Arguments
------------------
verbose : bool
The verbosity of the algorithm. If `True`, will print iteration
numbers and number of simulation calls. Default `False`.
save : bool
If `True`, results will be stored in a possibly existing database.
Default `True`.
References
----------
.. [1] GPS-ABC: Gaussian Process Surrogate Approximate Bayesian
Computation. E. Meeds and M. Welling.
http://arxiv.org/abs/1401.2838
'''
super(Pseudo_Marginal_ABC, self).__init__(problem, **params)
self.needed_params = ['epsilon', 'S']
assert set(self.needed_params).issubset(params.keys()), \
'Not enough parameters: Need {0}'.format(str(self.needed_params))
self.S = params['S']
self.epsilon = params['epsilon']
prev_diff = []
for s in xrange(self.S):
new_x = self.statistics(self.simulator(self.theta))
# Compute the P(y | x, theta) for these samples
u = linalg.norm(new_x - self.y_star) / self.epsilon
prev_diff.append(kernels.log_gaussian(u / self.epsilon))
self.prev_diff_term = logsumexp(np.array(prev_diff))
self.cur_sim_calls = self.S
def mh_step(self):
diff_p = []
# Get S samples and approximate marginal likelihood
for s in xrange(self.S):
new_x_p = self.statistics(self.simulator(self.theta_p))
# Compute the P(y | x, theta) for these samples
u_p = linalg.norm(new_x_p - self.y_star) / self.epsilon
diff_p.append(kernels.log_gaussian(u_p / self.epsilon))
self.cur_sim_calls += self.S
# Calculate acceptance according to eq. 4
numer = self.prior_logprob_p + self.proposal_logprob
denom = self.prior_logprob + self.proposal_logprob_p
cur_diff_term = logsumexp(np.array(diff_p))
diff_term = cur_diff_term - self.prev_diff_term
log_alpha = min(0.0, (numer - denom) + diff_term)
# Accept proposal with probability alpha
accept = distr.uniform.rvs(0, 1) <= np.exp(log_alpha)
if accept:
self.prev_diff_term = cur_diff_term
return accept
class Base_SL_ABC(Base_MCMC_ABC):
'''
Abstract Base class for Synthetic Likelihood ABC.
'''
__metaclass__ = ABCMeta
def __init__(self, problem, **params):
super(Base_SL_ABC, self).__init__(problem, **params)
self.needed_params = ['S']
assert set(self.needed_params).issubset(params.keys()), \
'Not enough parameters: Need {0}'.format(str(self.needed_params))
self.S = params['S']
def mh_step(self):
numer = self.prior_logprob_p + self.proposal_logprob
denom = self.prior_logprob + self.proposal_logprob_p
# Early exit
if np.isneginf(numer):
return False
# Get S samples from simulator
# TODO: Make marginal/pseudo marginal choosable
self.x = np.array([self.statistics(self.simulator(self.theta))
for s in xrange(self.S)], ndmin=2)
self.x_p = np.array([self.statistics(self.simulator(self.theta_p))
for s in xrange(self.S)], ndmin=2)
self.current_sim_calls = 2 * self.S
other_term = self.get_SL_estimate()
log_alpha = min(0.0, (numer - denom) + other_term)
return distr.uniform.rvs(0.0, 1.0) <= np.exp(log_alpha)
@abstractmethod
def get_SL_estimate(self):
'''
Returns an estimate of p(y_star | theta_p) / p(y_star | theta)
in log space.
'''
return NotImplemented
class SL_ABC(Base_SL_ABC):
'''
Synthetic Likelihood ABC
------------------------
Approximates the likelihood with a normal distribution, by estimating
the first and second order statistics from samples from the simulator.
'''
def __init__(self, problem, **params):
'''
Creates an instance of the Synthetic Likelihood ABC algorithm described
by Meeds and Welling [1]_.
Parameters
----------
problem : An instance of (a subclass of) `ABC_Problem`.
The problem to solve.
S : int
Number of simulations per iteration
epsilon : float
Error margin.
Optional Arguments
------------------
verbose : bool
The verbosity of the algorithm. If `True`, will print iteration
numbers and number of simulations. Default `False`.
save : bool
If `True`, results will be stored in a possibly existing database
Default `True`.
Note that while S and epsilon are keyword-arguments, they are necessary
References
----------
.. [1] GPS-ABC: Gaussian Process Surrogate Approximate Bayesian
Computation. E. Meeds and M. Welling.
http://arxiv.org/abs/1401.2838
'''
super(SL_ABC, self).__init__(problem, **params)
self.epsilon = 0.0
if 'epsilon' in params.keys():
self.epsilon = params['epsilon']
if 'diag' in params.keys():
self.diag = params['diag']
self.eps_eye = np.identity(self.y_dim) * self.epsilon ** 2
def __repr__(self):
name = super(SL_ABC, self).__repr__() + '_' + str(self.epsilon)
if self.diag:
return name + '_diag'
return name
def get_SL_estimate(self):
# Set mu's according to eq. 5
mu_theta = np.mean(self.x, 0)
mu_theta_p = np.mean(self.x_p, 0)
# Set sigma's according to eq. 6
x_m = self.x - mu_theta
x_m_p = self.x_p - mu_theta_p
sigma_theta = np.dot(x_m.T, x_m) / float(self.S - 1)
sigma_theta_p = np.dot(x_m_p.T, x_m_p) / float(self.S - 1)
if self.diag:
sigma_theta = np.diag(np.diag(sigma_theta))
sigma_theta_p = np.diag(np.diag(sigma_theta_p))
other_term = \
distr.multivariate_normal.logpdf(
self.y_star,
mu_theta_p,
sigma_theta_p + self.eps_eye) - \
distr.multivariate_normal.logpdf(
self.y_star,
mu_theta,
sigma_theta + self.eps_eye)
return other_term
class KL_ABC(Base_SL_ABC):
'''
KDE Likelihood ABC
------------------------
Approximates the likelihood with a kernel density approximation, by
estimating the first and second order statistics from samples from the
simulator.
'''
def __init__(self, problem, **params):
'''
Creates an instance of the Kernel Synthetic Likelihood ABC algorithm.
Parameters
----------
problem : An instance of (a subclass of) `ABC_Problem`.
The problem to solve.
S : int
Number of simulations per iteration
Optional Arguments
------------------
kernel : kernel function
The kernel to use in the x-direction.
Default Gaussian.
bandwidth : float or string
The bandwidth estimation method to use. If `h` is a `float`, it
will be used as the bandwidth.
Supported methods are:
- 'SJ': Sheather-Jones plug-in estimate
- 'Silverman': Silvermans rule of thumb
- 'Scott': Scotts rule of thumb
Default 'Silverman'.
verbose : bool
The verbosity of the algorithm. If `True`, will print iteration
numbers and number of simulations. Default `False`.
save : bool
If `True`, results will be stored in a possibly existing database
Default `True`.
Note that while S is a keyword-argument, they are necessary
'''
super(KL_ABC, self).__init__(problem, **params)
self.needed_params = ['S']
assert set(self.needed_params).issubset(params.keys()), \
'Not enough parameters: Need {0}'.format(str(self.needed_params))
self.S = params['S']
if 'kernel' in params.keys():
self.kernel = params['kernel']
else:
self.kernel = kernels.gaussian
if 'bandwidth' in params.keys():
self.bandwidth = params['bandwidth']
else:
self.bandwidth = 'Silverman'
if 'adaptive' in params.keys():
self.adaptive = params['adaptive']
else:
self.adaptive = False
if 'nonradial' in params.keys():
self.nonradial = params['nonradial']
else:
self.nonradial = False
def __repr__(self):
name = super(KL_ABC, self).__repr__() + '_' + self.kernel.__name__
if self.bandwidth != 'Silverman':
name += '_bw_' + str(self.bandwidth)
if self.nonradial:
name += '_nonradial'
return name
def get_SL_estimate(self):
if self.adaptive:
pass
else:
other_term = 0.0
for j in range(self.y_dim):
other_term += \
km.kernel_density_estimate(
self.y_star[j], self.x_p[:, [j]],
self.kernel, self.bandwidth, nonradial=self.nonradial) - \
km.kernel_density_estimate(
self.y_star[j], self.x[:, [j]],
self.kernel, self.bandwidth, nonradial=self.nonradial)
return other_term
class ASL_ABC(Base_MCMC_ABC):
'''
Adaptive Synthetic Likelihood ABC
------------------------
Approximates the likelihood with a normal distribution, by estimating
the first and second order statistics from samples from the simulator.
However the error on making a mistake with the acceptance probability
(due to approximation with a finite number of samples) is used to
determine whether more samples are needed. Hence the number of samples
that is drawn each iteration is adaptive to the acceptance error.
'''
def __init__(self, problem, **params):
'''
Creates an instance of the Adaptive Synthetic Likelihood ABC algorithm
described by Meeds and Welling [1]_.
Parameters
----------
problem : An instance of (a subclass of) `ABC_Problem`.
The problem to solve.
epsilon : float
Epsilon for the error tube
ksi : float
Error margin
S0 : int
Number of initial simulations per iteration
delta_S : int
Number of additional simulations
Note that while epsilon, ksi, S0 and delta_S are keyword-arguments,
they are necessary.
Optional Arguments
------------------
verbose : bool
The verbosity of the algorithm. If `True`, will print iteration
numbers and number of simulations. Default `False`.
save : bool
If `True`, results will be stored in a possibly existing database
Default `True`.
M : int
Number of samples to approximate mu_hat. Default 50.
E : int
Number of points to approximate conditional error. Default 50.
References
----------
.. [1] GPS-ABC: Gaussian Process Surrogate Approximate Bayesian
Computation. E. Meeds and M. Welling.
http://arxiv.org/abs/1401.2838
'''
super(ASL_ABC, self).__init__(problem, **params)
self.needed_params = ['epsilon', 'ksi', 'S0', 'delta_S']
assert set(self.needed_params).issubset(params.keys()), \
'Not enough parameters: Need {0}'.format(str(self.needed_params))
self.S0 = params['S0']
self.epsilon = params['epsilon']
self.ksi = params['ksi']
self.delta_S = params['delta_S']
if 'M' in params.keys():
self.M = params['M']
else:
self.M = 50
if 'E' in params.keys():
self.E = params['E']
else:
self.E = 50
self.eye_eps = np.identity(self.y_dim) * self.epsilon ** 2
def mh_step(self):
# Reset the samples
x = []
x_p = []
additional = self.S0
while True:
# Get additional samples from simulator
x.extend([self.statistics(self.simulator(self.theta))
for s in xrange(additional)])
x_p.extend([self.statistics(self.simulator(self.theta_p))
for s in xrange(additional)])
additional = self.delta_S
S = len(x)
# Convert to arrays
ax = np.array(x)
ax_p = np.array(x_p)
# Set mu's according to eq. 5
mu_hat_theta = np.array(np.mean(ax, 0), ndmin=1)
mu_hat_theta_p = np.array(np.mean(ax_p, 0), ndmin=1)
# Set sigma's according to eq. 6
x_m = ax - mu_hat_theta
x_m_p = ax_p - mu_hat_theta_p
sigma_theta = \
np.array(np.dot(x_m.T, x_m) / float(S - 1), ndmin=2)
sigma_theta_p = \
np.array(np.dot(x_m_p.T, x_m_p) / float(S - 1), ndmin=2)
sigma_theta_S = sigma_theta / float(S)
sigma_theta_p_S = sigma_theta_p / float(S)
alphas = np.zeros(self.M)
for m in range(self.M):
# Sample mu_theta_p and mu_theta using eq. 11
mu_theta = distr.multivariate_normal.rvs(mu_hat_theta,
sigma_theta_S)
mu_theta_p = distr.multivariate_normal.rvs(mu_hat_theta_p,
sigma_theta_p_S)
# Compute alpha using eq. 12
numer = self.prior_logprob_p + self.proposal_logprob + \
distr.multivariate_normal.logpdf(
self.y_star,
mu_theta_p,
sigma_theta_p + self.eye_eps)
denom = self.prior_logprob + self.proposal_logprob_p + \
distr.multivariate_normal.logpdf(
self.y_star,
mu_theta,
sigma_theta + self.eye_eps)
log_alpha = min(0.0, numer - denom)
alphas[m] = np.exp(log_alpha)
tau = np.median(alphas)
# Set unconditional error, using Monte Carlo estimate
error = np.mean([e * conditional_error(alphas, e, tau, self.M)
for e in np.linspace(0, 1, self.E)])
if error < self.ksi:
break
self.current_sim_calls = 2 * S
return distr.uniform.rvs() <= tau
class AKL_ABC(Base_MCMC_ABC):
'''
Adaptive Kernel Synthetic Likelihood ABC
----------------------------------------
Approximates the likelihood with a kernel density estimate.
However the error on making a mistake with the acceptance probability
(due to approximation with a finite number of samples) is used to
determine whether more samples are needed. Hence the number of samples
that is drawn each iteration is adaptive to the acceptance error.
The error is estimated using bootstrapping.
'''
def __init__(self, problem, **params):
'''
Creates an instance of the Adaptive KDE Likelihood ABC algorithm.
Parameters
----------
problem : An instance of (a subclass of) `ABC_Problem`.
The problem to solve.
ksi : float
Error margin
S0 : int
Number of initial simulations per iteration
delta_S : int
Number of additional simulations
Note that while epsilon, ksi, S0 and delta_S are keyword-arguments,
they are necessary.
Optional Arguments
------------------
verbose : bool
The verbosity of the algorithm. If `True`, will print iteration
numbers and number of simulations. Default `False`.
save : bool
If `True`, results will be stored in a possibly existing database
Default `True`.
M : int
Number of bootstrap repetitions. Default 100.
E : int
Number of points to approximate conditional error. Default 50.
'''
super(AKL_ABC, self).__init__(problem, **params)
self.needed_params = ['ksi', 'S0', 'delta_S']
assert set(self.needed_params).issubset(params.keys()), \
'Not enough parameters: Need {0}'.format(str(self.needed_params))
self.S0 = params['S0']
self.ksi = params['ksi']
self.delta_S = params['delta_S']
if 'M' in params.keys():
self.M = params['M']
else:
self.M = 50
if 'E' in params.keys():
self.E = params['E']
else:
self.E = 50
if 'kernel' in params.keys():
self.kernel = params['kernel']
else:
self.kernel = kernels.gaussian
if 'bandwidth' in params.keys():
self.bandwidth = params['bandwidth']
else:
self.bandwidth = 'Silverman'
def __repr__(self):
return super(AKL_ABC, self).__repr__() + '_' + self.kernel.__name__
def mh_step(self):
# Reset the samples
x = []
x_p = []
additional = self.S0
numer = self.prior_logprob_p + self.proposal_logprob
denom = self.prior_logprob + self.proposal_logprob_p
if np.isneginf(numer):
return False
while True:
# Get additional samples from simulator
x.extend([self.statistics(self.simulator(self.theta))
for s in xrange(additional)])
x_p.extend([self.statistics(self.simulator(self.theta_p))
for s in xrange(additional)])
additional = self.delta_S
S = len(x)
alphas = np.zeros(self.M)
for m in xrange(self.M):
# Get a bootstrap sample
new_x = get_bootstrap(x)
new_x_p = get_bootstrap(x_p)
# Compute alpha using eq. 12
other_term = 0.0
for j in range(self.y_dim):
other_term += \
km.kernel_density_estimate(
self.y_star[j], new_x_p[:, [j]],
self.kernel, self.bandwidth) - \
km.kernel_density_estimate(
self.y_star[j], new_x[:, [j]],
self.kernel, self.bandwidth)
log_alpha = min(0.0, (numer - denom) + other_term)
alphas[m] = np.exp(log_alpha)