/
gibbs_sampler_continuous_fullcollapsed_randomfactorialnetwork.py
1914 lines (1334 loc) · 78 KB
/
gibbs_sampler_continuous_fullcollapsed_randomfactorialnetwork.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
#!/usr/bin/env python
# encoding: utf-8
"""
sampler.py
Created by Loic Matthey on 2011-06-1.
Copyright (c) 2011 Gatsby Unit. All rights reserved.
"""
import numpy as np
# import scipy.special as scsp
# from scipy.stats import vonmises as vm
import scipy.stats as spst
import scipy.optimize as spopt
import scipy.integrate as spintg
import scipy.interpolate as spinter
import scipy.io as sio
import matplotlib.patches as plt_patches
# import matplotlib.collections as plt_collections
import matplotlib.pyplot as plt
import sys
from utils import *
import em_circularmixture
import em_circularmixture_allitems_uniquekappa
import slicesampler
# from dataio import *
import progress
def loglike_theta_fct_single(new_theta, (thetas, datapoint, rn, theta_mu, theta_kappa, ATtcB, sampled_feature_index, mean_fixed_contrib, inv_covariance_fixed_contrib)):
'''
Compute the loglikelihood of: theta_r | n_tc theta_r' tc
'''
# Put the new proposed point correctly
thetas[sampled_feature_index] = new_theta
like_mean = datapoint - mean_fixed_contrib - \
ATtcB*rn.get_network_response(thetas)
# Using inverse covariance as param
# return theta_kappa*np.cos(thetas[sampled_feature_index] - theta_mu) - 0.5*np.dot(like_mean, np.dot(inv_covariance_fixed_contrib, like_mean))
return -0.5*np.dot(like_mean, np.dot(inv_covariance_fixed_contrib, like_mean))
# return -1./(2*0.2**2)*np.sum(like_mean**2.)
def loglike_theta_fct_single_min(x, thetas, datapoint, rn, theta_mu, theta_kappa, ATtcB, sampled_feature_index, mean_fixed_contrib, inv_covariance_fixed_contrib):
return -loglike_theta_fct_single(x, (thetas, datapoint, rn, theta_mu, theta_kappa, ATtcB, sampled_feature_index, mean_fixed_contrib, inv_covariance_fixed_contrib))
def like_theta_fct_single(x, thetas, datapoint, rn, theta_mu, theta_kappa, ATtcB, sampled_feature_index, mean_fixed_contrib, inv_covariance_fixed_contrib):
return np.exp(loglike_theta_fct_single(x, (thetas, datapoint, rn, theta_mu, theta_kappa, ATtcB, sampled_feature_index, mean_fixed_contrib, inv_covariance_fixed_contrib)))
class Sampler:
'''
Continuous angles Theta, with Von Mise prior.
x | Theta ~ Normal. Using the population codes directly
y_t | x_t, y_{t-1} ~ Normal
'''
def __init__(self, data_gen, tc=None, theta_prior_dict=dict(kappa=0.01, gamma=0.0), n_parameters = dict(), sigma_output=0.0, parameters_dict=None, renormalize_sigma_output=False, lapse_rate=0.0):
'''
Initialise the sampler
n_parameters: {means: T x M, covariances: T x M x M}
'''
self.theta_prior_dict = theta_prior_dict
# Initialise sampling parameters
self.init_sampling_parameters(parameters_dict)
# Initialise noise parameters
self.set_noise_parameters(n_parameters)
# Get the data
self.init_from_data_gen(data_gen, tc=tc)
# Setup output noise
self.init_output_noise(sigma_output, renormalize=renormalize_sigma_output)
# Setup lapse_rate
self.lapse_rate = lapse_rate
def set_noise_parameters(self, n_parameters):
'''
Store the noise parameters, computed from a StatisticsMeasurer
n_parameters: {means: T x M, covariances: T x M x M}
'''
self.n_means_start = n_parameters['means'][0]
self.n_means_end = n_parameters['means'][1]
self.n_covariances_start = n_parameters['covariances'][0]
self.n_covariances_end = n_parameters['covariances'][1]
self.n_means_measured = n_parameters['means'][2]
self.n_covariances_measured = n_parameters['covariances'][2]
self.noise_covariance = self.n_covariances_measured[-1]
def init_from_data_gen(self, data_gen, tc=None):
'''
'''
self.data_gen = data_gen
self.random_network = self.data_gen.random_network
self.NT = self.data_gen.Y
# Get sizes
(self.N, self.M) = self.NT.shape
self.T = self.data_gen.T
self.R = self.data_gen.random_network.R
# Time weights
self.time_weights = self.data_gen.time_weights
self.sampled_feature_index = 0
# Initialise t_c
self.init_tc(tc=tc)
# Initialise latent angles
self.init_theta()
# Precompute the parameters and cache them
self.init_cache_parameters()
def init_sampling_parameters(self, parameters_dict=None):
'''
Takes a dictionary of parameters, will extra and use some of them
'''
if parameters_dict is None:
parameters_dict = dict()
default_parameters = dict(inference_method='sample', num_samples=200, burn_samples=100, selection_method='last', selection_num_samples=1, slice_width=np.pi/16., slice_jump_prob=0.3, integrate_tc_out=False, num_sampling_passes=1, cued_feature_type='single')
# First defaults parameters
for param_name, param_value in default_parameters.iteritems():
if not hasattr(self, param_name):
# Set default only if not already set
setattr(self, param_name, param_value)
# Then new parameters
for param_name, param_value in parameters_dict.iteritems():
if param_name in default_parameters:
setattr(self, param_name, param_value)
def init_tc(self, tc=None):
'''
Initialise the time of recall
tc = N x 1
Could be sampled later, for now just fix it.
'''
if np.isscalar(tc):
self.tc = tc*np.ones(self.N, dtype='int')
else:
self.tc = np.zeros(self.N, dtype='int')
def init_theta(self):
'''
Sample initial angles. Use a Von Mises prior, low concentration (~flat)
Theta: N x R
'''
self.theta_gamma = self.theta_prior_dict['gamma']
self.theta_kappa = self.theta_prior_dict['kappa']
self.theta = np.random.vonmises(self.theta_gamma, self.theta_kappa, size=(self.N, self.R))
if self.cued_feature_type == 'single':
self.init_theta_single_cued()
elif self.cued_feature_type == 'all':
self.init_theta_all_cued()
def init_theta_single_cued(self):
'''
Only one feature is cued, all others need to be sampled
'''
print "-> init theta, feature %d cued, time %d" % (self.data_gen.cued_features[0, 0], self.data_gen.cued_features[0, 1] + 1)
# Assign the cued ones now
# stimuli_correct: N x T x R
# cued_features: N x (recall_feature, recall_time)
self.theta[np.arange(self.N), self.data_gen.cued_features[:self.N, 0]] = self.data_gen.stimuli_correct[np.arange(self.N), self.data_gen.cued_features[:self.N, 1], self.data_gen.cued_features[:self.N, 0]]
# Construct the list of uncued features, which should be sampled
self.theta_to_sample = np.array([[r for r in xrange(self.R) if r != self.data_gen.cued_features[n, 0]] for n in xrange(self.N)], dtype='int')
# Index of the actual theta we need to report
self.theta_target_index = np.zeros(self.N, dtype=int)
def init_theta_all_cued(self):
'''
All non-sampled features are cued.
'''
print "-> init theta, all cued"
# Index of the actual theta we need to report
self.theta_target_index = np.zeros(self.N, dtype=int)
# Assign the cued ones now
# stimuli_correct: N x T x R
# cued_features: N x (recall_feature, recall_time)
# r = 0 always the target to be sampled
self.theta[:, 1:] = self.data_gen.stimuli_correct[np.arange(self.N), self.data_gen.cued_features[:self.N, 1], 1:]
# Construct the list of uncued features, which should be sampled
self.theta_to_sample = self.theta_target_index[:self.N]
def init_cache_parameters(self, amplify_diag=1.0):
'''
Most of our multiplicative factors are fixed, so precompute them, for all tc.
Computes:
- ATtcB
- mean_fixed_contrib
- inv_covariance_fixed_contrib
'''
self.ATtcB = np.zeros(self.T)
self.mean_fixed_contrib = np.zeros((self.T, self.M))
self.inv_covariance_fixed_contrib = np.zeros((self.M, self.M))
# Precompute parameters
for t in xrange(self.T):
(self.ATtcB[t], self.mean_fixed_contrib[t], self.inv_covariance_fixed_contrib) = self.precompute_parameters(t, amplify_diag=amplify_diag)
# Compute the normalization
self.compute_normalization()
def init_output_noise(self, sigma_output, renormalize=True):
'''
The output noise is added after samples from the posterior are taken. Adds another level of randomness. Should count it in the BIC.
Given a level of output noise (sigma_output), stores the corresponding kappa_output.
'''
if renormalize:
max_network_activation = self.random_network.compute_maximum_activation_network()
self.sigma_output = max_network_activation*sigma_output
else:
self.sigma_output = sigma_output
self.kappa_output = stddev_to_kappa_single(sigma_output)
# Add the precomputation of the new convolved posteriors here
def precompute_parameters(self, t, amplify_diag=1.0):
'''
Precompute some matrices to speed up the sampling.
'''
# Precompute the mean and covariance contributions.
ATmtc = np.power(self.time_weights[0, t], self.T - t - 1.)
mean_fixed_contrib = self.n_means_end[t] + np.dot(ATmtc, self.n_means_start[t])
ATtcB = np.dot(ATmtc, self.time_weights[1, t])
# inv_covariance_fixed_contrib = self.n_covariances_end[t] + np.dot(ATmtc, np.dot(self.n_covariances_start[t], ATmtc)) # + np.dot(ATtcB, np.dot(self.random_network.get_network_covariance_combined(), ATtcB.T))
inv_covariance_fixed_contrib = self.n_covariances_measured[-1]
# Weird, this solves it. Measured covariances are wrong for generation...
inv_covariance_fixed_contrib[np.arange(self.M), np.arange(self.M)] *= amplify_diag
# Precompute the inverse, should speedup quite nicely
inv_covariance_fixed_contrib = np.linalg.inv(inv_covariance_fixed_contrib)
# inv_covariance_fixed_contrib = np.eye(self.M)
return (ATtcB, mean_fixed_contrib, inv_covariance_fixed_contrib)
def compute_normalization(self):
'''
Compute normalization factor for loglikelihood
'''
self.normalization = np.empty(self.N)
for n in xrange(self.N):
## Pack parameters and integrate using scipy, super fast
params = (self.theta[n], self.NT[n], self.random_network, self.theta_gamma, self.theta_kappa, self.ATtcB[self.tc[n]], self.sampled_feature_index, self.mean_fixed_contrib[self.tc[n]], self.inv_covariance_fixed_contrib)
self.normalization[n] = np.log(spintg.quad(like_theta_fct_single, -np.pi, np.pi, args=params)[0])
#######
def run_inference(self, parameters=None):
'''
Infer angles based on memory state
Can either:
1) Sample using Gibbs sampling / Slice sampler
2) Set to Max Lik values
Warning: needs around 200 samples to mix. Burn_samples set to 100.
'''
print "Running inference..."
if parameters is not None:
# force some values
self.init_sampling_parameters(parameters)
if self.inference_method == 'sample':
# Sample thetas
print "-> Sampling theta, %d passes" % self.num_sampling_passes
print "initial loglikelihood: %.2f" % self.compute_loglikelihood()
for pass_i in xrange(self.num_sampling_passes):
print "--> Pass %d" % (pass_i + 1)
self.sample_all()
elif self.inference_method == 'max_lik':
# Just use the ML value for the theta
print "-> Setting theta to ML values"
self.set_theta_max_likelihood(num_points=100, post_optimise=True)
elif self.inference_method== 'none':
# Do nothing
print "-> no inference"
def force_sampling_round(self):
'''
Force a round of sampling on the model
'''
self.run_inference(dict(inference_method='sample'))
def sample_all(self):
'''
Do one full sweep of sampling
'''
self.sample_theta()
loglikelihood = self.compute_loglikelihood()
print "Loglikelihood: %.2f" % loglikelihood
print "top 90%% loglike: %.2f" % self.compute_loglikelihood_top90percent()
return loglikelihood
def sample_theta(self, return_samples=False, subset_theta=None, debug=True):
'''
Sample the thetas
Need to use a slice sampler, as we do not know the normalization constant.
ASSUMES A_t = A for all t. Same for B.
'''
if self.selection_num_samples > self.num_samples:
# Limit selection_num_samples
self.selection_num_samples = self.num_samples
if subset_theta is not None:
# Should only sample a subset of the theta
permuted_datapoints = np.array(subset_theta)
else:
# Iterate over whole datapoints
# permuted_datapoints = np.random.permutation(np.arange(self.N))
permuted_datapoints = np.arange(self.N)
# errors = np.zeros(permuted_datapoints.shape, dtype=float)
if debug:
if self.selection_method == 'last':
print "Sampling theta: %d samples, %d burnin, select last" % (self.num_samples, self.burn_samples)
else:
print "Sampling theta: %d samples, %d selection, %d burnin" % (self.num_samples, self.selection_num_samples, self.burn_samples)
if return_samples:
all_samples = np.zeros((permuted_datapoints.size, self.num_samples))
if debug:
search_progress = progress.Progress((self.R - 1)*permuted_datapoints.size)
if len(self.theta_to_sample.shape) > 1:
permutation_fct = np.random.permutation
else:
permutation_fct = lambda x: [x]
cache_randomdraws = np.random.rand(self.N, self.R-1)
# Do everything in log-domain, to avoid numerical errors
i = 0
# for n in progress.ProgressDisplay(permuted_datapoints, display=progress.SINGLE_LINE):
for n in permuted_datapoints:
# Sample all the non-cued features
permuted_features = permutation_fct(self.theta_to_sample[n])
for sampled_feature_index_i, sampled_feature_index in enumerate(permuted_features):
# Handle lapse rate
has_lapsed, sampled_orientation = self.handle_lapse_sample(cache_randomdraws[n, sampled_feature_index_i])
if not has_lapsed:
# Get samples from the current memory distribution
if self.integrate_tc_out:
samples = self.get_samples_theta_tc_integratedout(n, sampled_feature_index=sampled_feature_index)
else:
(samples, _) = self.get_samples_theta_current_tc(n, sampled_feature_index=sampled_feature_index)
# Keep all samples if desired
if return_samples:
all_samples[i] = samples
# Select the new orientation
if self.selection_method == 'median':
sampled_orientation = np.median(samples[-self.selection_num_samples:], overwrite_input=True)
elif self.selection_method == 'last':
sampled_orientation = samples[-1]
else:
raise ValueError('wrong value for selection_method')
# Add output noise if desired.
sampled_orientation = self.add_output_noise(sampled_orientation)
# Save the orientation
self.theta[n, sampled_feature_index] = wrap_angles(sampled_orientation)
if debug:
search_progress.increment()
if search_progress.done():
eol = '\n'
else:
eol = '\r'
line= "%.2f%%, %s - %s" % (search_progress.percentage(), search_progress.time_remaining_str(), search_progress.eta_str())
sys.stdout.write("%s%s%s" % (line, " " * (78-len(line)), eol))
sys.stdout.flush()
i+= 1
if return_samples:
return all_samples
def handle_lapse_sample(self, random_draw=None):
'''
Handle Lapse rate, where a certain proportion of sampling runs are simply
dropped and randomly set to U[-pi, pi]
Depends on self.lapse_rate. Samples one U[0, 1], could be precomputed...
'''
should_lapse = False
sampled_orientation = -1
if self.lapse_rate > 0.0:
if random_draw is None:
should_lapse = np.random.rand() <= self.lapse_rate
else:
should_lapse = random_draw <= self.lapse_rate
if should_lapse:
sampled_orientation = sample_angle()
return should_lapse, sampled_orientation
def get_samples_theta_current_tc(self, n, sampled_feature_index=0):
# Pack the parameters for the likelihood function.
# Here, as the loglike_function only varies one of the input, need to give the rest of the theta vector.
params = (self.theta[n], self.NT[n], self.random_network, self.theta_gamma, self.theta_kappa, self.ATtcB[self.tc[n]], sampled_feature_index, self.mean_fixed_contrib[self.tc[n]], self.inv_covariance_fixed_contrib)
theta_initial = self.theta[n, sampled_feature_index]
# theta_initial = np.random.rand()*2.*np.pi-np.pi
# Sample the new theta
samples, llh = slicesampler.sample_1D_circular(self.num_samples, theta_initial, loglike_theta_fct_single, burn=self.burn_samples, widths=self.slice_width, loglike_fct_params=params, debug=False, step_out=True, jump_probability=self.slice_jump_prob)
return (samples, llh)
def get_samples_theta_tc_integratedout(self, n, sampled_feature_index=0):
'''
Sample theta, with tc integrated out.
Use rejection sampling (or something), discarding some samples.
Note: the actual number of samples returned is random, but around num_samples.
'''
samples_integratedout = []
for tc in xrange(self.T):
params = (self.theta[n], self.NT[n], self.random_network, self.theta_gamma, self.theta_kappa, self.ATtcB[tc], sampled_feature_index, self.mean_fixed_contrib[tc], self.inv_covariance_fixed_contrib)
theta_initial = self.theta[n, sampled_feature_index]
# theta_initial = np.random.rand()*2.*np.pi-np.pi
samples, _ = slicesampler.sample_1D_circular(self.num_samples, theta_initial, loglike_theta_fct_single, burn=self.burn_samples, widths=self.slice_width, loglike_fct_params=params, debug=False, step_out=True, jump_probability=self.slice_jump_prob)
# Now keep only some of them, following p(tc)
# for now, p(tc) = 1/T
filter_samples = np.random.random_sample(num_samples) < 1./self.T
samples_integratedout.extend(samples[filter_samples])
return np.array(samples_integratedout)
def add_output_noise(self, sample):
'''
Assume that samples are corrupted by some extra Von Mises noise, centered at the current sample and with a kappa set by self.sigma_output.
if self.sigma_output is 0, return the same samples
'''
if self.sigma_output > 0.0:
sample += spst.vonmises.rvs(self.kappa_output)
return sample
def add_output_noise_vectorized(self, samples):
'''
Vector version of add_output_noise()
'''
if self.sigma_output > 0.0:
samples += spst.vonmises.rvs(self.kappa_output, size=samples.size)
samples = wrap_angles(samples)
return samples
def set_theta(self, new_thetas):
'''
Update thetas to a given value (most likely to experimentally measured ones)
'''
self.theta[:, self.sampled_feature_index] = new_thetas
def set_theta_max_likelihood(self, num_points=100, post_optimise=True):
'''
Update theta to their Max Likelihood values.
Should be faster than sampling.
'''
all_angles = np.linspace(-np.pi, np.pi, num_points, endpoint=False)
llh = np.zeros(num_points)
# Compute the array
for n in progress.ProgressDisplay(np.arange(self.N), display=progress.SINGLE_LINE):
# Pack the parameters for the likelihood function
params = (self.theta[n], self.NT[n], self.random_network, self.theta_gamma, self.theta_kappa, self.ATtcB[self.tc[n]], self.sampled_feature_index, self.mean_fixed_contrib[self.tc[n]], self.inv_covariance_fixed_contrib)
# Compute the loglikelihood for all possible first feature
# Use this as initial value for the optimisation routine
for i in xrange(num_points):
# Give the correct cued second feature
llh[i] = loglike_theta_fct_single(all_angles[i], params)
# opt_angles[n] = spopt.fminbound(loglike_theta_fct_single_min, -np.pi, np.pi, params, disp=3)
# opt_angles[n] = spopt.brent(loglike_theta_fct_single_min, params)
# opt_angles[n] = wrap_angles(np.array([np.mod(spopt.anneal(loglike_theta_fct_single_min, np.random.random_sample()*np.pi*2. - np.pi, args=params)[0], 2.*np.pi)]))
if post_optimise:
self.theta[n, self.sampled_feature_index] = spopt.fmin(loglike_theta_fct_single_min, all_angles[np.argmax(llh)], args=params, disp=False)[0]
else:
self.theta[n, self.sampled_feature_index] = all_angles[np.argmax(llh)]
# Add output noise if desired.
self.theta[:, self.sampled_feature_index] = self.add_output_noise_vectorized(self.theta[:, self.sampled_feature_index])
def change_time_cued(self, t_cued):
'''
Change the cue.
Modify time of cue, and pull it from data_gen again
'''
# The time of the cued feature
self.data_gen.cued_features[:self.N, 1] = t_cued
# Reset the cued theta
self.theta[np.arange(self.N), self.data_gen.cued_features[:self.N, 0]] = self.data_gen.stimuli_correct[np.arange(self.N), self.data_gen.cued_features[:self.N, 1], self.data_gen.cued_features[:self.N, 0]]
def compute_bic(self, K=None, integrate_tc_out=False, LL=None, precision=200):
'''
Compute the BIC score for the current model.
Default K parameters:
- Sigmax
- M neurons
- ratio_conj if code_type is mixed
- sigma_output if >0
Usually, sigma_y is set to a super small value, and rc_scales are set automatically.
Not sure if num_samples/burn_samples should count, I don't think so.
'''
if K is None:
# Assume we set Sigmax and M.
K = 2.
if self.random_network.population_code_type == 'mixed':
K += 1.
if self.sigma_output > 0.0:
K += 1
if self.lapse_rate > 0.0:
K += 1
if LL is None:
LL = self.compute_loglikelihood(integrate_tc_out=integrate_tc_out, precision=precision)
print 'Bic: K ', K
return bic(K, LL, self.N)
def compute_loglikelihood(self, integrate_tc_out=False, precision=200):
'''
Compute the summed loglikelihood for the current setting of thetas and using the likelihood defined in loglike_theta_fct_single
- integrate_tc_out: use the current tc, or should integrate over possible recall times?
'''
return np.nansum(self.compute_loglikelihood_N(integrate_tc_out=integrate_tc_out, precision=precision))
def compute_loglikelihood_N(self, integrate_tc_out=False, precision=200, lapse_likelihood_lower_bound=False):
'''
Compute the loglikelihood for each datapoint, using the current setting of thetas and likelihood functions.
Uses the normalisation.
- integrate_tc_out: use current tc, or should integrate over recall times?
'''
LL = 0
if self.sigma_output > 0.0:
LL += self.compute_loglikelihood_N_convolved_output_noise(precision=precision)
else:
if integrate_tc_out:
LL += self.compute_loglikelihood_tc_integratedout()
else:
LL += self.compute_loglikelihood_current_tc()
if self.lapse_rate > 0.0:
# If lapse rate set, need to handle it properly.
if lapse_likelihood_lower_bound:
# This should be safe, but its a lower bound
LL = (1. - self.lapse_rate)*LL - self.lapse_rate*np.log(2.*np.pi)
else:
# This is precise, but could diverge
LL = np.log(self.lapse_rate) -np.log(2.*np.pi) + np.log1p((1. - self.lapse_rate)*2.*np.pi/(self.lapse_rate)*np.exp(LL))
return LL
def compute_loglikelihood_top90percent(self, integrate_tc_out=False, precision=200, all_loglikelihoods=None):
'''
Compute the loglikelihood for each datapoint, just like compute_loglikelihood and compute_loglikelihood_N, but now only sums the top 90% results
'''
if all_loglikelihoods is None:
all_loglikelihoods = self.compute_loglikelihood_N(integrate_tc_out=integrate_tc_out, precision=precision)
return np.nansum(np.sort(all_loglikelihoods)[self.N/10:])
def compute_loglikelihood_current_tc(self):
'''
Compute the loglikelihood for the current setting of thetas and tc and using the likelihood defined in loglike_theta_fct_single
'''
loglikelihood = np.empty(self.N)
for n in xrange(self.N):
# Pack the parameters for the likelihood function
params = (self.theta[n].copy(), self.NT[n], self.random_network, self.theta_gamma, self.theta_kappa, self.ATtcB[self.tc[n]], self.sampled_feature_index, self.mean_fixed_contrib[self.tc[n]], self.inv_covariance_fixed_contrib)
# Compute the loglikelihood for the current datapoint
loglikelihood[n] = loglike_theta_fct_single(self.theta[n, self.sampled_feature_index], params)
loglikelihood -= self.normalization[:self.N]
return loglikelihood
def compute_loglikelihood_tc_integratedout(self):
'''
Compute the loglikelihood for the current setting of thetas and using the likelihood defined in loglike_theta_fct_single
Integrates tc out.
'''
loglikelihood = np.empty((self.N, self.T))
for n in xrange(self.N):
for tc in xrange(self.T):
# Pack the parameters for the likelihood function
params = (self.theta[n].copy(), self.NT[n], self.random_network, self.theta_gamma, self.theta_kappa, self.ATtcB[tc], self.sampled_feature_index, self.mean_fixed_contrib[tc], self.inv_covariance_fixed_contrib)
# Compute the loglikelihood for the current datapoint
loglikelihood[n, tc] = loglike_theta_fct_single(self.theta[n, self.sampled_feature_index], params)
loglikelihood -= self.normalization[:self.N]
return loglikelihood
def compute_loglikelihood_N_convolved_output_noise(self, precision=100):
'''
Compute the loglikelihood for the current setting of thetas and tc and using the likelihood defined in loglike_theta_fct_single
'''
# TODO CONVERT ME
assert self.R == 2, 'Only works for R=2 now, really should convert it'
loglikelihoods = np.empty(self.N)
posterior_space = np.linspace(-np.pi, np.pi, precision, endpoint=False)
for n in xrange(self.N):
# Compute the convolved posterior
convolved_posterior = self.compute_likelihood_convolved_output_noise_fullspace(n=n, all_angles=posterior_space)
# Get a spline interpolation
convolv_posterior_spline = spinter.InterpolatedUnivariateSpline(posterior_space, convolved_posterior)
normalization_convolv_posterior_spline = convolv_posterior_spline.integral(posterior_space[0], posterior_space[-1])
# Compute the final convolved loglikelihoods for the actual thetas
loglikelihoods[n] = np.log(convolv_posterior_spline(self.theta[n, self.theta_target_index[n]]).item()) - np.log(normalization_convolv_posterior_spline)
return loglikelihoods
def compute_loglikelihood_convolved_output_noise(self, precision=100):
'''
Total summed loglikelihood, given convolved posterior with noise output
'''
return np.nansum(self.compute_loglikelihood_N_convolved_output_noise(precision=precision))
def compute_likelihood_convolved_output_noise_fullspace(self, n=0, all_angles=None, precision=100, normalize=False):
'''
Compute/instantiate the convolved loglikelihood on the provided space.
Computes it with the convolution theorem, in fourier space.
'''
# TODO CONVERT ME
assert self.R == 2, 'Only works for R=2 now, really should convert it'
if all_angles is None:
all_angles = np.linspace(-np.pi, np.pi, precision, endpoint=False)
posterior = self.compute_loglikelihood_nt_fullspace(n=n, t=self.tc[n], all_angles=all_angles, normalize=True, should_exponentiate=True)
noise = vonmisespdf(all_angles, 0.0, self.kappa_output)
# Compute the convolved posterior
posterior_fft = np.fft.fft(posterior)
noise_fft = np.fft.fft(noise)
convolved_posterior = np.abs(np.fft.ifft(posterior_fft*noise_fft))
# Roll it back, weirdly messed up because of the [-pi, pi] space instead of [0, 2pi].
convolved_posterior = np.roll(convolved_posterior, convolved_posterior.size/2)
if normalize:
# Get a spline interpolation to compute the normalisation
convolv_posterior_spline = spinter.InterpolatedUnivariateSpline(all_angles, convolved_posterior)
normalization_convolv_posterior_spline = convolv_posterior_spline.integral(all_angles[0], all_angles[-1])
convolved_posterior /= normalization_convolv_posterior_spline
return convolved_posterior
def compute_loglikelihood_nt_fullspace(self, n=0, t=0, all_angles=None, num_points=1000, normalize=False, should_exponentiate=False, remove_mean=False):
'''
Computes and returns the loglikelihood/likelihood evaluated for a given datapoint n given time/item t on the entire space (e.g. [-pi,pi]).
'''
if all_angles is None:
all_angles = np.linspace(-np.pi, np.pi, num_points, endpoint=False)
else:
num_points = all_angles.size
loglikelihood = np.empty(num_points)
curr_theta = self.data_gen.stimuli_correct[n, t].copy()
# Compute the loglikelihood for all possible first feature
for i in xrange(num_points):
params = (curr_theta, self.NT[n], self.random_network, self.theta_gamma, self.theta_kappa, self.ATtcB[t], self.sampled_feature_index, self.mean_fixed_contrib[t], self.inv_covariance_fixed_contrib)
# Give the correct cued second feature
loglikelihood[i] = loglike_theta_fct_single(all_angles[i], params)
# Normalise if required.
if normalize:
if t == self.tc[n]:
loglikelihood -= self.normalization[n]
else:
loglikelihood -= np.log(np.trapz(np.exp(loglikelihood), all_angles))
# Center loglik
if remove_mean:
loglikelihood -= np.mean(loglikelihood)
if should_exponentiate:
# If desired, exponentiate everything
loglikelihood = np.exp(loglikelihood)
return loglikelihood
def compute_likelihood_fullspace(self, n=0, all_angles=None, num_points=1000, normalize=False, remove_mean=False, should_exponentiate=False):
'''
Computes and returns the (log)likelihood evaluated for a given datapoint on the entire space (e.g. [-pi,pi]).
'''
if all_angles is None:
all_angles = np.linspace(-np.pi, np.pi, num_points, endpoint=False)
else:
num_points = all_angles.size
likelihood = np.zeros((self.T, num_points))
# Compute the array
for t in xrange(self.T):
likelihood[t] = self.compute_loglikelihood_nt_fullspace(n=n, t=t, all_angles=all_angles, num_points=num_points, normalize=normalize, should_exponentiate=should_exponentiate, remove_mean=remove_mean)
likelihood = likelihood.T
return likelihood
######################
def plot_likelihood(self, n=0, t=0, amplify_diag = 1.0, should_sample=False, num_samples=2000, return_output=False, should_exponentiate = False, num_points=1000, should_normalize=False, ax_handle=None):
# Pack the parameters for the likelihood function.
# Here, as the loglike_function only varies one of the input, need to give the rest of the theta vector.
params = (self.theta[n].copy(), self.NT[n], self.random_network, self.theta_gamma, self.theta_kappa, self.ATtcB[t], self.sampled_feature_index, self.mean_fixed_contrib[t], self.inv_covariance_fixed_contrib)
x = np.linspace(-np.pi, np.pi, num_points)
ll_x = np.array([(loglike_theta_fct_single(a, params)) for a in x])
if should_normalize:
ll_x -= self.normalization[n]
if should_exponentiate:
ll_x = np.exp(ll_x)
# ll_x -= np.mean(ll_x)
# ll_x /= np.abs(np.max(ll_x))
if ax_handle is None:
f, ax_handle = plt.subplots()
ax_handle.plot(x, ll_x)
ax_handle.axvline(x=self.data_gen.stimuli_correct[n, self.data_gen.cued_features[n, 1], 0], color='r')
ax_handle.axvline(x=self.theta[n, self.theta_target_index[n]], color='k', linestyle='--')
ax_handle.set_xlim((-np.pi, np.pi))
if should_sample:
samples, _ = slicesampler.sample_1D_circular(num_samples, np.random.rand()*2.*np.pi-np.pi, loglike_theta_fct_single, burn=500, widths=np.pi/4., loglike_fct_params=params, debug=False, step_out=True)
x_edges = x - np.pi/num_points # np.histogram wants the left-right boundaries...
x_edges = np.r_[x_edges, -x_edges[0]] # the rightmost boundary is the mirror of the leftmost one
sample_h, left_x = np.histogram(samples, bins=x_edges)
ax_handle.bar(x_edges[:-1], sample_h/np.max(sample_h).astype('float'), facecolor='green', alpha=0.75, width=np.pi/num_points)
ax_handle.get_figure().canvas.draw()
if return_output:
if should_sample:
return (ll_x, x, samples)
else:
return (ll_x, x)
def plot_likelihood_variation_twoangles(self, index_second_feature=1, num_points=100, amplify_diag=1.0, should_plot=True, should_return=False, should_exponentiate = False, remove_mean=False, n=0, t=0, interpolation='nearest', normalize=False, colormap=None):
'''
Compute the likelihood, varying two angles around.
Plot the result
'''
all_angles = np.linspace(-np.pi, np.pi, num_points, endpoint=False)
llh_2angles = np.zeros((num_points, num_points))
curr_theta = self.data_gen.stimuli_correct[n, t].copy()
# Compute the array
for i in xrange(num_points):
print "%d%%" % (i/float(num_points)*100)
for j in xrange(num_points):
# Pack the parameters for the likelihood function
curr_theta[index_second_feature] = all_angles[j]
params = (curr_theta, self.NT[n], self.random_network, self.theta_gamma, self.theta_kappa, self.ATtcB[t], self.sampled_feature_index, self.mean_fixed_contrib[t], self.inv_covariance_fixed_contrib)
# llh_2angles[i, j] = loglike_theta_fct_vect(np.array([all_angles[i], all_angles[j]]), params)
llh_2angles[i, j] = loglike_theta_fct_single(all_angles[i], params)
if remove_mean:
llh_2angles -= np.mean(llh_2angles)
# Normalise if required.
if normalize:
llh_2angles -= self.normalization[n]
if should_exponentiate:
llh_2angles = np.exp(llh_2angles)
if should_plot:
# Plot the obtained landscape
f = plt.figure()
ax = f.add_subplot(111)
im= ax.imshow(llh_2angles.T, origin='lower', cmap=colormap)
im.set_extent((-np.pi, np.pi, -np.pi, np.pi))
im.set_interpolation(interpolation)
f.colorbar(im)
ax.set_xticks((-np.pi, -np.pi/2, 0, np.pi/2., np.pi))
ax.set_xticklabels((r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\pi$'), fontsize=15)
ax.set_yticks((-np.pi, -np.pi/2, 0, np.pi/2., np.pi))
ax.set_yticklabels((r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\pi$'), fontsize=15)
# Callback function when moving mouse around figure.
def report_pixel(x, y):
# Extract loglik at that position
x_i = (np.abs(all_angles-x)).argmin()
y_i = (np.abs(all_angles-y)).argmin()
v = llh_2angles[x_i, y_i]
return "x=%f y=%f value=%f" % (x, y, v)
ax.format_coord = report_pixel
# Indicate the correct solutions
correct_angles = self.data_gen.stimuli_correct[n]
colmap = plt.get_cmap('gist_rainbow')
color_gen = [colmap(1.*(i)/self.T) for i in xrange(self.T)][::-1] # use 22 colors
for t in xrange(self.T):
w = plt_patches.Wedge((correct_angles[t, 0], correct_angles[t, index_second_feature]), 0.25, 0, 360, 0.10, color=color_gen[t], alpha=0.9)
ax.add_patch(w)
# plt.annotate('O', (correct_angles[1, 0], correct_angles[1, 1]), color='blue', fontweight='bold', fontsize=30, horizontalalignment='center', verticalalignment='center')
if should_return:
return llh_2angles
def plot_likelihood_correctlycuedtimes(self, n=0, amplify_diag=1.0, all_angles=None, num_points=500, should_plot=True, should_return=False, should_exponentiate = False, show_legend=True, show_current_theta=True, debug=True, ax_handle=None):
'''
Plot the log-likelihood function, over the space of the sampled theta, keeping the other thetas fixed to their correct cued value.
'''
num_points = int(num_points)
if all_angles is None:
all_angles = np.linspace(-np.pi, np.pi, num_points, endpoint=False)
# Compute the likelihood
llh_2angles = self.compute_likelihood_fullspace(n=n, all_angles=all_angles, num_points=num_points, should_exponentiate=should_exponentiate, remove_mean=True)
# Save it if we need to return it
if should_return:
llh_2angles_out = llh_2angles.copy()
# Normalize loglik
llh_2angles /= np.abs(np.max(llh_2angles, axis=0))
opt_angles = np.argmax(llh_2angles, axis=0)
# Move them a bit apart
llh_2angles += 1.2*np.arange(self.T)*np.abs(np.max(llh_2angles, axis=0)-np.mean(llh_2angles, axis=0))
# Plot the result
if should_plot:
if ax_handle is None: