-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgaussian.py
1553 lines (1258 loc) · 54 KB
/
gaussian.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
from __future__ import division
from builtins import map
from builtins import zip
from builtins import range
from builtins import object
__all__ = \
['Gaussian', 'GaussianFixedMean', 'GaussianFixedCov', 'GaussianFixed',
'GaussianNonConj', 'DiagonalGaussian', 'DiagonalGaussianNonconjNIG',
'IsotropicGaussian', 'ScalarGaussianNIX', 'ScalarGaussianNonconjNIX',
'ScalarGaussianNonconjNIG', 'ScalarGaussianFixedvar']
import numpy as np
from numpy import newaxis as na
from numpy.core.umath_tests import inner1d
import scipy.linalg
import scipy.stats as stats
import scipy.special as special
import copy
from pybasicbayes.abstractions import GibbsSampling, MeanField, \
MeanFieldSVI, Collapsed, MaxLikelihood, MAP, Tempering
from pybasicbayes.distributions.meta import _FixedParamsMixin
from pybasicbayes.util.stats import sample_niw, invwishart_entropy, \
sample_invwishart, invwishart_log_partitionfunction, \
getdatasize, flattendata, getdatadimension, \
combinedata, multivariate_t_loglik, gi, niw_expectedstats
weps = 1e-12
class _GaussianBase(object):
@property
def params(self):
return dict(mu=self.mu, sigma=self.sigma)
@property
def D(self):
return self.mu.shape[0]
### internals
def getsigma(self):
return self._sigma
def setsigma(self,sigma):
self._sigma = sigma
self._sigma_chol = None
sigma = property(getsigma,setsigma)
@property
def sigma_chol(self):
if not hasattr(self,'_sigma_chol') or self._sigma_chol is None:
#print("debugging this now:" + str(type(self.sigma[0])))
self._sigma_chol = np.linalg.cholesky(self.sigma.astype("float64"))
return self._sigma_chol
### distribution stuff
def rvs(self,size=None):
size = 1 if size is None else size
size = size + (self.mu.shape[0],) if isinstance(size,tuple) \
else (size,self.mu.shape[0])
return self.mu + np.random.normal(size=size).dot(self.sigma_chol.T)
#return self.mu + np.random.normal(size=size).dot(self.sigma_chol.T)
def log_likelihood(self,x):
try:
mu, D = self.mu, self.D
sigma_chol = self.sigma_chol
bads = np.isnan(np.atleast_2d(x)).any(axis=1)
x = np.nan_to_num(x).reshape((-1,D)) - mu
xs = scipy.linalg.solve_triangular(sigma_chol,x.T,lower=True)
out = -1./2. * inner1d(xs.T,xs.T) - D/2*np.log(2*np.pi) \
- np.log(sigma_chol.diagonal()).sum()
out[bads] = 0
return out
except np.linalg.LinAlgError:
# NOTE: degenerate distribution doesn't have a density
return np.repeat(-np.inf,x.shape[0])
### plotting
# TODO making animations, this seems to generate an extra notebook figure
_scatterplot = None
_parameterplot = None
def plot(self,ax=None,data=None,indices=None,color='b',
plot_params=True,label='',alpha=1.,
update=False,draw=True):
import matplotlib.pyplot as plt
from pybasicbayes.util.plot import project_data, \
plot_gaussian_projection, plot_gaussian_2D
ax = ax if ax else plt.gca()
D = self.D
if data is not None:
data = flattendata(data)
if data is not None:
if D > 2:
plot_basis = np.random.RandomState(seed=0).randn(2,D)
data = project_data(data,plot_basis)
if update and self._scatterplot is not None:
self._scatterplot.set_offsets(data)
self._scatterplot.set_color(color)
else:
self._scatterplot = ax.scatter(
data[:,0],data[:,1],marker='.',color=color)
if plot_params:
if D > 2:
plot_basis = np.random.RandomState(seed=0).randn(2,D)
self._parameterplot = \
plot_gaussian_projection(
self.mu,self.sigma,plot_basis,
color=color,label=label,alpha=min(1-1e-3,alpha),
ax=ax, artists=self._parameterplot if update else None)
else:
self._parameterplot = \
plot_gaussian_2D(
self.mu,self.sigma,color=color,label=label,
alpha=min(1-1e-3,alpha), ax=ax,
artists=self._parameterplot if update else None)
if draw:
plt.draw()
return [self._scatterplot] + list(self._parameterplot)
def to_json_dict(self):
D = self.mu.shape[0]
assert D == 2
U,s,_ = np.linalg.svd(self.sigma)
U /= np.linalg.det(U)
theta = np.arctan2(U[0,0],U[0,1])*180/np.pi
return {'x':self.mu[0],'y':self.mu[1],'rx':np.sqrt(s[0]),
'ry':np.sqrt(s[1]), 'theta':theta}
class Gaussian(
_GaussianBase, GibbsSampling, MeanField, MeanFieldSVI,
Collapsed, MAP, MaxLikelihood):
'''
Multivariate Gaussian distribution class.
NOTE: Only works for 2 or more dimensions. For a scalar Gaussian, use a
scalar class. Uses a conjugate Normal/Inverse-Wishart prior.
Hyperparameters mostly follow Gelman et al.'s notation in Bayesian Data
Analysis:
nu_0, sigma_0, mu_0, kappa_0
Parameters are mean and covariance matrix:
mu, sigma
'''
def __init__(
self, mu=None, sigma=None,
mu_0=None,
sigma_0=None,
kappa_0=1, nu_0=4):
self.mu = mu
#print("I swear to fucking god:" + str(sigma))
self.sigma = sigma
self.mu_0 = mu_0
self.mu_mf = mu_0
self.sigma_mf = sigma_0
self.sigma_0 = sigma_0
self.kappa_0 = kappa_0
self.kappa_mf = kappa_0
self.nu_0 = nu_0
self.nu_mf = nu_0
#print("sigma:??????" + str(self.sigma))
# NOTE: resampling will set mu_mf and sigma_mf if necessary
#if mu is sigma is None \
#and not any(_ is None for _ in (mu_0,sigma_0,kappa_0,nu_0)):
#self.resample() # initialize from prior
#if mu is not None and sigma is not None \
#and not any(_ is None for _ in (mu_0,sigma_0,kappa_0,nu_0)):
#self.mu_mf = mu
#self.sigma_mf = sigma * (self.nu_0 - self.mu_mf.shape[0] - 1)
@property
def hypparams(self):
return dict(
mu_0=self.mu_0,sigma_0=self.sigma_0,
kappa_0=self.kappa_0,nu_0=self.nu_0)
@property
def natural_hypparam(self):
return self._standard_to_natural(
self.mu_0,self.sigma_0,self.kappa_0,self.nu_0)
@natural_hypparam.setter
def natural_hypparam(self,natparam):
self.mu_0, self.sigma_0, self.kappa_0, self.nu_0 = \
self._natural_to_standard(natparam)
def _standard_to_natural(self,mu_mf,sigma_mf,kappa_mf,nu_mf):
D = sigma_mf.shape[0]
out = np.zeros((D+3,D+3))
out[:D,:D] = sigma_mf + kappa_mf * np.outer(mu_mf,mu_mf)
out[:D,-2] = out[-2,:D] = kappa_mf * mu_mf
out[-2,-2] = kappa_mf
out[-1,-1] = nu_mf + 2 + D
return [out[:D,:D], out[:D,-2], out[-2,-2], out[-1,-1]]
def _natural_to_standard(self,natparam):
D = natparam.shape[0]-2
A = natparam[:D,:D]
b = natparam[:D,-2]
c = natparam[-2,-2]
d = natparam[-1,-1]
return b/c, A - np.outer(b,b)/c, c, d - 2 - D
@property
def num_parameters(self):
D = self.D
return D*(D+1)/2
@property
def D(self):
if self.mu is not None:
return self.mu.shape[0]
elif self.mu_0 is not None:
return self.mu_0.shape[0]
def _get_statistics(self,data,D=None):
if D is None:
D = self.D if self.D is not None else getdatadimension(data)
out = np.zeros((D+2,D+2))
if isinstance(data,np.ndarray):
out[:D,:D] = data.T.dot(data)
out[-2,:D] = out[:D,-2] = data.sum(0)
out[-2,-2] = out[-1,-1] = data.shape[0]
return out
else:
return sum(list(map(self._get_statistics,data)),out)
def _get_weighted_statistics(self,data,weights,D=None):
D = getdatadimension(data) if D is None else D
out = np.zeros((D+2,D+2))
if isinstance(data,np.ndarray):
out[:D,:D] = data.T.dot(weights[:,na]*data)
out[-2,:D] = out[:D,-2] = weights.dot(data)
out[-2,-2] = out[-1,-1] = weights.sum()
return out
else:
return sum(list(map(self._get_weighted_statistics,data,weights)),out)
def _get_empty_statistics(self, D):
out = np.zeros((D+2,D+2))
return out
def empirical_bayes(self,data):
self.natural_hypparam = self._get_statistics(data)
self.resample() # intialize from prior given new hyperparameters
return self
@staticmethod
def _stats_ensure_array(stats):
if isinstance(stats, np.ndarray):
return stats
x, xxT, n = stats
D = x.shape[-1]
out = np.zeros((D+2,D+2))
out[:D,:D] = xxT
out[-2,:D] = out[:D,-2] = x
out[-2,-2] = out[-1,-1] = n
return out
### Gibbs sampling
def resample(self,data=[]):
D = len(self.mu_0)
self.mu, self.sigma = \
sample_niw(*self._natural_to_standard(
self.natural_hypparam + self._get_statistics(data,D)))
# NOTE: next lines let Gibbs sampling initialize mean
nu = self.nu_mf if hasattr(self,'nu_mf') and self.nu_mf \
else self.nu_0
self.mu_mf, self._sigma_mf = self.mu, self.sigma * (nu - D - 1)
return self
def copy_sample(self):
new = copy.copy(self)
new.mu = self.mu.copy()
new.sigma = self.sigma.copy()
return new
### Mean Field
def _resample_from_mf(self):
self.mu, self.sigma = \
sample_niw(*self._natural_to_standard(
self.mf_natural_hypparam))
return self
def meanfieldupdate(self, data=None, weights=None, stats=None):
assert (data is not None and weights is not None) ^ (stats is not None)
stats = self._stats_ensure_array(stats) if stats is not None else \
self._get_weighted_statistics(data, weights, self.mu_0.shape[0])
self.mf_natural_hypparam = \
self.natural_hypparam + stats
def meanfield_sgdstep(self,data,weights,prob,stepsize):
D = len(self.mu_0)
self.mf_natural_hypparam = \
(1-stepsize) * self.mf_natural_hypparam + stepsize * (
self.natural_hypparam
+ 1./prob
* self._get_weighted_statistics(data,weights,D))
@property
def mf_natural_hypparam(self):
#print("sigma_mf just before call")
#print(self.sigma_mf)
#print(self._standard_to_natural(
#self.mu_mf,self.sigma_mf,self.kappa_mf,self.nu_mf))
return self._standard_to_natural(
self.mu_mf,self.sigma_mf,self.kappa_mf,self.nu_mf)
@mf_natural_hypparam.setter
def mf_natural_hypparam(self,natparam):
self.mu_mf, self.sigma_mf, self.kappa_mf, self.nu_mf = \
self._natural_to_standard(natparam)
# NOTE: next line is for plotting
self.mu, self.sigma = \
self.mu_mf, self.sigma_mf/(self.nu_mf - self.mu_mf.shape[0] - 1)
@property
def sigma_mf(self):
return self._sigma_mf
@sigma_mf.setter
def sigma_mf(self,val):
self._sigma_mf = val
self._sigma_mf_chol = None
@property
def sigma_mf_chol(self):
if self._sigma_mf_chol is None:
self._sigma_mf_chol = self.sigma_mf
return self._sigma_mf_chol
def get_vlb(self):
D = len(self.mu_0)
loglmbdatilde = self._loglmbdatilde()
# see Eq. 10.77 in Bishop
q_entropy = -0.5 * (loglmbdatilde + D * (np.log(self.kappa_mf/(2*np.pi))-1)) \
+ invwishart_entropy(self.sigma_mf,self.nu_mf,self.sigma_chol)
# see Eq. 10.74 in Bishop, we aren't summing over K
#print("sigma_mf\n" + str(type(self.sigma_mf)))
#print("sigma_0\n" + str(type(self.sigma_0)))
#print("nu_0: " + str(self.nu_0))
#print("mu_mf: " + str(self.mu_mf))
#print("loglmbdatilde: " + str(loglmbdatilde))
#print("D: " + str(D))
#print("something: " + str(np.linalg.solve(self.sigma_mf.astype(np.float64),
#self.mu_mf.astype(np.float64)-self.mu_0.astype(np.float64))))
p_avgengy = 0.5 * (D * np.log(self.kappa_0/(2*np.pi)) + loglmbdatilde
- D*self.kappa_0/self.kappa_mf - self.kappa_0*self.nu_mf*
np.dot(self.mu_mf -
self.mu_0,np.linalg.solve(self.sigma_mf.astype(np.float64),
self.mu_mf.astype(np.float64) - self.mu_0.astype(np.float64)))) \
+ invwishart_log_partitionfunction(self.sigma_0,self.nu_0) \
+ (self.nu_0 - D - 1)/2*loglmbdatilde - 1/2*self.nu_mf \
* np.linalg.solve(self.sigma_mf.astype(np.float64),
self.sigma_0.astype(np.float64)).trace()
return p_avgengy + q_entropy
def expected_log_likelihood(self, x=None, stats=None):
assert (x is not None) ^ isinstance(stats, (tuple, np.ndarray))
if x is not None:
mu_n, kappa_n, nu_n = self.mu_mf, self.kappa_mf, self.nu_mf
D = len(mu_n)
#print("mu: " + str(mu_n))
#print("x: " + str(x))
x = np.reshape(x,(-1,D)) - mu_n # x is now centered
#xs = np.linalg.solve(self.sigma_mf_chol,x.T)
#print("sigma_mf_chol: " + str(self.sigma_mf_chol))
xs = self.sigma_mf_chol
#print("xs: " + str(xs))
# see Eqs. 10.64, 10.67, and 10.71 in Bishop
#print("I really hope not: " + str(self._loglmbdatilde()))
#print(type(xs))
return self._loglmbdatilde()/2 - D/(2*kappa_n) - nu_n/2 * \
inner1d(xs.astype(np.float64),xs.astype(np.float64)) - D/2*np.log(2*np.pi)
else:
D = self.mu_mf.shape[0]
E_J, E_h, E_muJmuT, E_logdetJ = \
niw_expectedstats(
self.nu_mf, self.sigma_mf, self.mu_mf, self.kappa_mf)
if isinstance(stats, np.ndarray):
parammat = np.zeros((D+2,D+2))
parammat[:D,:D] = E_J
parammat[:D,-2] = parammat[-2,:D] = -E_h
parammat[-2,-2] = E_muJmuT
parammat[-1,-1] = -E_logdetJ
contract = 'ij,nij->n' if stats.ndim == 3 else 'ij,ij->'
return -1./2*np.einsum(contract, parammat, stats) \
- D/2.*np.log(2*np.pi)
else:
x, xxT, n = stats
c1, c2 = ('i,i->', 'ij,ij->') if x.ndim == 1 \
else ('i,ni->n', 'ij,nij->n')
out = -1./2 * np.einsum(c2, E_J, xxT)
out += np.einsum(c1, E_h, x)
out += -n/2.*E_muJmuT
out += -D/2.*np.log(2*np.pi) + n/2.*E_logdetJ
return out
def _loglmbdatilde(self):
# see Eq. 10.65 in Bishop
D = len(self.mu_0)
chol = self.sigma_mf_chol.astype('float64') # local step changes type somewhere
#print(type(chol.diagonal()[0]))
return special.digamma((self.nu_mf-np.arange(D))/2.).sum() \
+ D*np.log(2) - 2 * sum(np.log(chol.diagonal()))
### Collapsed
def log_marginal_likelihood(self,data):
n, D = getdatasize(data), len(self.mu_0)
return self._log_partition_function(
*self._natural_to_standard(
self.natural_hypparam + self._get_statistics(data,D))) \
- self._log_partition_function(self.mu_0,self.sigma_0,self.kappa_0,self.nu_0) \
- n*D/2 * np.log(2*np.pi)
def _log_partition_function(self,mu,sigma,kappa,nu):
D = len(mu)
chol = np.linalg.cholesky(sigma)
return nu*D/2*np.log(2) + special.multigammaln(nu/2,D) + D/2*np.log(2*np.pi/kappa) \
- nu*np.log(chol.diagonal()).sum()
def log_predictive_studentt_datapoints(self,datapoints,olddata):
D = len(self.mu_0)
mu_n, sigma_n, kappa_n, nu_n = \
self._natural_to_standard(
self.natural_hypparam + self._get_statistics(olddata,D))
return multivariate_t_loglik(
datapoints,nu_n-D+1,mu_n,(kappa_n+1)/(kappa_n*(nu_n-D+1))*sigma_n)
def log_predictive_studentt(self,newdata,olddata):
newdata = np.atleast_2d(newdata)
return sum(self.log_predictive_studentt_datapoints(
d,combinedata((olddata,newdata[:i])))[0] for i,d in enumerate(newdata))
### Max likelihood
def max_likelihood(self,data,weights=None):
D = getdatadimension(data)
if weights is None:
statmat = self._get_statistics(data,D)
else:
statmat = self._get_weighted_statistics(data,weights,D)
n, x, xxt = statmat[-1,-1], statmat[-2,:D], statmat[:D,:D]
# this SVD is necessary to check if the max likelihood solution is
# degenerate, which can happen in the EM algorithm
if n < D or (np.linalg.svd(xxt,compute_uv=False) > 1e-6).sum() < D:
self.broken = True
self.mu = 99999999*np.ones(D)
self.sigma = np.eye(D)
else:
self.mu = x/n
self.sigma = xxt/n - np.outer(self.mu,self.mu)
return self
def MAP(self,data,weights=None):
D = getdatadimension(data)
# max likelihood with prior pseudocounts included in data
if weights is None:
statmat = self._get_statistics(data)
else:
statmat = self._get_weighted_statistics(data,weights)
statmat += self.natural_hypparam
n, x, xxt = statmat[-1,-1], statmat[-2,:D], statmat[:D,:D]
self.mu = x/n
self.sigma = xxt/n - np.outer(self.mu,self.mu)
return self
class GaussianFixedMean(_GaussianBase, GibbsSampling, MaxLikelihood):
def __init__(self,mu=None,sigma=None,nu_0=None,lmbda_0=None):
self.sigma = sigma
self.mu = mu
self.nu_0 = nu_0
self.lmbda_0 = lmbda_0
if sigma is None and not any(_ is None for _ in (nu_0,lmbda_0)):
self.resample() # initialize from prior
@property
def hypparams(self):
return dict(nu_0=self.nu_0,lmbda_0=self.lmbda_0)
@property
def num_parameters(self):
D = len(self.mu)
return D*(D+1)/2
def _get_statistics(self,data):
n = getdatasize(data)
if n > 1e-4:
if isinstance(data,np.ndarray):
centered = data[gi(data)] - self.mu
sumsq = centered.T.dot(centered)
n = len(centered)
else:
sumsq = sum((d[gi(d)]-self.mu).T.dot(d[gi(d)]-self.mu) for d in data)
else:
sumsq = None
return n, sumsq
def _get_weighted_statistics(self,data,weights):
if isinstance(data,np.ndarray):
neff = weights.sum()
if neff > weps:
centered = data - self.mu
sumsq = centered.T.dot(weights[:,na]*centered)
else:
sumsq = None
else:
neff = sum(w.sum() for w in weights)
if neff > weps:
sumsq = sum((d-self.mu).T.dot(w[:,na]*(d-self.mu)) for w,d in zip(weights,data))
else:
sumsq = None
return neff, sumsq
def _posterior_hypparams(self,n,sumsq):
nu_0, lmbda_0 = self.nu_0, self.lmbda_0
if n > 1e-4:
nu_0 = nu_0 + n
sigma_n = self.lmbda_0 + sumsq
return sigma_n, nu_0
else:
return lmbda_0, nu_0
### Gibbs sampling
def resample(self, data=[]):
self.sigma = sample_invwishart(*self._posterior_hypparams(
*self._get_statistics(data)))
return self
### Max likelihood
def max_likelihood(self,data,weights=None):
D = getdatadimension(data)
if weights is None:
n, sumsq = self._get_statistics(data)
else:
n, sumsq = self._get_weighted_statistics(data,weights)
if n < D or (np.linalg.svd(sumsq,compute_uv=False) > 1e-6).sum() < D:
# broken!
self.sigma = np.eye(D)*1e-9
self.broken = True
else:
self.sigma = sumsq/n
return self
class GaussianFixedCov(_GaussianBase, GibbsSampling, MaxLikelihood):
# See Gelman's Bayesian Data Analysis notation around Eq. 3.18, p. 85
# in 2nd Edition. We replaced \Lambda_0 with sigma_0 since it is a prior
# *covariance* matrix rather than a precision matrix.
def __init__(self,mu=None,sigma=None,mu_0=None,sigma_0=None):
self.mu = mu
self.sigma = sigma
self.mu_0 = mu_0
self.sigma_0 = sigma_0
if mu is None and not any(_ is None for _ in (mu_0,sigma_0)):
self.resample()
@property
def hypparams(self):
return dict(mu_0=self.mu_0,sigma_0=self.sigma_0)
@property
def sigma_inv(self):
if not hasattr(self,'_sigma_inv'):
self._sigma_inv = np.linalg.inv(self.sigma)
return self._sigma_inv
@property
def sigma_inv_0(self):
if not hasattr(self,'_sigma_inv_0'):
self._sigma_inv_0 = np.linalg.inv(self.sigma_0)
return self._sigma_inv_0
@property
def num_parameters(self):
return len(self.mu)
def _get_statistics(self,data):
n = getdatasize(data)
if n > 0:
if isinstance(data,np.ndarray):
xbar = data.mean(0)
else:
xbar = sum(d.sum(0) for d in data) / n
else:
xbar = None
return n, xbar
def _get_weighted_statistics(self,data,weights):
if isinstance(data,np.ndarray):
neff = weights.sum()
if neff > weps:
xbar = weights.dot(data) / neff
else:
xbar = None
else:
neff = sum(w.sum() for w in weights)
if neff > weps:
xbar = sum(w.dot(d) for w,d in zip(weights,data)) / neff
else:
xbar = None
return neff, xbar
def _posterior_hypparams(self,n,xbar):
# It seems we should be working with lmbda and sigma inv (unless lmbda
# is a covariance, not a precision)
sigma_inv, mu_0, sigma_inv_0 = self.sigma_inv, self.mu_0, self.sigma_inv_0
if n > 0:
sigma_inv_n = n*sigma_inv + sigma_inv_0
mu_n = np.linalg.solve(
sigma_inv_n, sigma_inv_0.dot(mu_0) + n*sigma_inv.dot(xbar))
return mu_n, sigma_inv_n
else:
return mu_0, sigma_inv_0
### Gibbs sampling
def resample(self,data=[]):
mu_n, sigma_n_inv = self._posterior_hypparams(*self._get_statistics(data))
D = len(mu_n)
L = np.linalg.cholesky(sigma_n_inv)
self.mu = scipy.linalg.solve_triangular(L,np.random.normal(size=D),lower=True) \
+ mu_n
return self
### Max likelihood
def max_likelihood(self,data,weights=None):
if weights is None:
n, xbar = self._get_statistics(data)
else:
n, xbar = self._get_weighted_statistics(data,weights)
self.mu = xbar
return self
class GaussianFixed(_FixedParamsMixin, Gaussian):
def __init__(self,mu,sigma):
self.mu = mu
self.sigma = sigma
class GaussianNonConj(_GaussianBase, GibbsSampling):
def __init__(self,mu=None,sigma=None,
mu_0=None,mu_lmbda_0=None,nu_0=None,sigma_lmbda_0=None):
self._sigma_distn = GaussianFixedMean(mu=mu,
nu_0=nu_0,lmbda_0=sigma_lmbda_0,sigma=sigma)
self._mu_distn = GaussianFixedCov(sigma=self._sigma_distn.sigma,
mu_0=mu_0, sigma_0=mu_lmbda_0,mu=mu)
self._sigma_distn.mu = self._mu_distn.mu
@property
def hypparams(self):
d = self._mu_distn.hypparams
d.update(**self._sigma_distn.hypparams)
return d
def _get_mu(self):
return self._mu_distn.mu
def _set_mu(self,val):
self._mu_distn.mu = val
self._sigma_distn.mu = val
mu = property(_get_mu,_set_mu)
def _get_sigma(self):
return self._sigma_distn.sigma
def _set_sigma(self,val):
self._sigma_distn.sigma = val
self._mu_distn.sigma = val
sigma = property(_get_sigma,_set_sigma)
### Gibbs sampling
def resample(self,data=[],niter=1):
if getdatasize(data) == 0:
niter = 1
# TODO this is kinda dumb because it collects statistics over and over
# instead of updating them...
for itr in range(niter):
# resample mu
self._mu_distn.sigma = self._sigma_distn.sigma
self._mu_distn.resample(data)
# resample sigma
self._sigma_distn.mu = self._mu_distn.mu
self._sigma_distn.resample(data)
return self
# TODO collapsed
class DiagonalGaussian(_GaussianBase,GibbsSampling,MaxLikelihood,MeanField,Tempering):
'''
Product of normal-inverse-gamma priors over mu (mean vector) and sigmas
(vector of scalar variances).
The prior follows
sigmas ~ InvGamma(alphas_0,betas_0) iid
mu | sigma ~ N(mu_0,1/nus_0 * diag(sigmas))
It allows placing different prior hyperparameters on different components.
'''
def __init__(self,mu=None,sigmas=None,mu_0=None,nus_0=None,alphas_0=None,betas_0=None):
# all the s's refer to the fact that these are vectors of length
# len(mu_0) OR scalars
if mu_0 is not None:
D = mu_0.shape[0]
if nus_0 is not None and \
(isinstance(nus_0,int) or isinstance(nus_0,float)):
nus_0 = nus_0*np.ones(D)
if alphas_0 is not None and \
(isinstance(alphas_0,int) or isinstance(alphas_0,float)):
alphas_0 = alphas_0*np.ones(D)
if betas_0 is not None and \
(isinstance(betas_0,int) or isinstance(betas_0,float)):
betas_0 = betas_0*np.ones(D)
self.mu_0 = self.mf_mu = mu_0
self.nus_0 = self.mf_nus = nus_0
self.alphas_0 = self.mf_alphas = alphas_0
self.betas_0 = self.mf_betas = betas_0
self.mu = mu
self.sigmas = sigmas
assert self.mu is None or (isinstance(self.mu,np.ndarray) and not isinstance(self.mu,np.ma.MaskedArray))
assert self.sigmas is None or (isinstance(self.sigmas,np.ndarray) and not isinstance(self.sigmas,np.ma.MaskedArray))
if mu is sigmas is None \
and not any(_ is None for _ in (mu_0,nus_0,alphas_0,betas_0)):
self.resample() # intialize from prior
### the basics!
@property
def parameters(self):
return self.mu, self.sigmas
@parameters.setter
def parameters(self, mu_sigmas_tuple):
(mu,sigmas) = mu_sigmas_tuple
self.mu, self.sigmas = mu, sigmas
@property
def sigma(self):
return np.diag(self.sigmas)
@sigma.setter
def sigma(self,val):
val = np.array(val)
assert val.ndim in (1,2)
if val.ndim == 1:
self.sigmas = val
else:
self.sigmas = np.diag(val)
@property
def hypparams(self):
return dict(mu_0=self.mu_0,nus_0=self.nus_0,
alphas_0=self.alphas_0,betas_0=self.betas_0)
def rvs(self,size=None):
size = np.array(size,ndmin=1)
return np.sqrt(self.sigmas)*\
np.random.normal(size=np.concatenate((size,self.mu.shape))) + self.mu
def log_likelihood(self,x,temperature=1.):
mu, sigmas, D = self.mu, self.sigmas * temperature, self.mu.shape[0]
x = np.reshape(x,(-1,D))
Js = -1./(2*sigmas)
return (np.einsum('ij,ij,j->i',x,x,Js) - np.einsum('ij,j,j->i',x,2*mu,Js)) \
+ (mu**2*Js - 1./2*np.log(2*np.pi*sigmas)).sum()
### posterior updating stuff
@property
def natural_hypparam(self):
return self._standard_to_natural(self.alphas_0,self.betas_0,self.mu_0,self.nus_0)
@natural_hypparam.setter
def natural_hypparam(self,natparam):
self.alphas_0, self.betas_0, self.mu_0, self.nus_0 = \
self._natural_to_standard(natparam)
def _standard_to_natural(self,alphas,betas,mu,nus):
return np.array([2*betas + nus * mu**2, nus*mu, nus, 2*alphas])
def _natural_to_standard(self,natparam):
nus = natparam[2]
mu = natparam[1] / nus
alphas = natparam[3]/2.
betas = (natparam[0] - nus*mu**2) / 2.
return alphas, betas, mu, nus
def _get_statistics(self,data):
if isinstance(data,np.ndarray) and data.shape[0] > 0:
data = data[gi(data)]
ns = np.repeat(*data.shape)
return np.array([
np.einsum('ni,ni->i',data,data),
np.einsum('ni->i',data),
ns,
ns,
])
else:
return sum((self._get_statistics(d) for d in data), self._empty_stats())
def _get_weighted_statistics(self,data,weights):
if isinstance(data,np.ndarray):
idx = ~np.isnan(data).any(1)
data = data[idx]
weights = weights[idx]
assert data.ndim == 2 and weights.ndim == 1 \
and data.shape[0] == weights.shape[0]
neff = np.repeat(weights.sum(),data.shape[1])
return np.array([weights.dot(data**2), weights.dot(data), neff, neff])
else:
return sum(
(self._get_weighted_statistics(d,w) for d, w in zip(data,weights)),
self._empty_stats())
def _empty_stats(self):
return np.zeros_like(self.natural_hypparam)
### Gibbs sampling
def resample(self,data=[],temperature=1.,stats=None):
stats = self._get_statistics(data) if stats is None else stats
alphas_n, betas_n, mu_n, nus_n = self._natural_to_standard(
self.natural_hypparam + stats / temperature)
D = mu_n.shape[0]
self.sigmas = 1/np.random.gamma(alphas_n,scale=1/betas_n)
self.mu = np.sqrt(self.sigmas/nus_n)*np.random.randn(D) + mu_n
assert not np.isnan(self.mu).any()
assert not np.isnan(self.sigmas).any()
# NOTE: next line is to use Gibbs sampling to initialize mean field
self.mf_mu = self.mu
assert self.sigmas.ndim == 1
return self
def copy_sample(self):
new = copy.copy(self)
new.mu = self.mu.copy()
new.sigmas = self.sigmas.copy()
return new
### max likelihood
def max_likelihood(self,data,weights=None):
if weights is None:
n, muhat, sumsq = self._get_statistics(data)
else:
n, muhat, sumsq = self._get_weighted_statistics_old(data,weights)
self.mu = muhat
self.sigmas = sumsq/n
return self
### Mean Field
@property
def mf_natural_hypparam(self):
return self._standard_to_natural(self.mf_alphas,self.mf_betas,self.mf_mu,self.mf_nus)
@mf_natural_hypparam.setter
def mf_natural_hypparam(self,natparam):
self.mf_alphas, self.mf_betas, self.mf_mu, self.mf_nus = \
self._natural_to_standard(natparam)
# NOTE: this part is for plotting
self.mu = self.mf_mu
self.sigmas = np.where(self.mf_alphas > 1,self.mf_betas / (self.mf_alphas - 1),100000)
def meanfieldupdate(self,data,weights):
self.mf_natural_hypparam = \
self.natural_hypparam + self._get_weighted_statistics(data,weights)
def meanfield_sgdstep(self,data,weights,prob,stepsize):
self.mf_natural_hypparam = \
(1-stepsize) * self.mf_natural_hypparam + stepsize * (
self.natural_hypparam
+ 1./prob * self._get_weighted_statistics(data,weights))
def get_vlb(self):
natparam_diff = self.natural_hypparam - self.mf_natural_hypparam
expected_stats = self._expected_statistics(
self.mf_alphas,self.mf_betas,self.mf_mu,self.mf_nus)
linear_term = sum(v1.dot(v2) for v1, v2 in zip(natparam_diff, expected_stats))
normalizer_term = \
self._log_Z(self.alphas_0,self.betas_0,self.mu_0,self.nus_0) \
- self._log_Z(self.mf_alphas,self.mf_betas,self.mf_mu,self.mf_nus)
return linear_term - normalizer_term - len(self.mf_mu)/2. * np.log(2*np.pi)
def expected_log_likelihood(self,x):
x = np.atleast_2d(x).reshape((-1,len(self.mf_mu)))
a,b,c,d = self._expected_statistics(
self.mf_alphas,self.mf_betas,self.mf_mu,self.mf_nus)
return (x**2).dot(a) + x.dot(b) + c.sum() + d.sum() \
- len(self.mf_mu)/2. * np.log(2*np.pi)
def _expected_statistics(self,alphas,betas,mu,nus):
return np.array([
-1./2 * alphas/betas,
mu * alphas/betas,
-1./2 * (1./nus + mu**2 * alphas/betas),
-1./2 * (np.log(betas) - special.digamma(alphas))])
def _log_Z(self,alphas,betas,mu,nus):
return (special.gammaln(alphas) - alphas*np.log(betas) - 1./2*np.log(nus)).sum()
# TODO meanfield
class DiagonalGaussianNonconjNIG(_GaussianBase,GibbsSampling):
'''
Product of normal priors over mu and product of gamma priors over sigmas.
Note that while the conjugate prior in DiagonalGaussian is of the form
p(mu,sigmas), this prior is of the form p(mu)p(sigmas). Therefore its
resample() update has to perform inner iterations.
The prior follows
mu ~ N(mu_0,diag(sigmas_0))
sigmas ~ InvGamma(alpha_0,beta_0) iid
'''
def __init__(self,mu=None,sigmas=None,mu_0=None,sigmas_0=None,alpha_0=None,beta_0=None,
niter=20):
self.mu_0, self.sigmas_0 = mu_0, sigmas_0
self.alpha_0, self.beta_0 = alpha_0, beta_0
self.niter = niter
if None in (mu,sigmas):
self.resample()
else:
self.mu, self.sigmas = mu, sigmas
@property
def hypparams(self):