Search code examples
pythondata-sciencepymc3

PyMC3: how to sample from transformed random variable?


I have a super basic PYMC3 question: How do you sample from a transformed RV? I need this mostly for debugging purposes.

For example:

import pymc3 as pm

with pm.Model():
   A = pm.Normal('A')

   B = pm.Deterministic('B', A + 1)
   # or
   B = A + 1

I can generate samples from A using A.random(), but that function is not defined for B. + 1 is a trivial transform but in case it were more involved I would like to draw some samples from the deformed A, i.e. B, to ensure everything is healthy.


Solution

  • That is just about it -- PyMC3 requires you to first construct a model, which you have done, and then sample from the posterior (often in the presence of data!), using pm.sample.

    The syntax you're looking for is:

    with pm.Model():
        A = pm.Normal('A')
        B = pm.Deterministic('B', A + 1)
        trace = pm.sample(1000)
    
    (trace['B'] == trace['A'] + 1).all()  # True