 # Using transforms to enforce positivity of sum of RVs

Hi all,

pyro newbie here. I’m trying to figure out how to use transformations (in particular, softplus) to enforce the positivity of a sum of variables. My current attempt below returns an “AttributeError: ‘Tensor’ object has no attribute ‘batch_shape’”, because a+b is apparently a Tensor and not a distribution.

Any suggestions on how to fix this? Alternative approaches to achieve the same result (constraining the sum of a and b to be positive) are also very welcome. (What I actually want to do is sample from a Bernoulli distribution, with the probability given by the sum of various other RVs. Thus I need to somehow ensure that that sum is between 0 and 1. Choosing constraints on all summands such that the sum is always within [0,1] is extremely restrictive.)

``````import pyro
import pyro.distributions as dist
from pyro.infer import Predictive
from pyro.distributions.transforms import SoftplusTransform

def model():
a = pyro.sample("a", dist.Uniform(0.0, 1.0))
b = pyro.sample("b", dist.Uniform(-0.1, 0.1))
var = pyro.sample("var",  dist.TransformedDistribution(a+b, transforms=[SoftplusTransform()]))

# draw samples from the prior
data = Predictive(model, {}, num_samples=1000)()
print(data)
``````

I figured out how to do what I want. I’ll leave this here for future reference.

``````import pyro
import pyro.distributions as dist
from pyro.infer import Predictive
import torch

def model():
a = pyro.sample("a", dist.Uniform(0.0, 1.0))
b = pyro.sample("b", dist.Uniform(-0.1, 0.1))
var = pyro.deterministic("var", torch.nn.functional.softplus(a+b))

# draw samples from the prior
data = Predictive(model, {}, num_samples=1000)()
print(data)
``````
3 Likes