zhusuan.framework

BayesianNet

class BayesianNet(observed=None, device=device(type='cpu'))[source]

Bases: torch.nn.modules.module.Module

bernoulli(name, logits=None, probs=None, dtype=None, is_continuous=False, group_ndims=0, n_samples=None, **kwargs)[source]
beta(name, alpha, beta, dtype=None, is_continuous=True, group_ndims=0, n_samples=None, **kwargs)[source]
property cache

The dictionary of all named deterministic nodes in this BayesianNet.

Returns

A dict.

property device

The device this module lies at.

Returns

torch.device

exponential(name, rate, dtype=None, is_continuous=True, group_ndims=0, n_samples=None, **kwargs)[source]
gamma(name, alpha, beta, dtype=None, is_continuous=True, group_ndims=0, n_samples=None, **kwargs)[source]
laplace(name, loc, scale, dtype=None, is_continuous=True, group_ndims=0, n_samples=None, **kwargs)[source]
log_joint(use_cache=False)[source]

The default log joint probability of this BayesianNet. It works by summing over all the conditional log probabilities of stochastic nodes evaluated at their current values (samples or observations).

Returns

A Var.

logistic(name, loc, scale, dtype=None, is_continuous=True, group_ndims=0, n_samples=None, **kwargs)[source]
property nodes

The dictionary of all named stochastic nodes in this BayesianNet.

Returns

A dict.

normal(name, mean=0.0, std=None, logstd=None, dtype=None, is_continuous=True, is_reparameterized=True, group_ndims=0, n_samples=None, **kwargs)[source]
observe(observed)[source]

Assign the nodes and values to be observed in this BayesianNet.

Parameters

observed – A dictionary of (string, Tensor) pairs, which maps from names of stochastic nodes to their observed values.

property observed

The dictionary of all observed nodes in this BayesianNet.

Returns

A dict.

poisson(name, rate, dtype=None, is_continuous=True, group_ndims=0, n_samples=None, **kwargs)[source]
sn(dist, name, n_samples=None, **kwargs)[source]

Short cut for method stochastic_node()

snode(*args, **kwargs)[source]

Short cut for method stochastic_node()

stochastic_node(distribution, name, n_samples=None, **kwargs)[source]

Add a stochastic node in this BayesianNet that follows the distribution assigned by the name parameter.

Parameters
  • distribution – The distribution which the node follows.

  • name – The unique name of the node.

  • n_samples – number of samples per sample process

  • kwargs – Parameters of the distribution which the node builds with.

Returns

A instance(sample) of the node.

studentT(name, df, loc=0.0, scale=1.0, dtype=None, is_continuous=True, group_ndims=0, n_samples=None, **kwargs)[source]
to(device)[source]

Moves and/or casts the parameters and buffers.

This can be called as

to(device=None, dtype=None, non_blocking=False)[source]
to(dtype, non_blocking=False)[source]
to(tensor, non_blocking=False)[source]
to(memory_format=torch.channels_last)[source]

Its signature is similar to torch.Tensor.to(), but only accepts floating point or complex dtypes. In addition, this method will only cast the floating point or complex parameters and buffers to dtype (if given). The integral parameters and buffers will be moved device, if that is given, but with dtypes unchanged. When non_blocking is set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.

See below for examples.

Note

This method modifies the module in-place.

Args:
device (torch.device): the desired device of the parameters

and buffers in this module

dtype (torch.dtype): the desired floating point or complex dtype of

the parameters and buffers in this module

tensor (torch.Tensor): Tensor whose dtype and device are the desired

dtype and device for all parameters and buffers in this module

memory_format (torch.memory_format): the desired memory

format for 4D parameters and buffers in this module (keyword only argument)

Returns:

Module: self

Examples:

>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]], dtype=torch.float64)
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16)

>>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
>>> linear.weight
Parameter containing:
tensor([[ 0.3741+0.j,  0.2382+0.j],
        [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
>>> linear(torch.ones(3, 2, dtype=torch.cdouble))
tensor([[0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
training: bool
uniform(name, low, high, dtype=None, is_continuous=True, is_reparameterized=True, group_ndims=0, n_samples=None, **kwargs)[source]

StochasticTensor

class StochasticTensor(bn, name: str, dist: zhusuan.distributions.base.Distribution, observation=None, n_samples=None, **kwargs)[source]

Bases: object

The StochasticTensor class represents the stochastic nodes in a BayesianNet. We can use any distribution available in zhusuan.distributions to construct a stochastic node in a BayesianNet. For example:

class Net(BayesianNet):
    def __init__(self):
        self.stochastic_node('Normal', name='x', mean=0., std=1.)

will build a stochastic node in Net with the Normal distribution. The returned x will be a instance of StochasticTensor.

StochasticTensor instances are Vars, which means that they can be passed into any Jittor operations. This makes it easy to build Bayesian networks by mixing stochastic nodes and Jittor primitives.

See also

For more information, please refer to Basic Concepts in ZhuSuan.

Parameters
  • bn – A BayesianNet.

  • name – A string. The name of the StochasticTensor. Must be unique in a BayesianNet.

  • dist – A Distribution instance that determines the distribution used in this stochastic node.

  • observation – A Var, which matches the shape of dist. If specified, then the StochasticTensor is observed and the tensor property will return the observation.

  • n_samples – A 0-D integer. Number of samples generated by this StochasticTensor.

property bn

The BayesianNet where the StochasticTensor lives.

Returns

A BayesianNet instance.

property dist

The distribution followed by the StochasticTensor.

Returns

A Distribution instance.

property dtype

The sample type of the StochasticTensor.

Returns

A DType instance.

get_shape()[source]

Alias of shape.

Returns

A TensorShape instance.

is_observed()[source]

Whether the StochasticTensor is observed or not.

Returns

A bool.

log_prob(sample=None)[source]
property name

The name of the StochasticTensor.

Returns

A string.

sample(force=False)[source]

The value of this StochasticTensor. If it is observed, then the observation is returned, otherwise samples are returned. :param force: force to sample, disregard the observed value, default as False :return: A Var.

property shape

Return the static shape of this StochasticTensor.

Returns

A torch.Size instance.

property tensor

The value of this StochasticTensor. If it is observed, then the observation is returned, otherwise samples are returned.

Returns

A Var.