Model

class pymc3.model.Model(name='', model=None, theano_config=None)

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 __init__() with arbitrary definitions (do not forget to call base class __init__() first).

Parameters:
  • name (str) – name that will be used as prefix for names of all random variables defined within model
  • model (Model) – instance of Model that is supposed to be a parent for the new instance. If None, context will be used. All variables defined within instance will be passed to the parent instance. So that ‘nested’ model contributes to the variables and likelihood factors of parent model.
  • theano_config (dict) – A dictionary of theano config values that should be set temporarily in the model context. See the documentation of theano for a complete list. Set config key compute_test_value to raise if it is None.

Examples

How to define a custom model

class CustomModel(Model):
    # 1) override init
    def __init__(self, mean=0, sd=1, name='', model=None):
        # 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(CustomModel, self).__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, sd=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, sd=sd)

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

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

        # Potentials too
        Potential('p1', tt.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, sd=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')
Var(name, dist, data=None, total_size=None)

Create and add (un)observed random variable to the model with an appropriate prior distribution.

Parameters:
  • name (str) –
  • dist (distribution for the random variable) –
  • data (array_like (optional)) – If data is provided, the variable is observed. If None, the variable is unobserved.
  • total_size (scalar) – upscales logp of variable with coef = total_size/var.shape[0]
Returns:

FreeRV or ObservedRV

add_random_variable(var)

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

basic_RVs

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

check_test_point(test_point=None, round_vals=2)

Checks log probability of test_point for all random variables in the model.

Parameters:
  • test_point (Point) – Point to be evaluated. if None, then all model.test_point is used
  • round_vals (int) – Number of decimals to round log-probabilities
Returns:

Pandas Series

cont_vars

All the continuous variables in the model

disc_vars

All the discrete variables in the model

fastfn(outs, mode=None, *args, **kwargs)

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

Parameters:
  • outs (Theano variable or iterable of Theano variables) –
  • mode (Theano compilation mode) –
Returns:

Compiled Theano function as point function.

flatten(vars=None, order=None, inputvar=None)

Flattens model’s input and returns:

FlatView with
  • input vector variable
  • replacements input_var -> vars
  • view {variable: VarMap}
Parameters:
  • vars (list of variables or None) – if None, then all model.free_RVs are used for flattening input
  • order (ArrayOrdering) – Optional, use predefined ordering
  • inputvar (tt.vector) – Optional, use predefined inputvar
Returns:

flat_view

fn(outs, mode=None, *args, **kwargs)

Compiles a Theano function which returns the values of outs and takes values of model vars as arguments.

Parameters:
  • outs (Theano variable or iterable of Theano variables) –
  • mode (Theano compilation mode) –
Returns:

Compiled Theano function

logp_nojact

Theano scalar of log-probability of the model

logpt

Theano scalar of log-probability of the model

makefn(outs, mode=None, *args, **kwargs)

Compiles a Theano function which returns outs and takes the variable ancestors of outs as inputs.

Parameters:
  • outs (Theano variable or iterable of Theano variables) –
  • mode (Theano compilation mode) –
Returns:

Compiled Theano function

name_for(name)

Checks if name has prefix and adds if needed

name_of(name)

Checks if name has prefix and deletes if needed

profile(outs, n=1000, point=None, profile=True, *args, **kwargs)

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

Parameters:
  • outs (Theano variable or iterable of Theano variables) –
  • n (int, default 1000) – Number of iterations to run
  • point (point) – Point to pass to the function
  • profile (True or ProfileStats) –
  • kwargs (args,) – Compilation args
Returns:

ProfileStats – Use .summary() to print stats.

test_point

Test point used to check that the model doesn’t generate errors

unobserved_RVs

List of all random variable, including deterministic ones.

varlogpt

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

vars

List of unobserved random variables used as inputs to the model (which excludes deterministics).

class pymc3.model.Factor(*args, **kwargs)

Common functionality for objects with a log probability density associated with them.

d2logp(vars=None)

Compiled log probability density hessian function

d2logp_nojac(vars=None)

Compiled log density hessian function, without jacobian terms.

dlogp(vars=None)

Compiled log probability density gradient function

dlogp_nojac(vars=None)

Compiled log density gradient function, without jacobian terms.

fastd2logp(vars=None)

Compiled log probability density hessian function

fastd2logp_nojac(vars=None)

Compiled log density hessian function, without jacobian terms.

fastdlogp(vars=None)

Compiled log probability density gradient function

fastdlogp_nojac(vars=None)

Compiled log density gradient function, without jacobian terms.

fastlogp

Compiled log probability density function

logp

Compiled log probability density function

logp_nojact

Theano scalar of log-probability, excluding jacobian terms.

logpt

Theano scalar of log-probability of the model

pymc3.model.compilef(outs, mode=None, model=None)

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

Parameters:
  • outs (Theano variable or iterable of Theano variables) –
  • mode (Theano compilation mode) –
Returns:

Compiled Theano function as point function.

pymc3.model.fn(outs, mode=None, model=None, *args, **kwargs)

Compiles a Theano function which returns the values of outs and takes values of model vars as arguments.

Parameters:
  • outs (Theano variable or iterable of Theano variables) –
  • mode (Theano compilation mode) –
Returns:

Compiled Theano function

pymc3.model.fastfn(outs, mode=None, model=None)

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

Parameters:
  • outs (Theano variable or iterable of Theano variables) –
  • mode (Theano compilation mode) –
Returns:

Compiled Theano function as point function.

pymc3.model.modelcontext(model)

return the given model or try to find it in the context if there was none supplied.

pymc3.model.Point(*args, **kwargs)

Build a point. Uses same args as dict() does. Filters out variables not in the model. All keys are strings.

Parameters:kwargs (args,) – arguments to build a dict
pymc3.model.Deterministic(name, var, model=None)

Create a named deterministic variable

Parameters:
  • name (str) –
  • var (theano variables) –
Returns:

var (var, with name attribute)

pymc3.model.Potential(name, var, model=None)

Add an arbitrary factor potential to the model likelihood

Parameters:
  • name (str) –
  • var (theano variables) –
Returns:

var (var, with name attribute)