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).

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.


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 the register_rv method
        self.register_rv(Normal.dist(mu=mean, sigma=sigma), 'v1', initval=1)
        # this will create variable named like '{name::}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=sigma)

        # 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:
    # 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::*`


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_named_variable(var[, dims])

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


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

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.dlogp([vars, jacobian])

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


Evaluates shapes of untransformed AND transformed free variables.


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.make_obs_var(rv_var, data, dims, transform)

Create a TensorVariable for an observed random variable.


Checks if name has prefix and adds if needed


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[, observed, ...])

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

Model.replace_rvs_by_values(graphs, **kwargs)

Clone and replace random variables in graphs with their value variables.

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.update_start_vals(a, b)

Update point a with b, without overwriting existing keys.



Tuples of dimension names for specific model variables.


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



All the continuous value variables in the model


Coordinate values for model dimensions.


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


The symbolic lengths of dimensions in the model.



All the discrete value variables in the model


Maps transformed variables to initial value placeholders.




Aesara scalar of log-probability of the observed variables



Aesara scalar of log-probability of the Potential terms




List of all random variables, including deterministic ones.


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


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


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


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