Permalink
Browse files

pdfs.GammaPdf: implement sample() incl. tests

  • Loading branch information...
1 parent fb82839 commit 9360a1cb591eecfc1975bf914930bc9786c0f07f @strohel committed Aug 20, 2012
Showing with 16 additions and 0 deletions.
  1. +3 −0 pybayes/pdfs.py
  2. +13 −0 pybayes/tests/test_pdfs.py
View
@@ -678,6 +678,9 @@ def eval_log(self, x, cond = None):
return -math.lgamma(self.k) - self.k*math.log(self.theta) + (self.k - 1)*float('-inf')
return -math.lgamma(self.k) - self.k*math.log(self.theta) + (self.k - 1)*math.log(x[0]) - x[0]/self.theta
+ def sample(self, cond = None):
+ return random.gamma(self.k, self.theta, size=(1,))
+
class AbstractEmpPdf(Pdf):
r"""An abstraction of empirical probability density functions that provides common methods such
View
@@ -518,6 +518,19 @@ def test_eval_log(self):
self.assertApproxEqual(exp(self.gamma1.eval_log(x)), exp_results[i][0])
self.assertApproxEqual(exp(self.gamma2.eval_log(x)), exp_results[i][1])
+ @stochastic
+ def test_sample(self):
+ """Test GaussPdf.sample() mean and variance."""
+ N = 500 # number of samples
+ emp1 = pb.EmpPdf(self.gamma1.samples(N)) # Emipirical pdf computes sample mean and variance for us
+ emp2 = pb.EmpPdf(self.gamma2.samples(N)) # Emipirical pdf computes sample mean and variance for us
+
+ self.assertTrue(np.all(abs(emp1.mean() - self.gamma1.mean()) <= 0.4))
+ self.assertTrue(np.all(abs(emp2.mean() - self.gamma2.mean()) <= 0.3))
+
+ self.assertTrue(np.all(abs(emp1.variance() - self.gamma1.variance()) <= 2.2))
+ self.assertTrue(np.all(abs(emp2.variance() - self.gamma2.variance()) <= 1.3))
+
class TestEmpPdf(PbTestCase):
"""Test empirical pdf"""

0 comments on commit 9360a1c

Please sign in to comment.