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
 namestr
name that will be used as prefix for names of all random variables defined within model
 modelModel
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_configdict
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, sigma=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().__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('sd', beta=10, testval=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', 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, 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')

Var
(self, name, dist, data=None, total_size=None)¶ Create and add (un)observed random variable to the model with an appropriate prior distribution.
 Parameters
 namestr
 distdistribution for the random variable
 dataarray_like (optional)
If data is provided, the variable is observed. If None, the variable is unobserved.
 total_sizescalar
upscales logp of variable with
coef = total_size/var.shape[0]
 Returns
 FreeRV or ObservedRV

add_random_variable
(self, var)¶ Add a random variable to the named variables of the model.

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

check_test_point
(self, test_point=None, round_vals=2)¶ Checks log probability of test_point for all random variables in the model.
 Parameters
 test_pointPoint
Point to be evaluated. if None, then all model.test_point is used
 round_valsint
Number of decimals to round logprobabilities
 Returns
 Pandas Series

property
cont_vars
¶ All the continuous variables in the model

property
disc_vars
¶ All the discrete variables in the model

fastfn
(self, 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
 outsTheano variable or iterable of Theano variables
 modeTheano compilation mode
 Returns
 Compiled Theano function as point function.

flatten
(self, 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
 varslist of variables or None
if None, then all model.free_RVs are used for flattening input
 orderArrayOrdering
Optional, use predefined ordering
 inputvartt.vector
Optional, use predefined inputvar
 Returns
 flat_view

fn
(self, outs, mode=None, *args, **kwargs)¶ Compiles a Theano function which returns the values of
outs
and takes values of model vars as arguments. Parameters
 outsTheano variable or iterable of Theano variables
 modeTheano compilation mode
 Returns
 Compiled Theano function

property
logp_nojact
¶ Theano scalar of logprobability of the model but without the jacobian if transformed Random Variable is presented. Note that If there is no transformed variable in the model, logp_nojact will be the same as logpt as there is no need for Jacobian correction.

property
logpt
¶ Theano scalar of logprobability of the model

makefn
(self, outs, mode=None, *args, **kwargs)¶ Compiles a Theano function which returns
outs
and takes the variable ancestors ofouts
as inputs. Parameters
 outsTheano variable or iterable of Theano variables
 modeTheano compilation mode
 Returns
 Compiled Theano function

name_for
(self, name)¶ Checks if name has prefix and adds if needed

name_of
(self, name)¶ Checks if name has prefix and deletes if needed

profile
(self, 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
 outsTheano variable or iterable of Theano variables
 nint, default 1000
Number of iterations to run
 pointpoint
Point to pass to the function
 profileTrue or ProfileStats
 args, kwargs
Compilation args
 Returns
 ProfileStats
Use .summary() to print stats.

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

property
unobserved_RVs
¶ List of all random variable, including deterministic ones.

property
varlogpt
¶ Theano scalar of logprobability of the unobserved random variables (excluding deterministic).

property
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
(self, vars=None)¶ Compiled log probability density hessian function

d2logp_nojac
(self, vars=None)¶ Compiled log density hessian function, without jacobian terms.

dlogp
(self, vars=None)¶ Compiled log probability density gradient function

dlogp_nojac
(self, vars=None)¶ Compiled log density gradient function, without jacobian terms.

fastd2logp
(self, vars=None)¶ Compiled log probability density hessian function

fastd2logp_nojac
(self, vars=None)¶ Compiled log density hessian function, without jacobian terms.

fastdlogp
(self, vars=None)¶ Compiled log probability density gradient function

fastdlogp_nojac
(self, vars=None)¶ Compiled log density gradient function, without jacobian terms.

property
fastlogp
¶ Compiled log probability density function

property
logp
¶ Compiled log probability density function

property
logp_nojact
¶ Theano scalar of logprobability, excluding jacobian terms.

property
logpt
¶ Theano scalar of logprobability 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
 outsTheano variable or iterable of Theano variables
 modeTheano 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
 outsTheano variable or iterable of Theano variables
 modeTheano 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
 outsTheano variable or iterable of Theano variables
 modeTheano compilation mode
 Returns
 Compiled Theano function as point function.

pymc3.model.
modelcontext
(model: Union[ForwardRef('Model'), NoneType]) → 'Model'¶ Return the given model or, if none was supplied, try to find one in the context stack.

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
 args, kwargs
arguments to build a dict

pymc3.model.
Deterministic
(name, var, model=None)¶ Create a named deterministic variable
 Parameters
 namestr
 vartheano variables
 Returns
 varvar, with name attribute

pymc3.model.
Potential
(name, var, model=None)¶ Add an arbitrary factor potential to the model likelihood
 Parameters
 namestr
 vartheano variables
 Returns
 varvar, with name attribute

pymc3.model.
set_data
(new_data, model=None)¶ Sets the value of one or more data container variables.
 Parameters
 new_datadict
New values for the data containers. The keys of the dictionary are the variables names in the model and the values are the objects with which to update.
 modelModel (optional if in with context)
Examples
>>> import pymc3 as pm >>> with pm.Model() as model: ... x = pm.Data('x', [1., 2., 3.]) ... y = pm.Data('y', [1., 2., 3.]) ... beta = pm.Normal('beta', 0, 1) ... obs = pm.Normal('obs', x * beta, 1, observed=y) ... trace = pm.sample(1000, tune=1000)
Set the value of x to predict on new data.
>>> with model: ... pm.set_data({'x': [5,6,9]}) ... y_test = pm.sample_posterior_predictive(trace) >>> y_test['obs'].mean(axis=0) array([4.6088569 , 5.54128318, 8.32953844])