xtensor.random Random number generator operations#
Creating RNG variables#
- pytensor.xtensor.random.variable.rng(name=None)[source]#
Create a symbolic xtensor random number generator variable.
This creates a root variable with no data attached, suitable for use as a function input. When compiling a function, use
pytensor.In(rng, mutable=True)to allow in-place RNG updates.- Parameters:
name (str, optional) – Name for the variable.
- Returns:
A symbolic xtensor RNG variable.
- Return type:
Examples
>>> import numpy as np >>> import pytensor >>> import pytensor.xtensor.random as pxr
>>> rng = pxr.rng("rng") >>> next_rng, x = rng.normal(0, 1, extra_dims={"a": 3}) >>> fn = pytensor.function([pytensor.In(rng, mutable=True)], [next_rng, x]) >>> rng_val = np.random.default_rng(153) >>> rng_val, draw = fn(rng_val) >>> draw.shape (3,)
Create a shared xtensor random number generator variable.
The RNG state is stored internally and can be updated across function calls via the
updatesparameter ofpytensor.function.- Parameters:
value (numpy.random.Generator, optional) – The initial RNG state. If None, a new
numpy.random.default_rng(seed)is used.seed (int, optional) – Seed for the default RNG. Only used when
valueis None.name (str, optional) – Name for the shared variable.
borrow (bool) – If True, use the provided value directly without copying.
- Return type:
XRandomGeneratorSharedVariable
Examples
>>> import numpy as np >>> import pytensor >>> import pytensor.xtensor.random as pxr
Create from an existing Generator:
>>> rng = pxr.shared_rng(np.random.default_rng(153), name="rng") >>> next_rng, x = rng.normal(0, 1) >>> fn = pytensor.function([], x, updates={rng: next_rng}) >>> fn() array(1.45769255)
Or create from a seed directly:
>>> rng2 = pxr.shared_rng(seed=153, name="rng2") >>> next_rng2, x2 = rng2.normal(0, 1) >>> fn2 = pytensor.function([], x2, updates={rng2: next_rng2}) >>> fn2() array(1.45769255)
Use
set_valueto reset the RNG state:>>> rng.set_value(np.random.default_rng(153)) >>> fn() array(1.45769255) >>> rng.set_value(seed=153) >>> fn() array(1.45769255)
Distributions#
All distributions are available as methods on XRandomGeneratorVariable
(e.g. rng.normal()). They accept core_dims and extra_dims parameters
for named-dimension support.