API Reference

This reference provides detailed documentation for all modules, classes, and methods in the current release of Bambi.

bambi.models

class bambi.models.Model(data=None, default_priors=None, auto_scale=True, dropna=False, taylor=None, noncentered=True)[source]

Specification of model class

Parameters
  • data (DataFrame or str) – The dataset to use. Either a pandas DataFrame, or the name of the file containing the data, which will be passed to pd.read_csv().

  • default_priors (dict or str) – An optional specification of the default priors to use for all model terms. Either a dictionary containing named distributions, families, and terms (see the documentation in priors.PriorFactory for details), or the name of a JSON file containing the same information.

  • auto_scale (bool) – If True (default), priors are automatically rescaled to the data (to be weakly informative) any time default priors are used. Note that any priors explicitly set by the user will always take precedence over default priors.

  • dropna (bool)) – When True, rows with any missing values in either the predictors or outcome are automatically dropped from the dataset in a listwise manner.

  • taylor (int) – Order of Taylor expansion to use in approximate variance when constructing the default priors. Should be between 1 and 13. Lower values are less accurate, tending to undershoot the correct prior width, but are faster to compute and more stable. Odd-numbered values tend to work better. Defaults to 5 for Normal models and 1 for non-Normal models. Values higher than the defaults are generally not recommended as they can be unstable.

  • noncentered (bool) – If True (default), uses a non-centered parameterization for normal hyperpriors on grouped parameters. If False, naive (centered) parameterization is used.

add(fixed=None, random=None, priors=None, family='gaussian', link=None, categorical=None, append=True)[source]

Adds one or more terms to the model via an R-like formula syntax.

Parameters
  • fixed (str) – Optional formula specification of fixed effects.

  • random (list) – Optional list-based specification of random effects.

  • priors (dict) – Optional specification of priors for one or more terms. A dict where the keys are the names of terms in the model, and the values are either instances of class Prior or ints, floats, or strings that specify the width of the priors on a standardized scale.

  • family (str, Family) – A specification of the model family (analogous to the family object in R). Either a string, or an instance of class priors.Family. If a string is passed, a family with the corresponding name must be defined in the defaults loaded at Model initialization. Valid pre-defined families are ‘gaussian’, ‘bernoulli’, ‘poisson’, and ‘t’.

  • link (str) – The model link function to use. Can be either a string (must be one of the options defined in the current backend; typically this will include at least ‘identity’, ‘logit’, ‘inverse’, and ‘log’), or a callable that takes a 1D ndarray or theano tensor as the sole argument and returns one with the same shape.

  • categorical (str or list) – The names of any variables to treat as categorical. Can be either a single variable name, or a list of names. If categorical is None, the data type of the columns in the DataFrame will be used to infer handling. In cases where numeric columns are to be treated as categoricals (e.g., random factors coded as numerical IDs), explicitly passing variable names via this argument is recommended.

  • append (bool) – If True, terms are appended to the existing model rather than replacing any existing terms. This allows formula-based specification of the model in stages.

build(backend=None)[source]

Set up the model for sampling/fitting.

Performs any steps that require access to all model terms (e.g., scaling priors on each term), then calls the BackEnd’s build() method.

Parameters

backend (str) – The name of the backend to use for model fitting. Currently, ‘pymc’ and ‘stan’ are supported. If None, assume that fit() has already been called (possibly without building) and look in self._backend_name.

fit(fixed=None, random=None, priors=None, family='gaussian', link=None, run=True, categorical=None, backend=None, **kwargs)[source]

Fit the model using the specified BackEnd.

Parameters
  • fixed (str) – Optional formula specification of fixed effects.

  • random (list) – Optional list-based specification of random effects.

  • priors (dict) – Optional specification of priors for one or more terms. A dict where the keys are the names of terms in the model, and the values are either instances of class Prior or ints, floats, or strings that specify the width of the priors on a standardized scale.

  • family (str or Family) – A specification of the model family (analogous to the family object in R). Either a string, or an instance of class priors.Family. If a string is passed, a family with the corresponding name must be defined in the defaults loaded at Model initialization. Valid pre-defined families are ‘gaussian’, ‘bernoulli’, ‘poisson’, and ‘t’.

  • link (str) – The model link function to use. Can be either a string (must be one of the options defined in the current backend; typically this will include at least ‘identity’, ‘logit’, ‘inverse’, and ‘log’), or a callable that takes a 1D ndarray or theano tensor as the sole argument and returns one with the same shape.

  • run (bool) – Whether or not to immediately begin fitting the model once any set up of passed arguments is complete.

  • categorical (str or list) – The names of any variables to treat as categorical. Can be either a single variable name, or a list of names. If categorical is None, the data type of the columns in the DataFrame will be used to infer handling. In cases where numeric columns are to be treated as categoricals (e.g., random factors coded as numerical IDs), explicitly passing variable names via this argument is recommended.

  • backend (str) – The name of the BackEnd to use. Currently only ‘pymc’ and ‘stan’ backends are supported. Defaults to PyMC3.

property fixed_terms

Return dict of all and only fixed effects in model.

