forked from pymc-devs/pymc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultivariate.py
executable file
·2086 lines (1771 loc) · 73.7 KB
/
multivariate.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
# Copyright 2020 The PyMC Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import warnings
import numpy as np
import scipy
import theano
import theano.tensor as tt
from scipy import linalg, stats
from theano.graph.basic import Apply
from theano.graph.op import Op, get_test_value
from theano.graph.utils import TestValueError
from theano.tensor.nlinalg import det, eigh, matrix_inverse, trace
from theano.tensor.slinalg import Cholesky
import pymc3 as pm
from pymc3.distributions import transforms
from pymc3.distributions.continuous import ChiSquared, Normal
from pymc3.distributions.dist_math import bound, factln, logpow
from pymc3.distributions.distribution import (
Continuous,
Discrete,
_DrawValuesContext,
draw_values,
generate_samples,
)
from pymc3.distributions.shape_utils import broadcast_dist_samples_to, to_tuple
from pymc3.distributions.special import gammaln, multigammaln
from pymc3.exceptions import ShapeError
from pymc3.math import kron_diag, kron_dot, kron_solve_lower, kronecker
from pymc3.model import Deterministic
from pymc3.theanof import floatX, intX
__all__ = [
"MvNormal",
"MvStudentT",
"Dirichlet",
"Multinomial",
"DirichletMultinomial",
"Wishart",
"WishartBartlett",
"LKJCorr",
"LKJCholeskyCov",
"MatrixNormal",
"KroneckerNormal",
]
class _QuadFormBase(Continuous):
def __init__(self, mu=None, cov=None, chol=None, tau=None, lower=True, *args, **kwargs):
super().__init__(*args, **kwargs)
if len(self.shape) > 2:
raise ValueError("Only 1 or 2 dimensions are allowed.")
if chol is not None and not lower:
chol = chol.T
if len([i for i in [tau, cov, chol] if i is not None]) != 1:
raise ValueError(
"Incompatible parameterization. Specify exactly one of tau, cov, or chol."
)
self.mu = mu = tt.as_tensor_variable(mu)
self.solve_lower = tt.slinalg.Solve(A_structure="lower_triangular")
# Step methods and advi do not catch LinAlgErrors at the
# moment. We work around that by using a cholesky op
# that returns a nan as first entry instead of raising
# an error.
cholesky = Cholesky(lower=True, on_error="nan")
if cov is not None:
self.k = cov.shape[0]
self._cov_type = "cov"
cov = tt.as_tensor_variable(cov)
if cov.ndim != 2:
raise ValueError("cov must be two dimensional.")
self.chol_cov = cholesky(cov)
self.cov = cov
self._n = self.cov.shape[-1]
elif tau is not None:
self.k = tau.shape[0]
self._cov_type = "tau"
tau = tt.as_tensor_variable(tau)
if tau.ndim != 2:
raise ValueError("tau must be two dimensional.")
self.chol_tau = cholesky(tau)
self.tau = tau
self._n = self.tau.shape[-1]
else:
self.k = chol.shape[0]
self._cov_type = "chol"
if chol.ndim != 2:
raise ValueError("chol must be two dimensional.")
self.chol_cov = tt.as_tensor_variable(chol)
self._n = self.chol_cov.shape[-1]
def _quaddist(self, value):
"""Compute (x - mu).T @ Sigma^-1 @ (x - mu) and the logdet of Sigma."""
mu = self.mu
if value.ndim > 2 or value.ndim == 0:
raise ValueError("Invalid dimension for value: %s" % value.ndim)
if value.ndim == 1:
onedim = True
value = value[None, :]
else:
onedim = False
delta = value - mu
if self._cov_type == "cov":
# Use this when Theano#5908 is released.
# return MvNormalLogp()(self.cov, delta)
dist, logdet, ok = self._quaddist_cov(delta)
elif self._cov_type == "tau":
dist, logdet, ok = self._quaddist_tau(delta)
else:
dist, logdet, ok = self._quaddist_chol(delta)
if onedim:
return dist[0], logdet, ok
return dist, logdet, ok
def _quaddist_chol(self, delta):
chol_cov = self.chol_cov
diag = tt.nlinalg.diag(chol_cov)
# Check if the covariance matrix is positive definite.
ok = tt.all(diag > 0)
# If not, replace the diagonal. We return -inf later, but
# need to prevent solve_lower from throwing an exception.
chol_cov = tt.switch(ok, chol_cov, 1)
delta_trans = self.solve_lower(chol_cov, delta.T).T
quaddist = (delta_trans ** 2).sum(axis=-1)
logdet = tt.sum(tt.log(diag))
return quaddist, logdet, ok
def _quaddist_cov(self, delta):
return self._quaddist_chol(delta)
def _quaddist_tau(self, delta):
chol_tau = self.chol_tau
diag = tt.nlinalg.diag(chol_tau)
# Check if the precision matrix is positive definite.
ok = tt.all(diag > 0)
# If not, replace the diagonal. We return -inf later, but
# need to prevent solve_lower from throwing an exception.
chol_tau = tt.switch(ok, chol_tau, 1)
delta_trans = tt.dot(delta, chol_tau)
quaddist = (delta_trans ** 2).sum(axis=-1)
logdet = -tt.sum(tt.log(diag))
return quaddist, logdet, ok
def _cov_param_for_repr(self):
if self._cov_type == "chol":
return "chol_cov"
else:
return self._cov_type
class MvNormal(_QuadFormBase):
R"""
Multivariate normal log-likelihood.
.. math::
f(x \mid \pi, T) =
\frac{|T|^{1/2}}{(2\pi)^{k/2}}
\exp\left\{ -\frac{1}{2} (x-\mu)^{\prime} T (x-\mu) \right\}
======== ==========================
Support :math:`x \in \mathbb{R}^k`
Mean :math:`\mu`
Variance :math:`T^{-1}`
======== ==========================
Parameters
----------
mu: array
Vector of means.
cov: array
Covariance matrix. Exactly one of cov, tau, or chol is needed.
tau: array
Precision matrix. Exactly one of cov, tau, or chol is needed.
chol: array
Cholesky decomposition of covariance matrix. Exactly one of cov,
tau, or chol is needed.
lower: bool, default=True
Whether chol is the lower tridiagonal cholesky factor.
Examples
--------
Define a multivariate normal variable for a given covariance
matrix::
cov = np.array([[1., 0.5], [0.5, 2]])
mu = np.zeros(2)
vals = pm.MvNormal('vals', mu=mu, cov=cov, shape=(5, 2))
Most of the time it is preferable to specify the cholesky
factor of the covariance instead. For example, we could
fit a multivariate outcome like this (see the docstring
of `LKJCholeskyCov` for more information about this)::
mu = np.zeros(3)
true_cov = np.array([[1.0, 0.5, 0.1],
[0.5, 2.0, 0.2],
[0.1, 0.2, 1.0]])
data = np.random.multivariate_normal(mu, true_cov, 10)
sd_dist = pm.Exponential.dist(1.0, shape=3)
chol, corr, stds = pm.LKJCholeskyCov('chol_cov', n=3, eta=2,
sd_dist=sd_dist, compute_corr=True)
vals = pm.MvNormal('vals', mu=mu, chol=chol, observed=data)
For unobserved values it can be better to use a non-centered
parametrization::
sd_dist = pm.Exponential.dist(1.0, shape=3)
chol, _, _ = pm.LKJCholeskyCov('chol_cov', n=3, eta=2,
sd_dist=sd_dist, compute_corr=True)
vals_raw = pm.Normal('vals_raw', mu=0, sigma=1, shape=(5, 3))
vals = pm.Deterministic('vals', tt.dot(chol, vals_raw.T).T)
"""
def __init__(self, mu, cov=None, tau=None, chol=None, lower=True, *args, **kwargs):
super().__init__(mu=mu, cov=cov, tau=tau, chol=chol, lower=lower, *args, **kwargs)
self.mean = self.median = self.mode = self.mu = self.mu
def random(self, point=None, size=None):
"""
Draw random values from Multivariate Normal distribution.
Parameters
----------
point: dict, optional
Dict of variable values on which random values are to be
conditioned (uses default point if not specified).
size: int, optional
Desired size of random sample (returns one sample if not
specified).
Returns
-------
array
"""
size = to_tuple(size)
param_attribute = getattr(self, "chol_cov" if self._cov_type == "chol" else self._cov_type)
mu, param = draw_values([self.mu, param_attribute], point=point, size=size)
dist_shape = to_tuple(self.shape)
output_shape = size + dist_shape
# Simple, there can be only be 1 batch dimension, only available from `mu`.
# Insert it into `param` before events, if there is a sample shape in front.
if param.ndim > 2 and dist_shape[:-1]:
param = param.reshape(size + (1,) + param.shape[-2:])
mu = broadcast_dist_samples_to(to_shape=output_shape, samples=[mu], size=size)[0]
param = np.broadcast_to(param, shape=output_shape + dist_shape[-1:])
assert mu.shape == output_shape
assert param.shape == output_shape + dist_shape[-1:]
if self._cov_type == "cov":
chol = np.linalg.cholesky(param)
elif self._cov_type == "chol":
chol = param
else: # tau -> chol -> swapaxes (chol, -1, -2) -> inv ...
lower_chol = np.linalg.cholesky(param)
upper_chol = np.swapaxes(lower_chol, -1, -2)
chol = np.linalg.inv(upper_chol)
standard_normal = np.random.standard_normal(output_shape)
return mu + np.einsum("...ij,...j->...i", chol, standard_normal)
def logp(self, value):
"""
Calculate log-probability of Multivariate Normal distribution
at specified value.
Parameters
----------
value: numeric
Value for which log-probability is calculated.
Returns
-------
TensorVariable
"""
quaddist, logdet, ok = self._quaddist(value)
k = floatX(value.shape[-1])
norm = -0.5 * k * pm.floatX(np.log(2 * np.pi))
return bound(norm - 0.5 * quaddist - logdet, ok)
def _distr_parameters_for_repr(self):
return ["mu", self._cov_param_for_repr()]
class MvStudentT(_QuadFormBase):
R"""
Multivariate Student-T log-likelihood.
.. math::
f(\mathbf{x}| \nu,\mu,\Sigma) =
\frac
{\Gamma\left[(\nu+p)/2\right]}
{\Gamma(\nu/2)\nu^{p/2}\pi^{p/2}
\left|{\Sigma}\right|^{1/2}
\left[
1+\frac{1}{\nu}
({\mathbf x}-{\mu})^T
{\Sigma}^{-1}({\mathbf x}-{\mu})
\right]^{-(\nu+p)/2}}
======== =============================================
Support :math:`x \in \mathbb{R}^p`
Mean :math:`\mu` if :math:`\nu > 1` else undefined
Variance :math:`\frac{\nu}{\mu-2}\Sigma`
if :math:`\nu>2` else undefined
======== =============================================
Parameters
----------
nu: int
Degrees of freedom.
Sigma: matrix
Covariance matrix. Use `cov` in new code.
mu: array
Vector of means.
cov: matrix
The covariance matrix.
tau: matrix
The precision matrix.
chol: matrix
The cholesky factor of the covariance matrix.
lower: bool, default=True
Whether the cholesky fatcor is given as a lower triangular matrix.
"""
def __init__(
self, nu, Sigma=None, mu=None, cov=None, tau=None, chol=None, lower=True, *args, **kwargs
):
if Sigma is not None:
if cov is not None:
raise ValueError("Specify only one of cov and Sigma")
cov = Sigma
super().__init__(mu=mu, cov=cov, tau=tau, chol=chol, lower=lower, *args, **kwargs)
self.nu = nu = tt.as_tensor_variable(nu)
self.mean = self.median = self.mode = self.mu = self.mu
def random(self, point=None, size=None):
"""
Draw random values from Multivariate Student's T distribution.
Parameters
----------
point: dict, optional
Dict of variable values on which random values are to be
conditioned (uses default point if not specified).
size: int, optional
Desired size of random sample (returns one sample if not
specified).
Returns
-------
array
"""
with _DrawValuesContext():
nu, mu = draw_values([self.nu, self.mu], point=point, size=size)
if self._cov_type == "cov":
(cov,) = draw_values([self.cov], point=point, size=size)
dist = MvNormal.dist(mu=np.zeros_like(mu), cov=cov, shape=self.shape)
elif self._cov_type == "tau":
(tau,) = draw_values([self.tau], point=point, size=size)
dist = MvNormal.dist(mu=np.zeros_like(mu), tau=tau, shape=self.shape)
else:
(chol,) = draw_values([self.chol_cov], point=point, size=size)
dist = MvNormal.dist(mu=np.zeros_like(mu), chol=chol, shape=self.shape)
samples = dist.random(point, size)
chi2_samples = np.random.chisquare(nu, size)
# Add distribution shape to chi2 samples
chi2_samples = chi2_samples.reshape(chi2_samples.shape + (1,) * len(self.shape))
return (samples / np.sqrt(chi2_samples / nu)) + mu
def logp(self, value):
"""
Calculate log-probability of Multivariate Student's T distribution
at specified value.
Parameters
----------
value: numeric
Value for which log-probability is calculated.
Returns
-------
TensorVariable
"""
quaddist, logdet, ok = self._quaddist(value)
k = floatX(value.shape[-1])
norm = (
gammaln((self.nu + k) / 2.0)
- gammaln(self.nu / 2.0)
- 0.5 * k * floatX(np.log(self.nu * np.pi))
)
inner = -(self.nu + k) / 2.0 * tt.log1p(quaddist / self.nu)
return bound(norm + inner - logdet, ok)
def _distr_parameters_for_repr(self):
return ["mu", "nu", self._cov_param_for_repr()]
class Dirichlet(Continuous):
R"""
Dirichlet log-likelihood.
.. math::
f(\mathbf{x}|\mathbf{a}) =
\frac{\Gamma(\sum_{i=1}^k a_i)}{\prod_{i=1}^k \Gamma(a_i)}
\prod_{i=1}^k x_i^{a_i - 1}
======== ===============================================
Support :math:`x_i \in (0, 1)` for :math:`i \in \{1, \ldots, K\}`
such that :math:`\sum x_i = 1`
Mean :math:`\dfrac{a_i}{\sum a_i}`
Variance :math:`\dfrac{a_i - \sum a_0}{a_0^2 (a_0 + 1)}`
where :math:`a_0 = \sum a_i`
======== ===============================================
Parameters
----------
a: array
Concentration parameters (a > 0).
"""
def __init__(self, a, transform=transforms.stick_breaking, *args, **kwargs):
if kwargs.get("shape") is None:
warnings.warn(
(
"Shape not explicitly set. "
"Please, set the value using the `shape` keyword argument. "
"Using the test value to infer the shape."
),
DeprecationWarning,
)
try:
kwargs["shape"] = np.shape(get_test_value(a))
except TestValueError:
pass
super().__init__(transform=transform, *args, **kwargs)
self.a = a = tt.as_tensor_variable(a)
self.mean = a / tt.sum(a)
self.mode = tt.switch(tt.all(a > 1), (a - 1) / tt.sum(a - 1), np.nan)
def random(self, point=None, size=None):
"""
Draw random values from Dirichlet distribution.
Parameters
----------
point: dict, optional
Dict of variable values on which random values are to be
conditioned (uses default point if not specified).
size: int, optional
Desired size of random sample (returns one sample if not
specified).
Returns
-------
array
"""
a = draw_values([self.a], point=point, size=size)[0]
output_shape = to_tuple(size) + to_tuple(self.shape)
a = broadcast_dist_samples_to(to_shape=output_shape, samples=[a], size=size)[0]
samples = stats.gamma.rvs(a=a, size=output_shape)
samples = samples / samples.sum(-1, keepdims=True)
return samples
def logp(self, value):
"""
Calculate log-probability of Dirichlet distribution
at specified value.
Parameters
----------
value: numeric
Value for which log-probability is calculated.
Returns
-------
TensorVariable
"""
a = self.a
# only defined for sum(value) == 1
return bound(
tt.sum(logpow(value, a - 1) - gammaln(a), axis=-1) + gammaln(tt.sum(a, axis=-1)),
tt.all(value >= 0),
tt.all(value <= 1),
np.logical_not(a.broadcastable),
tt.all(a > 0),
broadcast_conditions=False,
)
def _distr_parameters_for_repr(self):
return ["a"]
class Multinomial(Discrete):
R"""
Multinomial log-likelihood.
Generalizes binomial distribution, but instead of each trial resulting
in "success" or "failure", each one results in exactly one of some
fixed finite number k of possible outcomes over n independent trials.
'x[i]' indicates the number of times outcome number i was observed
over the n trials.
.. math::
f(x \mid n, p) = \frac{n!}{\prod_{i=1}^k x_i!} \prod_{i=1}^k p_i^{x_i}
========== ===========================================
Support :math:`x \in \{0, 1, \ldots, n\}` such that
:math:`\sum x_i = n`
Mean :math:`n p_i`
Variance :math:`n p_i (1 - p_i)`
Covariance :math:`-n p_i p_j` for :math:`i \ne j`
========== ===========================================
Parameters
----------
n: int or array
Number of trials (n > 0). If n is an array its shape must be (N,) with
N = p.shape[0]
p: one- or two-dimensional array
Probability of each one of the different outcomes. Elements must
be non-negative and sum to 1 along the last axis. They will be
automatically rescaled otherwise.
"""
def __init__(self, n, p, *args, **kwargs):
super().__init__(*args, **kwargs)
p = p / tt.sum(p, axis=-1, keepdims=True)
if len(self.shape) > 1:
self.n = tt.shape_padright(n)
self.p = p if p.ndim > 1 else tt.shape_padleft(p)
else:
# n is a scalar, p is a 1d array
self.n = tt.as_tensor_variable(n)
self.p = tt.as_tensor_variable(p)
self.mean = self.n * self.p
mode = tt.cast(tt.round(self.mean), "int32")
diff = self.n - tt.sum(mode, axis=-1, keepdims=True)
inc_bool_arr = tt.abs_(diff) > 0
mode = tt.inc_subtensor(mode[inc_bool_arr.nonzero()], diff[inc_bool_arr.nonzero()])
self.mode = mode
def _random(self, n, p, size=None, raw_size=None):
original_dtype = p.dtype
# Set float type to float64 for numpy. This change is related to numpy issue #8317 (https://github.com/numpy/numpy/issues/8317)
p = p.astype("float64")
# Now, re-normalize all of the values in float64 precision. This is done inside the conditionals
p /= np.sum(p, axis=-1, keepdims=True)
# Thanks to the default shape handling done in generate_values, the last
# axis of n is a dummy axis that allows it to broadcast well with p
n = np.broadcast_to(n, size)
p = np.broadcast_to(p, size)
n = n[..., 0]
# np.random.multinomial needs `n` to be a scalar int and `p` a
# sequence so we semi flatten them and iterate over them
size_ = to_tuple(raw_size)
if p.ndim > len(size_) and p.shape[: len(size_)] == size_:
# p and n have the size_ prepend so we don't need it in np.random
n_ = n.reshape([-1])
p_ = p.reshape([-1, p.shape[-1]])
samples = np.array([np.random.multinomial(nn, pp) for nn, pp in zip(n_, p_)])
samples = samples.reshape(p.shape)
else:
# p and n don't have the size prepend
n_ = n.reshape([-1])
p_ = p.reshape([-1, p.shape[-1]])
samples = np.array(
[np.random.multinomial(nn, pp, size=size_) for nn, pp in zip(n_, p_)]
)
samples = np.moveaxis(samples, 0, -1)
samples = samples.reshape(size + p.shape)
# We cast back to the original dtype
return samples.astype(original_dtype)
def random(self, point=None, size=None):
"""
Draw random values from Multinomial distribution.
Parameters
----------
point: dict, optional
Dict of variable values on which random values are to be
conditioned (uses default point if not specified).
size: int, optional
Desired size of random sample (returns one sample if not
specified).
Returns
-------
array
"""
n, p = draw_values([self.n, self.p], point=point, size=size)
samples = generate_samples(
self._random,
n,
p,
dist_shape=self.shape,
not_broadcast_kwargs={"raw_size": size},
size=size,
)
return samples
def logp(self, x):
"""
Calculate log-probability of Multinomial distribution
at specified value.
Parameters
----------
x: numeric
Value for which log-probability is calculated.
Returns
-------
TensorVariable
"""
n = self.n
p = self.p
return bound(
factln(n) + tt.sum(-factln(x) + logpow(p, x), axis=-1, keepdims=True),
tt.all(x >= 0),
tt.all(tt.eq(tt.sum(x, axis=-1, keepdims=True), n)),
tt.all(p <= 1),
tt.all(tt.eq(tt.sum(p, axis=-1), 1)),
tt.all(tt.ge(n, 0)),
broadcast_conditions=False,
)
class DirichletMultinomial(Discrete):
R"""Dirichlet Multinomial log-likelihood.
Dirichlet mixture of Multinomials distribution, with a marginalized PMF.
.. math::
f(x \mid n, a) = \frac{\Gamma(n + 1)\Gamma(\sum a_k)}
{\Gamma(\n + \sum a_k)}
\prod_{k=1}^K
\frac{\Gamma(x_k + a_k)}
{\Gamma(x_k + 1)\Gamma(a_k)}
========== ===========================================
Support :math:`x \in \{0, 1, \ldots, n\}` such that
:math:`\sum x_i = n`
Mean :math:`n \frac{a_i}{\sum{a_k}}`
========== ===========================================
Parameters
----------
n : int or array
Total counts in each replicate. If n is an array its shape must be (N,)
with N = a.shape[0]
a : one- or two-dimensional array
Dirichlet parameter. Elements must be strictly positive.
The number of categories is given by the length of the last axis.
shape : integer tuple
Describes shape of distribution. For example if n=array([5, 10]), and
a=array([1, 1, 1]), shape should be (2, 3).
"""
def __init__(self, n, a, shape, *args, **kwargs):
super().__init__(shape=shape, defaults=("_defaultval",), *args, **kwargs)
n = intX(n)
a = floatX(a)
if len(self.shape) > 1:
self.n = tt.shape_padright(n)
self.a = tt.as_tensor_variable(a) if a.ndim > 1 else tt.shape_padleft(a)
else:
# n is a scalar, p is a 1d array
self.n = tt.as_tensor_variable(n)
self.a = tt.as_tensor_variable(a)
p = self.a / self.a.sum(-1, keepdims=True)
self.mean = self.n * p
# Mode is only an approximation. Exact computation requires a complex
# iterative algorithm as described in https://doi.org/10.1016/j.spl.2009.09.013
mode = tt.cast(tt.round(self.mean), "int32")
diff = self.n - tt.sum(mode, axis=-1, keepdims=True)
inc_bool_arr = tt.abs_(diff) > 0
mode = tt.inc_subtensor(mode[inc_bool_arr.nonzero()], diff[inc_bool_arr.nonzero()])
self._defaultval = mode
def _random(self, n, a, size=None):
# numpy will cast dirichlet and multinomial samples to float64 by default
original_dtype = a.dtype
# Thanks to the default shape handling done in generate_values, the last
# axis of n is a dummy axis that allows it to broadcast well with `a`
n = np.broadcast_to(n, size)
a = np.broadcast_to(a, size)
n = n[..., 0]
# np.random.multinomial needs `n` to be a scalar int and `a` a
# sequence so we semi flatten them and iterate over them
n_ = n.reshape([-1])
a_ = a.reshape([-1, a.shape[-1]])
p_ = np.array([np.random.dirichlet(aa) for aa in a_])
samples = np.array([np.random.multinomial(nn, pp) for nn, pp in zip(n_, p_)])
samples = samples.reshape(a.shape)
# We cast back to the original dtype
return samples.astype(original_dtype)
def random(self, point=None, size=None):
"""
Draw random values from Dirichlet-Multinomial distribution.
Parameters
----------
point: dict, optional
Dict of variable values on which random values are to be
conditioned (uses default point if not specified).
size: int, optional
Desired size of random sample (returns one sample if not
specified).
Returns
-------
array
"""
n, a = draw_values([self.n, self.a], point=point, size=size)
samples = generate_samples(
self._random,
n,
a,
dist_shape=self.shape,
size=size,
)
# If distribution is initialized with .dist(), valid init shape is not asserted.
# Under normal use in a model context valid init shape is asserted at start.
expected_shape = to_tuple(size) + to_tuple(self.shape)
sample_shape = tuple(samples.shape)
if sample_shape != expected_shape:
raise ShapeError(
f"Expected sample shape was {expected_shape} but got {sample_shape}. "
"This may reflect an invalid initialization shape."
)
return samples
def logp(self, value):
"""
Calculate log-probability of DirichletMultinomial distribution
at specified value.
Parameters
----------
value: integer array
Value for which log-probability is calculated.
Returns
-------
TensorVariable
"""
a = self.a
n = self.n
sum_a = a.sum(axis=-1, keepdims=True)
const = (gammaln(n + 1) + gammaln(sum_a)) - gammaln(n + sum_a)
series = gammaln(value + a) - (gammaln(value + 1) + gammaln(a))
result = const + series.sum(axis=-1, keepdims=True)
# Bounds checking to confirm parameters and data meet all constraints
# and that each observation value_i sums to n_i.
return bound(
result,
tt.all(tt.ge(value, 0)),
tt.all(tt.gt(a, 0)),
tt.all(tt.ge(n, 0)),
tt.all(tt.eq(value.sum(axis=-1, keepdims=True), n)),
broadcast_conditions=False,
)
def _distr_parameters_for_repr(self):
return ["n", "a"]
def posdef(AA):
try:
linalg.cholesky(AA)
return 1
except linalg.LinAlgError:
return 0
class PosDefMatrix(Op):
"""
Check if input is positive definite. Input should be a square matrix.
"""
# Properties attribute
__props__ = ()
# Compulsory if itypes and otypes are not defined
def make_node(self, x):
x = tt.as_tensor_variable(x)
assert x.ndim == 2
o = tt.TensorType(dtype="int8", broadcastable=[])()
return Apply(self, [x], [o])
# Python implementation:
def perform(self, node, inputs, outputs):
(x,) = inputs
(z,) = outputs
try:
z[0] = np.array(posdef(x), dtype="int8")
except Exception:
pm._log.exception("Failed to check if %s positive definite", x)
raise
def infer_shape(self, fgraph, node, shapes):
return [[]]
def grad(self, inp, grads):
(x,) = inp
return [x.zeros_like(theano.config.floatX)]
def __str__(self):
return "MatrixIsPositiveDefinite"
matrix_pos_def = PosDefMatrix()
class Wishart(Continuous):
R"""
Wishart log-likelihood.
The Wishart distribution is the probability distribution of the
maximum-likelihood estimator (MLE) of the precision matrix of a
multivariate normal distribution. If V=1, the distribution is
identical to the chi-square distribution with nu degrees of
freedom.
.. math::
f(X \mid nu, T) =
\frac{{\mid T \mid}^{nu/2}{\mid X \mid}^{(nu-k-1)/2}}{2^{nu k/2}
\Gamma_p(nu/2)} \exp\left\{ -\frac{1}{2} Tr(TX) \right\}
where :math:`k` is the rank of :math:`X`.
======== =========================================
Support :math:`X(p x p)` positive definite matrix
Mean :math:`nu V`
Variance :math:`nu (v_{ij}^2 + v_{ii} v_{jj})`
======== =========================================
Parameters
----------
nu: int
Degrees of freedom, > 0.
V: array
p x p positive definite matrix.
Notes
-----
This distribution is unusable in a PyMC3 model. You should instead
use LKJCholeskyCov or LKJCorr.
"""
def __init__(self, nu, V, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn(
"The Wishart distribution can currently not be used "
"for MCMC sampling. The probability of sampling a "
"symmetric matrix is basically zero. Instead, please "
"use LKJCholeskyCov or LKJCorr. For more information "
"on the issues surrounding the Wishart see here: "
"https://github.com/pymc-devs/pymc3/issues/538.",
UserWarning,
)
self.nu = nu = tt.as_tensor_variable(nu)
self.p = p = tt.as_tensor_variable(V.shape[0])
self.V = V = tt.as_tensor_variable(V)
self.mean = nu * V
self.mode = tt.switch(tt.ge(nu, p + 1), (nu - p - 1) * V, np.nan)
def random(self, point=None, size=None):
"""
Draw random values from Wishart distribution.
Parameters
----------
point: dict, optional
Dict of variable values on which random values are to be
conditioned (uses default point if not specified).
size: int, optional
Desired size of random sample (returns one sample if not
specified).
Returns
-------
array
"""
nu, V = draw_values([self.nu, self.V], point=point, size=size)
size = 1 if size is None else size
return generate_samples(stats.wishart.rvs, nu.item(), V, broadcast_shape=(size,))
def logp(self, X):
"""
Calculate log-probability of Wishart distribution
at specified value.
Parameters
----------
X: numeric
Value for which log-probability is calculated.
Returns
-------
TensorVariable
"""
nu = self.nu
p = self.p
V = self.V
IVI = det(V)
IXI = det(X)
return bound(
(
(nu - p - 1) * tt.log(IXI)
- trace(matrix_inverse(V).dot(X))
- nu * p * tt.log(2)
- nu * tt.log(IVI)
- 2 * multigammaln(nu / 2.0, p)
)
/ 2,
matrix_pos_def(X),
tt.eq(X, X.T),
nu > (p - 1),
broadcast_conditions=False,
)
def WishartBartlett(name, S, nu, is_cholesky=False, return_cholesky=False, testval=None):
R"""
Bartlett decomposition of the Wishart distribution. As the Wishart
distribution requires the matrix to be symmetric positive semi-definite
it is impossible for MCMC to ever propose acceptable matrices.
Instead, we can use the Barlett decomposition which samples a lower
diagonal matrix. Specifically: