pymc.Model#

class pymc.Model(*args, **kwargs)[source]#

Encapsulates the variables and likelihood factors of a model.

Model class can be used for creating class based models. To create a class based model you should inherit from Model and override the __init__ method with arbitrary definitions (do not forget to call base class pymc.Model.__init__() first).

Parameters
name: str

name that will be used as prefix for names of all random variables defined within model

check_bounds: bool

Ensure that input parameters to distributions are in a valid range. If your model is built in a way where you know your parameters can only take on valid values you can set this to False for increased speed. This should not be used if your model contains discrete variables.

Examples

How to define a custom model

class CustomModel(Model):
    # 1) override init
    def __init__(self, mean=0, sigma=1, name=''):
        # 2) call super's init first, passing model and name
        # to it name will be prefix for all variables here if
        # no name specified for model there will be no prefix
        super().__init__(name, model)
        # now you are in the context of instance,
        # `modelcontext` will return self you can define
        # variables in several ways note, that all variables
        # will get model's name prefix

        # 3) you can create variables with Var method
        self.Var('v1', Normal.dist(mu=mean, sigma=sd))
        # this will create variable named like '{prefix::}v1'
        # and assign attribute 'v1' to instance created
        # variable can be accessed with self.v1 or self['v1']

        # 4) this syntax will also work as we are in the
        # context of instance itself, names are given as usual
        Normal('v2', mu=mean, sigma=sd)

        # something more complex is allowed, too
        half_cauchy = HalfCauchy('sigma', beta=10, initval=1.)
        Normal('v3', mu=mean, sigma=half_cauchy)

        # Deterministic variables can be used in usual way
        Deterministic('v3_sq', self.v3 ** 2)

        # Potentials too
        Potential('p1', at.constant(1))

# After defining a class CustomModel you can use it in several
# ways

# I:
#   state the model within a context
with Model() as model:
    CustomModel()
    # arbitrary actions

# II:
#   use new class as entering point in context
with CustomModel() as model:
    Normal('new_normal_var', mu=1, sigma=0)

# III:
#   just get model instance with all that was defined in it
model = CustomModel()

# IV:
#   use many custom models within one context
with Model() as model:
    CustomModel(mean=1, name='first')
    CustomModel(mean=2, name='second')

# variables inside both scopes will be named like `first::*`, `second::*`

Methods

Model.__init__([name, coords, check_bounds])

Model.add_coord(name[, values, mutable, length])

Registers a dimension coordinate with the model.

Model.add_coords(coords, *[, lengths])

Vectorized version of Model.add_coord.

Model.add_random_variable(var[, dims])

Add a random variable to the named variables of the model.

Model.check_start_vals(start)

Check that the starting values for MCMC do not cause the relevant log probability to evaluate to something invalid (e.g.

Model.check_test_point(*args, **kwargs)

Model.compile_d2logp([vars, jacobian])

Compiled log probability density hessian function.

Model.compile_dlogp([vars, jacobian])

Compiled log probability density gradient function.

Model.compile_fn(outs, *[, inputs, mode, ...])

Compiles an Aesara function

Model.compile_logp([vars, jacobian, sum])

Compiled log probability density function.

Model.create_value_var(rv_var, transform[, ...])

Create a TensorVariable that will be used as the random variable's "value" in log-likelihood graphs.

Model.d2logp([vars, jacobian])

Hessian of the models log-probability w.r.t.

Model.d2logpt(*args, **kwargs)

Model.dlogp([vars, jacobian])

Gradient of the models log-probability w.r.t.

Model.dlogpt(*args, **kwargs)

Model.eval_rv_shapes()

Evaluates shapes of untransformed AND transformed free variables.

Model.flatten([vars, order, inputvar])

Flattens model's input and returns:

Model.initial_point([seed])

Computes the initial point of the model.

Model.logp([vars, jacobian, sum])

Elemwise log-probability of the model.

Model.logp_dlogp_function([grad_vars, tempered])

Compile an Aesara function that computes logp and gradient.

Model.logpt(*args, **kwargs)

Model.make_obs_var(rv_var, data, dims, transform)

Create a TensorVariable for an observed random variable.

Model.name_for(name)

Checks if name has prefix and adds if needed

Model.name_of(name)

Checks if name has prefix and deletes if needed

Model.point_logps([point, round_vals])

Computes the log probability of point for all random variables in the model.

Model.profile(outs, *[, n, point, profile])

Compiles and profiles an Aesara function which returns outs and takes values of model vars as a dict as an argument.

Model.register_rv(rv_var, name[, data, ...])

Register an (un)observed random variable with the model.

Model.set_data(name, values[, coords])

Changes the values of a data variable in the model.

Model.set_dim(name, new_length[, coord_values])

Update a mutable dimension.

Model.set_initval(rv_var, initval)

Sets an initial value (strategy) for a random variable.

Model.shape_from_dims(dims)

Model.update_start_vals(a, b)

Update point a with b, without overwriting existing keys.

Attributes

RV_dims

Tuples of dimension names for specific model variables.

basic_RVs

List of random variables the model is defined in terms of (which excludes deterministics).

cont_vars

All the continuous variables in the model

coords

Coordinate values for model dimensions.

datalogp

Aesara scalar of log-probability of the observed variables and potential terms

datalogpt

dim_lengths

The symbolic lengths of dimensions in the model.

disc_vars

All the discrete variables in the model

independent_vars

List of all variables that are non-stochastic inputs to the model.

initial_values

Maps transformed variables to initial value placeholders.

isroot

model

ndim

observedlogp

Aesara scalar of log-probability of the observed variables

observedlogpt

parent

potentiallogp

Aesara scalar of log-probability of the Potential terms

potentiallogpt

prefix

root

test_point

Deprecated alias for Model.initial_point(seed=None).

unobserved_RVs

List of all random variables, including deterministic ones.

unobserved_value_vars

List of all random variables (including untransformed projections), as well as deterministics used as inputs and outputs of the model's log-likelihood graph

value_vars

List of unobserved random variables used as inputs to the model's log-likelihood (which excludes deterministics).

varlogp

Aesara scalar of log-probability of the unobserved random variables (excluding deterministic).

varlogp_nojac

Aesara scalar of log-probability of the unobserved random variables (excluding deterministic) without jacobian term.

varlogp_nojact

varlogpt

vars