Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Marginal Util Function #778

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion edward/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from edward.util import check_data, check_latent_vars, copy, dot, \
get_ancestors, get_blanket, get_children, get_control_variate_coef, \
get_descendants, get_parents, get_session, get_siblings, get_variables, \
Progbar, random_variables, rbf, set_seed, to_simplex, transform
marginal, Progbar, random_variables, rbf, set_seed, to_simplex, transform
from edward.version import __version__, VERSION

from tensorflow.python.util.all_util import remove_undocumented
Expand Down Expand Up @@ -74,6 +74,7 @@
'get_session',
'get_siblings',
'get_variables',
'marginal',
'Progbar',
'random_variables',
'rbf',
Expand Down
1 change: 1 addition & 0 deletions edward/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
'get_session',
'get_siblings',
'get_variables',
'marginal',
'Progbar',
'random_variables',
'rbf',
Expand Down
63 changes: 63 additions & 0 deletions edward/util/random_variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -778,3 +778,66 @@ def transform(x, *args, **kwargs):
new_x = TransformedDistribution(x, bij, *args, **kwargs)
new_x.support = new_support
return new_x


def marginal(x, n):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functions should be placed according to alphabetical ordering of function names.

"""Performs a full graph sample on the provided random variable.

Given a random variable and a sample size, adds an additional sample
dimension to the root random variables in x's graph, and samples from
a new graph in terms of that sample size.

Args:
x : RandomVariable.
Random variable to perform full graph sample on.
n : tf.Tensor or int
The size of the full graph sample to take.

Returns:
tf.Tensor.
The fully sampled values from x, of shape [n] + x.shape
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

x.shape = x.sample_shape + x.batch_shape + x.event_shape. You replace the sample_shape, so the output should have shape [n] + x.batch_shape + x.event_shape. But I guess it currently fails if x.sample_shape is non-scalar anyways.


#### Examples

```python
ed.get_session()
loc = Normal(0.0, 100.0)
y = Normal(loc, 0.0001)
conditional_sample = y.sample(50)
marginal_sample = ed.marginal(y, 50)

np.std(conditional_sample.eval())
0.000100221

np.std(marginal_sample.eval())
106.55982
```

#### Notes

The current implementation only works for graphs of RVs that don't use
the `sample_shape` kwarg.
"""
ancestors = get_ancestors(x)
if any([rv.sample_shape != () for rv in ancestors]) or x.sample_shape != ():
raise NotImplementedError("`marginal` doesn't support graphs of RVs "
"with non scalar sample_shape args.")
elif ancestors == []:
old_roots = [x]
else:
old_roots = [rv for rv in ancestors if get_ancestors(rv) == []]

new_roots = []
for rv in old_roots:
new_rv = copy(rv)
new_rv._sample_shape = tf.TensorShape(n).concatenate(new_rv._sample_shape)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tf.TensorShape() fails if n is a tf.Tensor

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also came up when I looked into #774, and I think would need to be solved at the same time. Sample shape needs a TensorShape, and there's no nice way to turn tensor n into one (I don't think).

So I think either sample_shape needs to be interpreted as 'whatever gets passed to sample' and therefore is stored as a tensor, not a tensorshape. This would solve #774, and I don't think would break much. Another alternative is having sample_shape and sample_shape_tensor attributes built from the actual tensor representation of the RV.

Let me know if you'd prefer this is implemented in the same PR, I'll push the other changes.

new_rv._value = new_rv.sample(new_rv._sample_shape)
new_roots.append(new_rv)
dict_swap = dict(zip(old_roots, new_roots))
x_full = copy(x, dict_swap, replace_itself=True)
if x_full.shape[1:] != x.shape:
print(x_full.shape)
print(x.shape)
raise ValueError('Could not transform graph for bulk sampling.')

return x_full
103 changes: 103 additions & 0 deletions tests/util/test_marginal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import edward as ed
import numpy as np
import tensorflow as tf

from edward.models import Normal, InverseGamma
from tensorflow.contrib.distributions import bijectors
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found this test very intuitive. Great work. One note: you don't use the bijectors module



class test_marginal_class(tf.test.TestCase):

def test_bad_graph(self):
with self.test_session():
loc = Normal(tf.zeros(5), 5.0)
y_loc = tf.expand_dims(loc, 1) # this displaces the sample dimension
inv_scale = Normal(tf.zeros(3), 1.0)
y_scale = tf.expand_dims(tf.nn.softplus(inv_scale), 0)
y = Normal(y_loc, y_scale)
with self.assertRaises(ValueError):
ed.marginal(y, 20)

def test_sample_arg(self):
with self.test_session():
y = Normal(0.0, 1.0, sample_shape=10)
with self.assertRaises(NotImplementedError):
ed.marginal(y, 20)

def test_sample_arg_ancestor(self):
with self.test_session():
x = Normal(0.0, 1.0, sample_shape=10)
y = Normal(x, 0.0)
with self.assertRaises(NotImplementedError):
ed.marginal(y, 20)

def test_no_ancestor(self):
with self.test_session():
y = Normal(0.0, 1.0)
sample = ed.marginal(y, 4)
self.assertEqual(sample.shape, [4])

def test_no_ancestor_batch(self):
with self.test_session():
y = Normal(tf.zeros([2, 3, 4]), 1.0)
sample = ed.marginal(y, 5)
self.assertEqual(sample.shape, [5, 2, 3, 4])

def test_single_ancestor(self):
with self.test_session():
loc = Normal(0.0, 1.0)
y = Normal(loc, 1.0)
sample = ed.marginal(y, 4)
self.assertEqual(sample.shape, [4])

def test_single_ancestor_batch(self):
with self.test_session():
loc = Normal(tf.zeros([2, 3, 4]), 1.0)
y = Normal(loc, 1.0)
sample = ed.marginal(y, 5)
self.assertEqual(sample.shape, [5, 2, 3, 4])

def test_sample_passthrough(self):
with self.test_session():
loc = Normal(0.0, 100.0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's with very low probability this can produce a false negative/positive, but in general you should always set seed in tests when checking randomness.

y = Normal(loc, 0.0001)
conditional_sample = y.sample(50)
marginal_sample = ed.marginal(y, 50)
self.assertTrue(np.std(conditional_sample.eval()) < 1.0)
self.assertTrue(np.std(marginal_sample.eval()) > 1.0)

def test_multiple_ancestors(self):
with self.test_session():
loc = Normal(0.0, 1.0)
scale = InverseGamma(1.0, 1.0)
y = Normal(loc, scale)
sample = ed.marginal(y, 4)
self.assertEqual(sample.shape, [4])

def test_multiple_ancestors_batch(self):
with self.test_session():
loc = Normal(tf.zeros(5), 1.0)
scale = InverseGamma(tf.ones(5), 1.0)
y = Normal(loc, scale)
sample = ed.marginal(y, 4)
self.assertEqual(sample.shape, [4, 5])

def test_multiple_ancestors_batch_broadcast(self):
with self.test_session():
loc = Normal(tf.zeros([5, 1]), 1.0)
scale = InverseGamma(tf.ones([1, 6]), 1.0)
y = Normal(loc, scale)
sample = ed.marginal(y, 4)
self.assertEqual(sample.shape, [4, 5, 6])

def test_multiple_ancestors_failed_broadcast(self):
with self.test_session():
loc = Normal(tf.zeros([5, 1]), 1.0)
scale = InverseGamma(tf.ones([6]), 1.0)
y = Normal(loc, scale)
with self.assertRaises(ValueError):
sample = ed.marginal(y, 4)