Skip to content

Commit 2eafe29

Browse files
axchtensorflower-gardener
authored andcommitted
Fix numeric error for high-success BetaBinomial.
Specifically, BetaBinomial(concentration0=small, total_counts=n).log_prob(n) used to incur a catastrophic cancellation between the total counts and the count of successes, which lost accuracy in the concentration0 parameter. By computing the count of failures before adding the concentration we cover the case when there are zero failures without losing precision. PiperOrigin-RevId: 384326009
1 parent bc93267 commit 2eafe29

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

tensorflow_probability/python/distributions/beta_binomial.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ def _sample_n(self, n, seed=None):
269269
def _log_prob(self, counts):
270270
n, c1, c0 = self._params_list_as_tensors()
271271
return (_log_combinations(n, counts)
272-
+ tfp_math.lbeta(c1 + counts, n + c0 - counts)
272+
+ tfp_math.lbeta(c1 + counts, (n - counts) + c0)
273273
- tfp_math.lbeta(c1, c0))
274274

275275
@distribution_util.AppendDocstring(_beta_binomial_sample_note)

tensorflow_probability/python/distributions/beta_binomial_test.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,12 @@ def testSampleCornerConcentrations(self):
149149
total_count=50.)
150150
self.assertAllEqual(d.sample(10, seed=seed_stream()), [[0, 50]] * 10)
151151

152+
def testLogProbCornerCase(self):
153+
d = tfd.BetaBinomial(
154+
concentration0=2e-8, concentration1=1.0, total_count=1.0)
155+
# Numerically 0 is better than numerically +inf
156+
self.assertAllEqual(d.log_prob(1.0), 0.0)
157+
152158
def testEmpiricalCdfAgainstDirichletMultinomial(self):
153159
# This test is too slow for Eager mode.
154160
if tf.executing_eagerly():

0 commit comments

Comments
 (0)