Model¶
- pymc3.model.Deterministic(name, var, model=None, dims=None)¶
Create a named deterministic variable
- Parameters
- name: str
- var: theano variables
- Returns
- var: var, with name attribute
- 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.
- property fastlogp¶
Compiled log probability density function
- property logp¶
Compiled log probability density function
- property logp_nojact¶
Theano scalar of log-probability, excluding jacobian terms.
- property logpt¶
Theano scalar of log-probability of the model
- class pymc3.model.Model(*args, **kwargs)¶
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.- 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.
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(name, dist, data=None, total_size=None, dims=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]
- dimstuple
Dimension names for the variable.
- Returns
- FreeRV or ObservedRV
- add_random_variable(var, dims=None)¶
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(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
- property cont_vars¶
All the continuous variables in the model
- property 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_dlogp_function(grad_vars=None, tempered=False, **kwargs)¶
Compile a theano function that computes logp and gradient.
- Parameters
- grad_vars: list of random variables, optional
Compute the gradient with respect to those variables. If None, use all free random variables of this model.
- tempered: bool
Compute the tempered logp free_logp + alpha * observed_logp. alpha can be changed using ValueGradFunction.set_weights([alpha]).
- property logp_nojact¶
Theano scalar of log-probability 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 log-probability of the model
- makefn(outs, mode=None, *args, **kwargs)¶
Compiles a Theano function which returns
outs
and takes the variable ancestors ofouts
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
- 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 log-probability of the unobserved random variables (excluding deterministic).
- property vars¶
List of unobserved random variables used as inputs to the model (which excludes deterministics).
- 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.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
- 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.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.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.modelcontext(model: Optional[pymc3.model.Model]) pymc3.model.Model ¶
Return the given model or, if none was supplied, try to find one in the context stack.
- pymc3.model.set_data(new_data, model=None)¶
Sets the value of one or more data container variables.
- Parameters
- new_data: dict
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.
- model: Model (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])