API Reference#
This reference provides detailed documentation for all modules, classes, and methods in the current release of Bambi.
bambi.models
#
- class bambi.models.GroupSpecificTerm(name, data, predictor, grouper, categorical=False, prior=None, constant=None)[source]#
Representation of a single (group specific) model term.
- Parameters
name (str) – Name of the term.
data ((DataFrame, Series, ndarray)) – The term values.
predictor ((DataFrame, Series, ndarray)) – Data of the predictor variable in the group specific term.
grouper ((DataFrame, Series, ndarray)) – Data of the grouping variable in the group specific term.
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.
- class bambi.models.InteractionTerm(name, data, categorical=False, prior=None)[source]#
Representation of a single (common) interaction 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.
- 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(common=None, group_specific=None, priors=None, family='gaussian', link=None, categorical=None, append=True)[source]#
Add one or more terms to the model via an R-like formula syntax.
- Parameters
common (str) – Optional formula specification of common effects.
group_specific (list) – Optional list-based specification of group specific 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., group specific 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='pymc')[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 only ‘pymc’ is supported.
- property common_terms#
Return dict of all and only common effects in model.
- fit(common=None, group_specific=None, fixed=None, random=None, priors=None, family='gaussian', link=None, run=True, categorical=None, omit_offsets=True, backend='pymc', **kwargs)[source]#
Fit the model using the specified BackEnd.
- Parameters
common (str) – Optional formula specification of common effects.
group_specific (list) – Optional list-based specification of group specific 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 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., group specific factors coded as numerical IDs), explicitly passing variable names via this argument is recommended.
omit_offsets (bool) – Omits offset terms in the InferenceData object when the model includes group specific effects. Defaults to True.
backend (str) – The name of the BackEnd to use. Currently only ‘pymc’ backend is supported.
- property group_specific_terms#
Return dict of all and only group specific effects in model.
- plot_priors(draws=5000, var_names=None, random_seed=None, figsize=None, textsize=None, hdi_prob=None, round_to=2, point_estimate='mean', kind='kde', bins=None, omit_offsets=True, omit_group_specific=True, ax=None)[source]#
Samples from the prior distribution and plot its marginals.
- Parameters
draws (int) – Number of draws to sample from the prior predictive distribution. Defaults to 5000.
var_names (str or list) – A list of names of variables for which to compute the posterior predictive distribution. Defaults to both observed and unobserved RVs.
random_seed (int) – Seed for the random number generator.
figsize (tuple) – Figure size. If None it will be defined automatically.
textsize (float) – Text size scaling factor for labels, titles and lines. If None it will be autoscaled based on figsize.
hdi_prob (float, optional) – Plots highest density interval for chosen percentage of density. Use ‘hide’ to hide the highest density interval. Defaults to 0.94.
round_to (int, optional) – Controls formatting of floats. Defaults to 2 or the integer part, whichever is bigger.
point_estimate (Optional[str]) – Plot point estimate per variable. Values should be ‘mean’, ‘median’, ‘mode’ or None. Defaults to ‘auto’ i.e. it falls back to default set in rcParams.
kind (str) – Type of plot to display (kde or hist) For discrete variables this argument is ignored and a histogram is always used.
bins (integer or sequence or 'auto', optional) – Controls the number of bins, accepts the same keywords matplotlib.hist() does. Only works if kind == hist. If None (default) it will use auto for continuous variables and range(xmin, xmax + 1) for discrete variables.
omit_offsets (bool) – Whether to omit offset terms in the plot. Defaults to True.
omit_group_specific (bool) – Whether to omit group specific effects in the plot. Defaults to True.
ax (numpy array-like of matplotlib axes or bokeh figures, optional) – A 2D array of locations into which to plot the densities. If not supplied, ArviZ will create its own array of plot areas (and return it).
**kwargs – Passed as-is to plt.hist() or plt.plot() function depending on the value of kind.
- Returns
axes
- Return type
matplotlib axes or bokeh figures
- posterior_predictive(idata, draws=500, var_names=None, inplace=True, random_seed=None)[source]#
Generate samples from the posterior predictive distribution.
- Parameters
idata (InfereceData) – InfereceData with samples from the posterior distribution.
draws (int) – Number of draws to sample from the prior predictive distribution. Defaults to 500.
var_names (str or list) – A list of names of variables for which to compute the posterior predictive distribution. Defaults to both observed and unobserved RVs.
inplace (bool) – If
True
it will add a posterior_predictive group to idata, otherwise it will return a copy of idata with the added group. If true and idata already have a posterior_predictive group it will be overwrittedrandom_seed (int) – Seed for the random number generator.
- Returns
When
inplace=True
add posterior_predictive group inplace to idata and return ``None`. Otherwise a copy of idata with a posterior_predictive group.- Return type
None or InferenceData
- prior_predictive(draws=500, var_names=None, omit_offsets=True, random_seed=None)[source]#
Generate samples from the prior predictive distribution.
- Parameters
draws (int) – Number of draws to sample from the prior predictive distribution. Defaults to 500.
var_names (str or list) – A list of names of variables for which to compute the posterior predictive distribution. Defaults to both observed and unobserved RVs.
random_seed (int) – Seed for the random number generator.
- Returns
InferenceData object with the groups prior, prior_predictive and ovserved_data.
- Return type
InferenceData
- set_priors(priors=None, common=None, group_specific=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.
common (Prior, int, float or str) – A prior specification to apply to all common terms included in the model.
group_specific (Prior, int, float or str) – A prior specification to apply to all group specific terms 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 group specific 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.ResponseTerm(name, data, categorical=False, prior=None, success_event=None)[source]#
Representation of a single response 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.
success_event (str or None) – Indicates the success level when the term is a categorical variable.
- class bambi.models.Term(name, data, categorical=False, prior=None, constant=None)[source]#
Representation of a single (common) 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.
- 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, ‘sigma’: 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’, ‘common’, or ‘group_specific’. 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, 'sigma': 1000}]} >>> pf = PriorFactory(dists=dists)
>>> families = {'normalish': {'dist': ['normal', {sigma: '#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’, ‘common’, or ‘group_specific’.
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’.