Hi everyone,
I am implementing the rng_fn
of a custom RandomVariable
used for a custom Distribution
. This function calls a function from another package and generates random samples of the RandomVariable
. That function accepts a seed
for each draw, so for sequential draws to be reproducible, I am thinking of using the rng
object passed to rng_fn
to sample a random integer to pass to the package as the seed. Since each draw of the random integer is reproducible, the results of the rng_fn
should be reproducible as well. My question is, how to draw from rng
, which is a RandomGeneratorType
or a RandomStateType
? I believe that it is also a SharedVariable
by default.
Thanks!
Welcome!
@ricardoV94 might have suggestions.
The RNG is no longer a shared variable in the rng_fn
function. It’s either a numpy RandomState or Generator (usually the latter as the RandomState is being gradually abandoned by NumPy). You can take draws from these objects by calling rng.foo
like rng.beta(alpha, beta, size=size)
. Most distributions are available in both Generators and RandomStates, but you can check the numpy API to confirm (some have different names, like integers and randint).
If you want to use scipy methods you can pass the rng as in scipy.stats.beta(alpha, beta).rvs(size, random_state=rng)
Finally, you can also use other RandomVariables rng_fn
class method.
1 Like
Thank you so much @ricardoV94 and @cluhmann! I thought this was the case when I read the tutorial on how to create custom Distribution
s in PyMC. However, the pytensor code seems to enforce a check to ensure that rng
is a RandomGeneratorType
or a RandomStateType
(see https://github.com/pymc-devs/pytensor/blob/a6e7722f16c49eea208891c02940ff16bd3e3482/pytensor/tensor/random/op.py#L328-L333). Can I just ignore and assume that PyMC
will use either Generator
or RandomState
for rng
?
The variables in make_node are not the things that are passed into the rng_fn. They are the “symbolic” counterparts
Awesome! That makes things much easier. Thank you so much, @ricardoV94!