forked from pymc-devs/pymc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiscrete.py
1836 lines (1514 loc) · 53.9 KB
/
discrete.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.
import aesara.tensor as at
import numpy as np
from aesara.tensor.random.basic import (
RandomVariable,
bernoulli,
betabinom,
binomial,
categorical,
geometric,
hypergeometric,
nbinom,
poisson,
)
from scipy import stats
import pymc3 as pm
from pymc3.aesaraf import floatX, intX, take_along_axis
from pymc3.distributions.dist_math import (
betaln,
binomln,
bound,
factln,
log_diff_normal_cdf,
logpow,
normal_lccdf,
normal_lcdf,
)
from pymc3.distributions.distribution import Discrete
from pymc3.distributions.logprob import _logcdf, _logp
from pymc3.math import log1mexp, logaddexp, logsumexp, sigmoid
__all__ = [
"Binomial",
"BetaBinomial",
"Bernoulli",
"DiscreteWeibull",
"Poisson",
"NegativeBinomial",
"Constant",
"ZeroInflatedPoisson",
"ZeroInflatedBinomial",
"ZeroInflatedNegativeBinomial",
"DiscreteUniform",
"Geometric",
"HyperGeometric",
"Categorical",
"OrderedLogistic",
"OrderedProbit",
]
class Binomial(Discrete):
R"""
Binomial log-likelihood.
The discrete probability distribution of the number of successes
in a sequence of n independent yes/no experiments, each of which
yields success with probability p.
The pmf of this distribution is
.. math:: f(x \mid n, p) = \binom{n}{x} p^x (1-p)^{n-x}
.. plot::
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
import arviz as az
plt.style.use('arviz-darkgrid')
x = np.arange(0, 22)
ns = [10, 17]
ps = [0.5, 0.7]
for n, p in zip(ns, ps):
pmf = st.binom.pmf(x, n, p)
plt.plot(x, pmf, '-o', label='n = {}, p = {}'.format(n, p))
plt.xlabel('x', fontsize=14)
plt.ylabel('f(x)', fontsize=14)
plt.legend(loc=1)
plt.show()
======== ==========================================
Support :math:`x \in \{0, 1, \ldots, n\}`
Mean :math:`n p`
Variance :math:`n p (1 - p)`
======== ==========================================
Parameters
----------
n: int
Number of Bernoulli trials (n >= 0).
p: float
Probability of success in each trial (0 < p < 1).
"""
rv_op = binomial
@classmethod
def dist(cls, n, p, *args, **kwargs):
n = at.as_tensor_variable(intX(n))
p = at.as_tensor_variable(floatX(p))
# mode = at.cast(tround(n * p), self.dtype)
return super().dist([n, p], **kwargs)
def logp(value, n, p):
r"""
Calculate log-probability of Binomial distribution at specified value.
Parameters
----------
value: numeric
Value(s) for which log-probability is calculated. If the log probabilities for multiple
values are desired the values must be provided in a numpy array or Aesara tensor
Returns
-------
TensorVariable
"""
return bound(
binomln(n, value) + logpow(p, value) + logpow(1 - p, n - value),
0 <= value,
value <= n,
0 <= p,
p <= 1,
)
def logcdf(value, n, p):
"""
Compute the log of the cumulative distribution function for Binomial distribution
at the specified value.
Parameters
----------
value: numeric or np.ndarray or aesara.tensor
Value(s) for which log CDF is calculated. If the log CDF for multiple
values are desired the values must be provided in a numpy array or Aesara tensor.
Returns
-------
TensorVariable
"""
value = at.floor(value)
return bound(
at.switch(
at.lt(value, n),
at.log(at.betainc(n - value, value + 1, 1 - p)),
0,
),
0 <= value,
0 < n,
0 <= p,
p <= 1,
)
class BetaBinomial(Discrete):
R"""
Beta-binomial log-likelihood.
Equivalent to binomial random variable with success probability
drawn from a beta distribution.
The pmf of this distribution is
.. math::
f(x \mid \alpha, \beta, n) =
\binom{n}{x}
\frac{B(x + \alpha, n - x + \beta)}{B(\alpha, \beta)}
.. plot::
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
from scipy import special
import arviz as az
plt.style.use('arviz-darkgrid')
def BetaBinom(a, b, n, x):
pmf = special.binom(n, x) * (special.beta(x+a, n-x+b) / special.beta(a, b))
return pmf
x = np.arange(0, 11)
alphas = [0.5, 1, 2.3]
betas = [0.5, 1, 2]
n = 10
for a, b in zip(alphas, betas):
pmf = BetaBinom(a, b, n, x)
plt.plot(x, pmf, '-o', label=r'$\alpha$ = {}, $\beta$ = {}, n = {}'.format(a, b, n))
plt.xlabel('x', fontsize=12)
plt.ylabel('f(x)', fontsize=12)
plt.ylim(0)
plt.legend(loc=9)
plt.show()
======== =================================================================
Support :math:`x \in \{0, 1, \ldots, n\}`
Mean :math:`n \dfrac{\alpha}{\alpha + \beta}`
Variance :math:`n \dfrac{\alpha \beta}{(\alpha+\beta)^2 (\alpha+\beta+1)}`
======== =================================================================
Parameters
----------
n: int
Number of Bernoulli trials (n >= 0).
alpha: float
alpha > 0.
beta: float
beta > 0.
"""
rv_op = betabinom
@classmethod
def dist(cls, alpha, beta, n, *args, **kwargs):
alpha = at.as_tensor_variable(floatX(alpha))
beta = at.as_tensor_variable(floatX(beta))
n = at.as_tensor_variable(intX(n))
return super().dist([n, alpha, beta], **kwargs)
def logp(value, n, alpha, beta):
r"""
Calculate log-probability of BetaBinomial distribution at specified value.
Parameters
----------
value: numeric
Value(s) for which log-probability is calculated. If the log probabilities for multiple
values are desired the values must be provided in a numpy array or Aesara tensor
Returns
-------
TensorVariable
"""
return bound(
binomln(n, value) + betaln(value + alpha, n - value + beta) - betaln(alpha, beta),
value >= 0,
value <= n,
alpha > 0,
beta > 0,
)
def logcdf(value, n, alpha, beta):
"""
Compute the log of the cumulative distribution function for BetaBinomial distribution
at the specified value.
Parameters
----------
value: numeric
Value for which log CDF is calculated.
Returns
-------
TensorVariable
"""
# logcdf can only handle scalar values at the moment
if np.ndim(value):
raise TypeError(
f"BetaBinomial.logcdf expects a scalar value but received a {np.ndim(value)}-dimensional object."
)
safe_lower = at.switch(at.lt(value, 0), value, 0)
return bound(
at.switch(
at.lt(value, n),
logsumexp(
BetaBinomial.logp(at.arange(safe_lower, value + 1), n, alpha, beta),
keepdims=False,
),
0,
),
0 <= value,
0 <= n,
0 < alpha,
0 < beta,
)
class Bernoulli(Discrete):
R"""Bernoulli log-likelihood
The Bernoulli distribution describes the probability of successes
(x=1) and failures (x=0).
The pmf of this distribution is
.. math:: f(x \mid p) = p^{x} (1-p)^{1-x}
.. plot::
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
import arviz as az
plt.style.use('arviz-darkgrid')
x = [0, 1]
for p in [0, 0.5, 0.8]:
pmf = st.bernoulli.pmf(x, p)
plt.plot(x, pmf, '-o', label='p = {}'.format(p))
plt.xlabel('x', fontsize=12)
plt.ylabel('f(x)', fontsize=12)
plt.ylim(0)
plt.legend(loc=9)
plt.show()
======== ======================
Support :math:`x \in \{0, 1\}`
Mean :math:`p`
Variance :math:`p (1 - p)`
======== ======================
Parameters
----------
p: float
Probability of success (0 < p < 1).
"""
rv_op = bernoulli
@classmethod
def dist(cls, p=None, logit_p=None, *args, **kwargs):
p = at.as_tensor_variable(floatX(p))
# mode = at.cast(tround(p), "int8")
return super().dist([p], **kwargs)
def logp(value, p):
r"""
Calculate log-probability of Bernoulli distribution at specified value.
Parameters
----------
value: numeric
Value(s) for which log-probability is calculated. If the log probabilities for multiple
values are desired the values must be provided in a numpy array or Aesara tensor
Returns
-------
TensorVariable
"""
# if self._is_logit:
# lp = at.switch(value, self._logit_p, -self._logit_p)
# return -log1pexp(-lp)
# else:
return bound(
at.switch(value, at.log(p), at.log(1 - p)),
value >= 0,
value <= 1,
p >= 0,
p <= 1,
)
def logcdf(value, p):
"""
Compute the log of the cumulative distribution function for Bernoulli distribution
at the specified value.
Parameters
----------
value: numeric or np.ndarray or aesara.tensor
Value(s) for which log CDF is calculated. If the log CDF for multiple
values are desired the values must be provided in a numpy array or Aesara tensor.
Returns
-------
TensorVariable
"""
return bound(
at.switch(
at.lt(value, 1),
at.log1p(-p),
0,
),
0 <= value,
0 <= p,
p <= 1,
)
def _distr_parameters_for_repr(self):
return ["p"]
class DiscreteWeibullRV(RandomVariable):
name = "discrete_weibull"
ndim_supp = 0
ndims_params = [0, 0]
dtype = "int64"
_print_name = ("dWeibull", "\\operatorname{dWeibull}")
@classmethod
def rng_fn(cls, rng, q, beta, size):
p = rng.uniform(size=size)
return np.ceil(np.power(np.log(1 - p) / np.log(q), 1.0 / beta)) - 1
discrete_weibull = DiscreteWeibullRV()
class DiscreteWeibull(Discrete):
R"""Discrete Weibull log-likelihood
The discrete Weibull distribution is a flexible model of count data that
can handle both over- and under-dispersion.
The pmf of this distribution is
.. math:: f(x \mid q, \beta) = q^{x^{\beta}} - q^{(x + 1)^{\beta}}
.. plot::
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
from scipy import special
import arviz as az
plt.style.use('arviz-darkgrid')
def DiscreteWeibull(q, b, x):
return q**(x**b) - q**((x + 1)**b)
x = np.arange(0, 10)
qs = [0.1, 0.9, 0.9]
betas = [0.3, 1.3, 3]
for q, b in zip(qs, betas):
pmf = DiscreteWeibull(q, b, x)
plt.plot(x, pmf, '-o', label=r'q = {}, $\beta$ = {}'.format(q, b))
plt.xlabel('x', fontsize=12)
plt.ylabel('f(x)', fontsize=12)
plt.ylim(0)
plt.legend(loc=1)
plt.show()
======== ======================
Support :math:`x \in \mathbb{N}_0`
Mean :math:`\mu = \sum_{x = 1}^{\infty} q^{x^{\beta}}`
Variance :math:`2 \sum_{x = 1}^{\infty} x q^{x^{\beta}} - \mu - \mu^2`
======== ======================
"""
rv_op = discrete_weibull
@classmethod
def dist(cls, q, beta, *args, **kwargs):
q = at.as_tensor_variable(floatX(q))
beta = at.as_tensor_variable(floatX(beta))
return super().dist([q, beta], **kwargs)
def logp(value, q, beta):
r"""
Calculate log-probability of DiscreteWeibull distribution at specified value.
Parameters
----------
value: numeric
Value(s) for which log-probability is calculated. If the log probabilities for multiple
values are desired the values must be provided in a numpy array or Aesara tensor
Returns
-------
TensorVariable
"""
return bound(
at.log(at.power(q, at.power(value, beta)) - at.power(q, at.power(value + 1, beta))),
0 <= value,
0 < q,
q < 1,
0 < beta,
)
def logcdf(value, q, beta):
"""
Compute the log of the cumulative distribution function for Discrete Weibull distribution
at the specified value.
Parameters
----------
value: numeric or np.ndarray or aesara.tensor
Value(s) for which log CDF is calculated. If the log CDF for multiple
values are desired the values must be provided in a numpy array or Aesara tensor.
Returns
-------
TensorVariable
"""
return bound(
at.log1p(-at.power(q, at.power(value + 1, beta))),
0 <= value,
0 < q,
q < 1,
0 < beta,
)
class Poisson(Discrete):
R"""
Poisson log-likelihood.
Often used to model the number of events occurring in a fixed period
of time when the times at which events occur are independent.
The pmf of this distribution is
.. math:: f(x \mid \mu) = \frac{e^{-\mu}\mu^x}{x!}
.. plot::
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
import arviz as az
plt.style.use('arviz-darkgrid')
x = np.arange(0, 15)
for m in [0.5, 3, 8]:
pmf = st.poisson.pmf(x, m)
plt.plot(x, pmf, '-o', label='$\mu$ = {}'.format(m))
plt.xlabel('x', fontsize=12)
plt.ylabel('f(x)', fontsize=12)
plt.ylim(0)
plt.legend(loc=1)
plt.show()
======== ==========================
Support :math:`x \in \mathbb{N}_0`
Mean :math:`\mu`
Variance :math:`\mu`
======== ==========================
Parameters
----------
mu: float
Expected number of occurrences during the given interval
(mu >= 0).
Notes
-----
The Poisson distribution can be derived as a limiting case of the
binomial distribution.
"""
rv_op = poisson
@classmethod
def dist(cls, mu, *args, **kwargs):
mu = at.as_tensor_variable(floatX(mu))
# mode = intX(at.floor(mu))
return super().dist([mu], *args, **kwargs)
def logp(value, mu):
r"""
Calculate log-probability of Poisson distribution at specified value.
Parameters
----------
value: numeric
Value(s) for which log-probability is calculated. If the log probabilities for multiple
values are desired the values must be provided in a numpy array or Aesara tensor
Returns
-------
TensorVariable
"""
log_prob = bound(logpow(mu, value) - factln(value) - mu, mu >= 0, value >= 0)
# Return zero when mu and value are both zero
return at.switch(at.eq(mu, 0) * at.eq(value, 0), 0, log_prob)
def logcdf(value, mu):
"""
Compute the log of the cumulative distribution function for Poisson distribution
at the specified value.
Parameters
----------
value: numeric or np.ndarray or aesara.tensor
Value(s) for which log CDF is calculated. If the log CDF for multiple
values are desired the values must be provided in a numpy array or Aesara tensor.
Returns
-------
TensorVariable
"""
value = at.floor(value)
# Avoid C-assertion when the gammaincc function is called with invalid values (#4340)
safe_mu = at.switch(at.lt(mu, 0), 0, mu)
safe_value = at.switch(at.lt(value, 0), 0, value)
return bound(
at.log(at.gammaincc(safe_value + 1, safe_mu)),
0 <= value,
0 <= mu,
)
class NegativeBinomial(Discrete):
R"""
Negative binomial log-likelihood.
The negative binomial distribution describes a Poisson random variable
whose rate parameter is gamma distributed.
The pmf of this distribution is
.. math::
f(x \mid \mu, \alpha) =
\binom{x + \alpha - 1}{x}
(\alpha/(\mu+\alpha))^\alpha (\mu/(\mu+\alpha))^x
.. plot::
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
from scipy import special
import arviz as az
plt.style.use('arviz-darkgrid')
def NegBinom(a, m, x):
pmf = special.binom(x + a - 1, x) * (a / (m + a))**a * (m / (m + a))**x
return pmf
x = np.arange(0, 22)
alphas = [0.9, 2, 4]
mus = [1, 2, 8]
for a, m in zip(alphas, mus):
pmf = NegBinom(a, m, x)
plt.plot(x, pmf, '-o', label=r'$\alpha$ = {}, $\mu$ = {}'.format(a, m))
plt.xlabel('x', fontsize=12)
plt.ylabel('f(x)', fontsize=12)
plt.legend(loc=1)
plt.show()
======== ==========================
Support :math:`x \in \mathbb{N}_0`
Mean :math:`\mu`
======== ==========================
The negative binomial distribution can be parametrized either in terms of mu or p,
and either in terms of alpha or n. The link between the parametrizations is given by
.. math::
\mu &= \frac{n(1-p)}{p} \\
\alpha &= n
Parameters
----------
mu: float
Poission distribution parameter (mu > 0).
alpha: float
Gamma distribution parameter (alpha > 0).
p: float
Alternative probability of success in each trial (0 < p < 1).
n: float
Alternative number of target success trials (n > 0)
"""
rv_op = nbinom
@classmethod
def dist(cls, mu=None, alpha=None, p=None, n=None, *args, **kwargs):
n, p = cls.get_n_p(mu=mu, alpha=alpha, p=p, n=n)
n = at.as_tensor_variable(floatX(n))
p = at.as_tensor_variable(floatX(p))
return super().dist([n, p], *args, **kwargs)
@classmethod
def get_n_p(cls, mu=None, alpha=None, p=None, n=None):
if n is None:
if alpha is not None:
n = alpha
else:
raise ValueError("Incompatible parametrization. Must specify either alpha or n.")
elif alpha is not None:
raise ValueError("Incompatible parametrization. Can't specify both alpha and n.")
if p is None:
if mu is not None:
p = n / (mu + n)
else:
raise ValueError("Incompatible parametrization. Must specify either mu or p.")
elif mu is not None:
raise ValueError("Incompatible parametrization. Can't specify both mu and p.")
return n, p
def logp(value, n, p):
r"""
Calculate log-probability of NegativeBinomial distribution at specified value.
Parameters
----------
value: numeric
Value(s) for which log-probability is calculated. If the log probabilities for multiple
values are desired the values must be provided in a numpy array or Aesara tensor
Returns
-------
TensorVariable
"""
alpha = n
mu = alpha * (1 - p) / p
negbinom = bound(
binomln(value + alpha - 1, value)
+ logpow(mu / (mu + alpha), value)
+ logpow(alpha / (mu + alpha), alpha),
value >= 0,
mu > 0,
alpha > 0,
)
# Return Poisson when alpha gets very large.
return at.switch(at.gt(alpha, 1e10), Poisson.logp(value, mu), negbinom)
def logcdf(value, n, p):
"""
Compute the log of the cumulative distribution function for NegativeBinomial distribution
at the specified value.
Parameters
----------
value: numeric or np.ndarray or aesara.tensor
Value(s) for which log CDF is calculated. If the log CDF for multiple
values are desired the values must be provided in a numpy array or Aesara tensor.
Returns
-------
TensorVariable
"""
return bound(
at.log(at.betainc(n, at.floor(value) + 1, p)),
0 <= value,
0 < n,
0 <= p,
p <= 1,
)
class Geometric(Discrete):
R"""
Geometric log-likelihood.
The probability that the first success in a sequence of Bernoulli
trials occurs on the x'th trial.
The pmf of this distribution is
.. math:: f(x \mid p) = p(1-p)^{x-1}
.. plot::
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
import arviz as az
plt.style.use('arviz-darkgrid')
x = np.arange(1, 11)
for p in [0.1, 0.25, 0.75]:
pmf = st.geom.pmf(x, p)
plt.plot(x, pmf, '-o', label='p = {}'.format(p))
plt.xlabel('x', fontsize=12)
plt.ylabel('f(x)', fontsize=12)
plt.legend(loc=1)
plt.show()
======== =============================
Support :math:`x \in \mathbb{N}_{>0}`
Mean :math:`\dfrac{1}{p}`
Variance :math:`\dfrac{1 - p}{p^2}`
======== =============================
Parameters
----------
p: float
Probability of success on an individual trial (0 < p <= 1).
"""
rv_op = geometric
@classmethod
def dist(cls, p, *args, **kwargs):
p = at.as_tensor_variable(floatX(p))
return super().dist([p], *args, **kwargs)
def logp(value, p):
r"""
Calculate log-probability of Geometric distribution at specified value.
Parameters
----------
value: numeric
Value(s) for which log-probability is calculated. If the log probabilities for multiple
values are desired the values must be provided in a numpy array or Aesara tensor
Returns
-------
TensorVariable
"""
return bound(
at.log(p) + logpow(1 - p, value - 1),
0 <= p,
p <= 1,
value >= 1,
)
def logcdf(value, p):
"""
Compute the log of the cumulative distribution function for Geometric distribution
at the specified value.
Parameters
----------
value: numeric or np.ndarray or aesara.tensor
Value(s) for which log CDF is calculated. If the log CDF for multiple
values are desired the values must be provided in a numpy array or Aesara tensor.
Returns
-------
TensorVariable
"""
return bound(
log1mexp(-at.log1p(-p) * value),
0 <= value,
0 <= p,
p <= 1,
)
class HyperGeometric(Discrete):
R"""
Discrete hypergeometric distribution.
The probability of :math:`x` successes in a sequence of :math:`n` bernoulli
trials taken without replacement from a population of :math:`N` objects,
containing :math:`k` good (or successful or Type I) objects.
The pmf of this distribution is
.. math:: f(x \mid N, n, k) = \frac{\binom{k}{x}\binom{N-k}{n-x}}{\binom{N}{n}}
.. plot::
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
import arviz as az
plt.style.use('arviz-darkgrid')
x = np.arange(1, 15)
N = 50
k = 10
for n in [20, 25]:
pmf = st.hypergeom.pmf(x, N, k, n)
plt.plot(x, pmf, '-o', label='n = {}'.format(n))
plt.plot(x, pmf, '-o', label='N = {}'.format(N))
plt.plot(x, pmf, '-o', label='k = {}'.format(k))
plt.xlabel('x', fontsize=12)
plt.ylabel('f(x)', fontsize=12)
plt.legend(loc=1)
plt.show()
======== =============================
Support :math:`x \in \left[\max(0, n - N + k), \min(k, n)\right]`
Mean :math:`\dfrac{nk}{N}`
Variance :math:`\dfrac{(N-n)nk(N-k)}{(N-1)N^2}`
======== =============================
Parameters
----------
N : integer
Total size of the population
k : integer
Number of successful individuals in the population
n : integer
Number of samples drawn from the population
"""
rv_op = hypergeometric
@classmethod
def dist(cls, N, k, n, *args, **kwargs):
good = at.as_tensor_variable(intX(k))
bad = at.as_tensor_variable(intX(N - k))
n = at.as_tensor_variable(intX(n))
return super().dist([good, bad, n], *args, **kwargs)
def logp(value, good, bad, n):
r"""
Calculate log-probability of HyperGeometric distribution at specified value.
Parameters
----------
value : numeric
Value(s) for which log-probability is calculated. If the log probabilities for multiple
values are desired the values must be provided in a numpy array or Aesara tensor
Returns
-------
TensorVariable
"""
tot = good + bad
result = (
betaln(good + 1, 1)
+ betaln(bad + 1, 1)
+ betaln(tot - n + 1, n + 1)
- betaln(value + 1, good - value + 1)
- betaln(n - value + 1, bad - n + value + 1)
- betaln(tot + 1, 1)
)
# value in [max(0, n - N + k), min(k, n)]
lower = at.switch(at.gt(n - tot + good, 0), n - tot + good, 0)
upper = at.switch(at.lt(good, n), good, n)
return bound(result, lower <= value, value <= upper)
def logcdf(value, good, bad, n):
"""
Compute the log of the cumulative distribution function for HyperGeometric distribution
at the specified value.
Parameters
----------
value: numeric
Value for which log CDF is calculated.
Returns
-------
TensorVariable
"""
# logcdf can only handle scalar values at the moment
if np.ndim(value):
raise TypeError(
f"HyperGeometric.logcdf expects a scalar value but received a {np.ndim(value)}-dimensional object."
)
N = good + bad
# TODO: Use lower upper in locgdf for smarter logsumexp?
safe_lower = at.switch(at.lt(value, 0), value, 0)
return bound(
at.switch(
at.lt(value, n),
logsumexp(
HyperGeometric.logp(at.arange(safe_lower, value + 1), good, bad, n),
keepdims=False,
),
0,
),
0 <= value,
0 < N,
0 <= good,
0 <= n,
good <= N,
n <= N,
)
class DiscreteUniformRV(RandomVariable):
name = "discrete_uniform"
ndim_supp = 0
ndims_params = [0, 0]
dtype = "int64"
_print_name = ("DiscreteUniform", "\\operatorname{DiscreteUniform}")
@classmethod
def rng_fn(cls, rng, lower, upper, size=None):
return stats.randint.rvs(lower, upper + 1, size=size, random_state=rng)
discrete_uniform = DiscreteUniformRV()
class DiscreteUniform(Discrete):
R"""
Discrete uniform distribution.
The pmf of this distribution is
.. math:: f(x \mid lower, upper) = \frac{1}{upper-lower+1}
.. plot::
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
import arviz as az
plt.style.use('arviz-darkgrid')
ls = [1, -2]
us = [6, 2]
for l, u in zip(ls, us):
x = np.arange(l, u+1)
pmf = [1.0 / (u - l + 1)] * len(x)
plt.plot(x, pmf, '-o', label='lower = {}, upper = {}'.format(l, u))
plt.xlabel('x', fontsize=12)
plt.ylabel('f(x)', fontsize=12)
plt.ylim(0, 0.4)