property random_terms

Return dict of all and only random effects in model.

reset()[source]

Reset list of terms and y-variable.

set_priors(priors=None, fixed=None, random=None, match_derived_names=True)[source]

Set priors for one or more existing terms.

Parameters
  • priors (dict) – Dict of priors to update. Keys are names of terms to update; values are the new priors (either a Prior instance, or an int or float that scales the default priors). Note that a tuple can be passed as the key, in which case the same prior will be applied to all terms named in the tuple.

  • fixed (Prior, int, float or str) – A prior specification to apply to all fixed terms currently included in the model.

  • random (Prior, int, float or str) – A prior specification to apply to all random terms currently included in the model.

  • match_derived_names (bool) – If True, the specified prior(s) will be applied not only to terms that match the keyword exactly, but to the levels of random effects that were derived from the original specification with the passed name. For example, priors={‘condition|subject’:0.5} would apply the prior to the terms with names ‘1|subject’, ‘condition[T.1]|subject’, and so on. If False, an exact match is required for the prior to be applied.

property term_names

Return names of all terms in order of addition to model.

class bambi.models.RandomTerm(name, data, predictor, grouper, categorical=False, prior=None, constant=None)[source]
invert_dummies(dummies)[source]

For the sake of computational efficiency (i.e., to avoid lots of large matrix multiplications in the backends), invert the dummy-coding process and represent full-rank dummies as a vector of indices into the coefficients.

class bambi.models.Term(name, data, categorical=False, prior=None, constant=None)[source]

Representation of a single (fixed) model term.

Parameters
  • name (str) – Name of the term. data (DataFrame, Series, ndarray): The term values.

  • categorical (bool) – If True, the source variable is interpreted as nominal/categorical. If False, the source variable is treated as continuous.

  • prior (Prior) – A specification of the prior(s) to use. An instance of class priors.Prior.

  • constant (bool) – indicates whether the term levels collectively act as a constant, in which case the term is treated as an intercept for prior distribution purposes.

bambi.priors

class bambi.priors.Family(name, prior, link, parent)[source]

A specification of model family.

Parameters
  • name (str) – Family name.

  • prior (Prior) – A Prior instance specifying the model likelihood prior.

  • link (str) – The name of the link function transforming the linear model prediction to a parameter of the likelihood.

  • parent (str) – The name of the prior parameter to set to the link-transformed predicted outcome (e.g., mu, p, etc.).

class bambi.priors.Prior(name, scale=None, **kwargs)[source]

Abstract specification of a term prior.

Parameters
  • name (str) – Name of prior distribution (e.g., Normal, Bernoulli, etc.)

  • kwargs (dict) – Optional keywords specifying the parameters of the named distribution.

update(**kwargs)[source]

Update the model arguments with additional arguments.

Parameters

kwargs (dict) – Optional keyword arguments to add to prior args.

class bambi.priors.PriorFactory(defaults=None, dists=None, terms=None, families=None)[source]

An object that supports specification and easy retrieval of default priors.

Parameters
  • defaults (str or dict) – Optional base configuration containing default priors for distribution, families, and term types. If a string, the name of a JSON file containing the config. If a dict, must contain keys for ‘dists’, ‘terms’, and ‘families’; see the built-in JSON configuration for an example. If None, a built-in set of priors will be used as defaults.

  • dists (dict) – Optional specification of named distributions to use as priors. Each key gives the name of a newly defined distribution; values are two-element lists, where the first element is the name of the built-in distribution to use (‘Normal’, ‘Cauchy’, etc.), and the second element is a dictionary of parameters on that distribution (e.g., {‘mu’: 0, ‘sd’: 10}). Priors can be nested to arbitrary depths by replacing any parameter with another prior specification.

  • terms (dict) – Optional specification of default priors for different model term types. Valid keys are ‘intercept’, ‘fixed’, or ‘random’. Values are either strings preprended by a #, in which case they are interpreted as pointers to distributions named in the dists dictionary, or key -> value specifications in the same format as elements in the dists dictionary.

  • families (dict) – Optional specification of default priors for named family objects. Keys are family names, and values are dicts containing mandatory keys for ‘dist’, ‘link’, and ‘parent’.

Examples

>>> dists = {'my_dist': ['Normal', {'mu': 10, 'sd': 1000}]}
>>> pf = PriorFactory(dists=dists)
>>> families = {'normalish': {'dist': ['normal', {sd: '#my_dist'}],
>>>             link:'identity', parent: 'mu'}}
>>> pf = PriorFactory(dists=dists, families=families)
get(dist=None, term=None, family=None)[source]

Retrieve default prior for a named distribution, term type, or family.

Parameters
  • dist (str) – Name of desired distribution. Note that the name is the key in the defaults dictionary, not the name of the Distribution object used to construct the prior.

  • term (str) – The type of term family to retrieve defaults for. Must be one of ‘intercept’, ‘fixed’, or ‘random’.

  • family (str) – The name of the Family to retrieve. Must be a value defined internally. In the default config, this is one of ‘gaussian’, ‘bernoulli’, ‘poisson’, or ‘t’.