# Model

Specification of model class

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L73-L1724)

``` python
Model(
    formula,
    data,
    family="gaussian",
    priors=None,
    link=None,
    categorical=None,
    potentials=None,
    dropna=False,
    auto_scale=True,
    noncentered=True,
    center_predictors=True,
    extra_namespace=None,
)
```

## Parameters

`formula: str or Formula`  
A model description written using one or more model formulas. See [Formula](../reference/Formula.md) for formula syntax and nonlinear coefficient semantics.

`data: pd.DataFrame`  
A pandas dataframe containing the data on which the model will be fit, with column names matching variables defined in the formula.

`family: str or bambi.Family = "gaussian"`  
A specification of the model family (analogous to the family object in R). Either a string, or an instance of class [bambi.Family](../reference/Family.md). If a string is passed, a family with the corresponding name must be defined in the defaults loaded at [Model](../reference/Model.md) initialization. Defaults to `"gaussian"`.

`priors: dict = None`  
Optional specification of priors for one or more terms. A dictionary where the keys are the names of terms in the model, "common," "group_specific," or the name of a model component, and the values are instances of class [Prior](../reference/Prior.md) or `dict`. An observational model parameter (e.g. "sigma" when it is modeled with a formula) maps to a nested dictionary of the same form; a constant component name maps directly to a [Prior](../reference/Prior.md), a number, or an array. If priors are unset, use automatic priors inspired by the R rstanarm library. Names that don't match any term or component are reported with a warning; set `bmb.config["UNUSED_PRIORS"]` to `"error"` or `"ignore"` to change that. Bare term priors can be combined with priors nested under the parent component. If both specify the same term, the nested parent prior takes precedence. For nonlinear models, coefficients without a formula accept a direct prior. Coefficients with additive formulas accept a term-prior dictionary. Nonlinear coefficients are scalar by default and are shared across response categories. A nonlinear coefficient expression can depend on a vector-valued modeled parameter.

`link: str or dict of str to str = None`  
The name of the link function to use. Valid names are `"cloglog"`, `"identity"`, `"inverse_squared"`, `"inverse"`, `"log"`, `"logexpm1"`, `"logit"`, `"probit"`, and `"softmax"`. Not all the link functions can be used with all the families. If a dictionary, keys are the names of the target parameters and the values are the names of the link functions. For nonlinear formulas, each parameter's inverse link is applied once to its complete predictor.

`categorical: str or list of str = None`  
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 `data` will be used to infer handling. In cases where numeric columns are to be treated as categorical (e.g., group specific factors coded as numerical IDs), explicitly passing variable names via this argument is recommended.

`potentials: list of 2-tuples = None`  
Optional specification of potentials. A potential is an arbitrary expression added to the likelihood, this is generally useful to add constraints to models, that are difficult to express otherwise. The first term of a 2-tuple is the name of a variable in the model, the second a lambda function expressing the desired constraint. If a constraint involves n variables, you can pass n 2-tuples or pass a tuple which first element is an n-tuple and second element is a lambda function with n arguments. The number and order of the lambda function has to match the number and order of the variable names.

`dropna: bool = False`  
When `True`, rows with any missing values in either the predictors or outcome are automatically dropped from the dataset in a listwise manner, optional.

`auto_scale: bool = True`  
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.

`noncentered: bool or dict[str, bool] = True`  
Default parameterization for group-specific terms. `True` (default) uses non-centered; `False` uses centered. Can also be a `dict` keyed by component name (e.g. `{"mu": True, "sigma": False}`) for per-parameter defaults; missing keys default to `True`, unknown keys raise. Per-[Prior](../reference/Prior.md) `noncentered=` overrides this setting.

`center_predictors: bool = True`  
If `True` (default), and if there is an intercept in the common terms, the data is centered by subtracting the mean. The centering is undone after sampling to provide the actual intercept in all conditional parameters that have an intercept. Note that this changes the interpretation of the prior on the intercept because it refers to the intercept of the centered data.

`extra_namespace: dict = None`  
Additional user supplied variables with transformations or data to include in the environment where the formula is evaluated. Defaults to `None`.

## Attributes

| Name | Description |
|----|----|
| [conditional_parameters](#bambi.Model.conditional_parameters) | Return likelihood parameters defined by formulas. |

### conditional_parameters

Return likelihood parameters defined by formulas.

`conditional_parameters`

#### Examples

For a Gaussian model with an ordinary formula, the mapping contains the formula-defined parent `mu`. The unmodeled auxiliary `sigma` remains a marginal parameter.

``` python
>>> import bambi as bmb
>>> import pandas as pd
>>> model = bmb.Model("y ~ x", pd.DataFrame({"y": [1, 2], "x": [0, 1]}))
>>> set(model.conditional_parameters)
{'mu'}
```

## Methods

| Name | Description |
|----|----|
| [build()](#bambi.Model.build) | Set up the model for sampling/fitting |
| [compute_log_likelihood()](#bambi.Model.compute_log_likelihood) | Compute the model's log-likelihood |
| [compute_log_prior()](#bambi.Model.compute_log_prior) | Compute the model's log-prior |
| [fit()](#bambi.Model.fit) | Fit the model using PyMC |
| [get_covariates()](#bambi.Model.get_covariates) | Return observed covariate names from formulas and expressions. |
| [get_terms()](#bambi.Model.get_terms) | Return formula terms from all conditional quantities. |
| [graph()](#bambi.Model.graph) | Produce a graphviz Digraph from a built Bambi model. |
| [plot_priors()](#bambi.Model.plot_priors) | Samples from the prior distribution and plots its marginals. |
| [predict()](#bambi.Model.predict) | Predict method for Bambi models |
| [prior_predictive()](#bambi.Model.prior_predictive) | Generate samples from the prior predictive distribution. |
| [r2_score()](#bambi.Model.r2_score) | Bayesian R² for regression models. |
| [set_alias()](#bambi.Model.set_alias) | Set aliases for the terms and auxiliary parameters in the model |
| [set_priors()](#bambi.Model.set_priors) | Set priors for one or more existing terms. |

### build()

Set up the model for sampling/fitting

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L671-L678)

``` python
build()
```

Creates an instance of the underlying PyMC model and adds all the necessary terms to it.

### compute_log_likelihood()

Compute the model's log-likelihood

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L1358-L1382)

``` python
compute_log_likelihood(
    idata,
    data=None,
    inplace=True,
    progressbar=False,
)
```

#### Parameters

`idata: DataTree`  
The `DataTree` instance returned by `.fit()`.

`data: pd.DataFrame or None = None`  
An optional data frame with values for the predictors and the response on which the model's log-likelihood function is evaluated. If omitted, the original dataset is used.

`inplace: bool = True`  
If `True` it will modify `idata` in-place. Otherwise, it will return a copy of `idata` with the `log_likelihood` group added.

`progressbar: bool = False`  
Whether to display the log-likelihood computation progress bar. Defaults to `False`.

#### Returns

`DataTree or None`  

### compute_log_prior()

Compute the model's log-prior

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L1494-L1512)

``` python
compute_log_prior(
    idata,
    inplace=True,
)
```

#### Parameters

`idata: DataTree`  
The `DataTree` instance returned by `.fit()`.

`inplace: bool = True`  
If `True` it will modify `idata` in-place. Otherwise, it will return a copy of `idata` with the `log_prior` group added.

#### Returns

`DataTree or None`  

### fit()

Fit the model using PyMC

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L520-L669)

``` python
fit(
    draws=1000,
    tune=1000,
    discard_tuned_samples=True,
    omit_offsets=True,
    include_mean=None,
    include_response_params=False,
    inference_method=None,
    init="auto",
    n_init=50000,
    chains=None,
    cores=None,
    random_seed=None,
    nuts=None,
    **kwargs,
)
```

#### Parameters

`draws: int = 1000`  
The number of samples to draw from the posterior distribution. Defaults to 1000.

`tune: int = 1000`  
Number of iterations to tune. Defaults to 1000. Samplers adjust the step sizes, scalings or similar during tuning. These tuning samples are be drawn in addition to the number specified in the `draws` argument, and will be discarded unless `discard_tuned_samples` is set to `False`.

`discard_tuned_samples: bool = True`  
Whether to discard posterior samples of the tune interval. Defaults to `True`.

`omit_offsets: bool = True`  
Omits offset terms in the `DataTree` object returned when the model includes group specific effects. Defaults to `True`.

`include_mean: (bool, optional, deprecated) = None`  
**This argument is deprecated and will be removed in future versions**. Use `include_response_params`.

`include_response_params: bool = False`  
Include parameters of the response distribution in the output. These usually take more space than other parameters as there's one of them per observation. Defaults to `False`.

`inference_method: str or None = None`  
The method to use for fitting the model. If `None` (default), Bambi lets the backend select the MCMC sampler: PyMC uses nutpie when it is installed and compatible with the model and sampling options, otherwise it uses its built-in sampler. Pass `"pymc"` to always use the built-in sampler. NUTS implementations include `"pymc"`, `"nutpie"`, `"blackjax"`, and `"numpyro"`. Alternatively, `"vi"` fits the model using variational inference as implemented in PyMC's [fit](../reference/Model.fit.md) function. Finally, `"laplace"` uses a Laplace approximation and is not recommended other than for pedagogical use.

`init: str = "auto"`  
Initialization method. Defaults to `"auto"`. The available methods are:

- `"auto"`: Use `"jitter+adapt_diag"` and if this method fails it uses `"adapt_diag"`.
- `"adapt_diag"`: Start with an identity mass matrix and then adapt a diagonal based on the variance of the tuning samples. All chains use the test value (usually the prior mean) as starting point.
- `"jitter+adapt_diag"`: Same as `"adapt_diag"`, but use test value plus a uniform jitter in \[-1, 1\] as starting point in each chain.
- `"advi+adapt_diag"`: Run ADVI and then adapt the resulting diagonal mass matrix based on the sample variance of the tuning samples.
- `"advi+adapt_diag_grad"`: Run ADVI and then adapt the resulting diagonal mass matrix based on the variance of the gradients during tuning. This is **experimental** and might be removed in a future release.
- `"advi"`: Run ADVI to estimate posterior mean and diagonal mass matrix.
- `"advi_map"`: Initialize ADVI with MAP and use MAP as starting point.
- `"map"`: Use the MAP as starting point. This is strongly discouraged.
- `"adapt_full"`: Adapt a dense mass matrix using the sample covariances. All chains use the test value (usually the prior mean) as starting point.
- `"jitter+adapt_full"`: Same as `"adapt_full"`, but use test value plus a uniform jitter in \[-1, 1\] as starting point in each chain.

`n_init: int = 50000`  
Number of initialization iterations. Only works for `"advi"` init methods.

`chains: int = None`  
The number of chains to sample. Running independent chains is important for some convergence statistics and can also reveal multiple modes in the posterior. If `None`, then set to either `cores` or 2, whichever is larger.

`cores: int = None`  
The number of chains to run in parallel. If `None`, it is equal to the number of CPUs in the system unless there are more than 4 CPUs, in which case it is set to 4.

`random_seed: int or list of ints = None`  
A list is accepted if cores is greater than one.

`nuts: dict = None`  
A dictionary of NUTS sampler settings passed directly to `pm.sample(nuts=...)`, e.g. `model.fit(nuts={"target_accept": 0.9, "max_treedepth": 12})`.

`kwargs: dict = {}`  
For other kwargs see the documentation for `pm.sample()`.

#### Returns

`DataTree or Approximation`  
It returns a `DataTree` if `inference_method` is `"pymc"`, `"nutpie"`, `"blackjax"`, `"numpyro"`, or `"laplace"`, and an `Approximation` object if `"vi"`.

### get_covariates()

Return observed covariate names from formulas and expressions.

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L488-L518)

``` python
get_covariates()
```

### get_terms()

Return formula terms from all conditional quantities.

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L478-L486)

``` python
get_terms()
```

### graph()

Produce a graphviz Digraph from a built Bambi model.

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L1514-L1568)

``` python
graph(
    formatting="plain",
    name=None,
    figsize=None,
    dpi=300,
    fmt="png",
)
```

Requires graphviz, which may be installed most easily with:

``` cmd
conda install -c conda-forge python-graphviz
```

Alternatively, you may install the `graphviz` binaries yourself, and then `pip install graphviz` to get the python bindings. See <http://graphviz.readthedocs.io/en/stable/manual.html> for more information.

#### Parameters

`formatting: str = "plain"`  
One of `"plain"` or `"plain_with_params"`. Defaults to `"plain"`.

`name: str = None`  
Name of the figure to save. Defaults to `None`, no figure is saved.

`figsize: tuple = None`  
Maximum width and height of figure in inches. Defaults to `None`, the figure size is set automatically. If defined and the drawing is larger than the given size, the drawing is uniformly scaled down so that it fits within the given size. Only works if `name` is not `None`.

`dpi: int = 300`  
Point per inch of the figure to save. Defaults to 300. Only works if `name` is not `None`.

`fmt: str = "png"`  
Format of the figure to save. Defaults to `"png"`. Only works if `name` is not `None`.

#### Returns

`graphviz.Digraph`  
The graph

#### Examples

``` python
model = Model("y ~ x + (1|z)")
model.fit()
model.graph()
```

### plot_priors()

Samples from the prior distribution and plots its marginals.

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L1015-L1184)

``` python
plot_priors(
    draws=5000,
    var_names=None,
    filter_vars=None,
    kind="kde",
    ci_kind=None,
    ci_prob=None,
    point_estimate=None,
    plot_collection=None,
    backend=None,
    labeller=None,
    aes_by_visuals=None,
    visuals=None,
    stats=None,
    figsize=None,
    omit_offsets=True,
    omit_group_specific=True,
    random_seed=None,
    bins=None,
    hdi_prob=None,
    round_to=None,
    **pc_kwargs,
)
```

#### Parameters

`draws: int = 5000`  
Number of draws to sample from the prior predictive distribution. Defaults to 5000.

`var_names: str or list of str = None`  
A list of names of variables for which to compute the prior predictive distribution. Defaults to `None` which means to include both observed and unobserved RVs.

`filter_vars: (like, regex) = "like"`  
If `None`, interpret `var_names` as the real variable names. If `"like"`, interpret `var_names` as substrings of the real variable names. If `"regex"`, interpret `var_names` as regular expressions on the real variable names. Forwarded to [arviz_plots.plot_dist()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.plot_dist.html#arviz_plots.plot_dist).

`kind: str = "kde"`  
Type of plot to display (`"kde"` or `"hist"`). For discrete variables this argument is ignored and a histogram is always used. Forwarded to [arviz_plots.plot_dist()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.plot_dist.html#arviz_plots.plot_dist).

`ci_kind: (eti, hdi) = "eti"`  
Which credible interval to use. Defaults to `arviz_base.rcParams["stats.ci_kind"]`. Forwarded to [arviz_plots.plot_dist()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.plot_dist.html#arviz_plots.plot_dist).

`ci_prob: float = None`  
Indicates the probability that should be contained within the plotted credible interval. Defaults to `arviz_base.rcParams["stats.ci_prob"]`. Forwarded to [arviz_plots.plot_dist()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.plot_dist.html#arviz_plots.plot_dist).

`point_estimate: str = None`  
Plot point estimate per variable. Values should be `"mean"`, `"median"`, `"mode"` or `None`. When `None` (default) use `arviz_base.rcParams["stats.point_estimate"]`. Forwarded to [arviz_plots.plot_dist()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.plot_dist.html#arviz_plots.plot_dist).

`plot_collection: arviz_plots.PlotCollection = None`  
The plot collection to use. Forwarded to [arviz_plots.plot_dist()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.plot_dist.html#arviz_plots.plot_dist).

`backend: (matplotlib, plotly, bokeh) = "matplotlib"`  
The backend to use for plotting. If `None`, it inspects whether `plot_connection` is not `None`. If it's not, it uses `plot_collection.backend`. Otherwise, it uses `arviz_base.rcParams["plot.backend"]`. Forwarded to [arviz_plots.plot_dist()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.plot_dist.html#arviz_plots.plot_dist).

`labeller: arviz_base.labels.BaseLabeller = None`  
The labeller. If `None`, it uses [arviz_base.labels.BaseLabeller](https://arviz-base.readthedocs.io/en/latest/api/generated/arviz_base.labels.BaseLabeller.html#arviz_base.labels.BaseLabeller). Forwarded to [arviz_plots.plot_dist()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.plot_dist.html#arviz_plots.plot_dist).

`aes_by_visuals: mapping of {str : sequence of str} = None`  
Forwarded to [arviz_plots.plot_dist()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.plot_dist.html#arviz_plots.plot_dist). See `aes_by_visuals` in there.

`visuals: mapping of {str : mapping or bool} = None`  
Forwarded to [arviz_plots.plot_dist()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.plot_dist.html#arviz_plots.plot_dist). See `visuals` in there.

`stats: mapping = None`  
Forwarded to [arviz_plots.plot_dist()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.plot_dist.html#arviz_plots.plot_dist). See `stats` in there.

`figsize: tuple = None`  
Figure size. If `None` it will be defined automatically.

`omit_offsets: bool = True`  
Whether to omit offset terms in the plot. Defaults to `True`.

`omit_group_specific: bool = True`  
Whether to omit group specific effects in the plot. Defaults to `True`.

`random_seed: int or None = None`  
Seed for random number generator. Passed down to [Model.prior_predictive](../reference/Model.prior_predictive.md).

`bins: (int, optional, deprecated) = None`  
**This argument is deprecated and will be removed in future versions**.

`hdi_prob: (float or str, optional, deprecated) = None`  
Plots highest density interval for chosen percentage of density. Use `"hide"` to hide the highest density interval. **This argument is deprecated and will be removed in future versions**.

`round_to: (int, optional, deprecated) = None`  
Controls formatting of floats. Defaults to 2 or the integer part, whichever is bigger. **This argument is deprecated and will be removed in future versions**.

`pc_kwargs: dict = {}`  
Passed to [arviz_plots.PlotCollection.wrap()](https://arviz-plots.readthedocs.io/en/latest/api/generated/arviz_plots.PlotCollection.wrap.html#arviz_plots.PlotCollection.wrap)

#### Returns

`pc: arviz_plots.PlotCollection`  

### predict()

Predict method for Bambi models

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L1216-L1356)

``` python
predict(
    idata,
    kind="response_params",
    data=None,
    inplace=True,
    include_group_specific=True,
    sample_new_groups=None,
    random_seed=None,
    progressbar=False,
    draws=None,
    thin=None,
)
```

Obtains in-sample and out-of-sample predictions from a fitted Bambi model.

#### Parameters

`idata: DataTree`  
The `DataTree` instance returned by `.fit()`.

`kind: str = "response_params"`  
Indicates the type of prediction required. Can be `"response_params"`, `"response"`, `"response_conditional"`, or `"time_and_cause"`.

- `"response_params"` returns draws from the posterior distribution of the likelihood parameters.
- `"response"` returns draws from the posterior predictive response distribution. It is available for every response type and ignores censoring or truncation of the observed response. For competing-risks responses, it draws the first-event time.
- `"response_conditional"` is available for censored, truncated, and competing-risks responses only. For censored responses, it conditions the underlying response on the observed censoring restriction. For truncated responses, it draws from the truncated distribution. For competing risks, it conditions right-censored observations on the first event occurring after the observed time. Exact events are drawn as `"response"`.
- `"time_and_cause"` is available for competing-risks responses only. It returns first-event times and one-based cause codes in separate variables.

Defaults to `"response_params"`.

`data: pd.DataFrame or None = None`  
An optional data frame with values for the predictors that are used to obtain out-of-sample predictions. If omitted, the original dataset is used.

`inplace: bool = True`  
If `True` it will modify `idata` in-place. Otherwise, it will return a copy of `idata` with the predictions added. If `kind="response_params"`, a new variable with the name of the parent parameter, e.g. `"mu"` and `"sigma"` for a Gaussian likelihood, or `"p"` for a Bernoulli likelihood, is added to the `posterior` group for in-sample predictions or to [predictions](../reference/interpret.predictions.md) for out-of-sample data. With `kind="response"`, the draws are added to `posterior_predictive` in sample or to [predictions](../reference/interpret.predictions.md) out of sample. The same applies to `kind="response_conditional"`. With `kind="time_and_cause"`, the first-event times and cause codes are added as separate variables named `<response>_time` and `<response>_cause`. Existing output groups are overwritten. For a transformed univariate response, `<response>` is the first argument of the transformation; for example, predictions from `censored(y, status)` are named `y`. A `counts(y1, y2)` response is named `y1_y2`.

`include_group_specific: bool = True`  
Determines if predictions incorporate group-specific effects. If `False`, predictions are made with common effects only (i.e. group specific are set to zero). Defaults to `True`.

`sample_new_groups: bool or None = None`  
Deprecated and has no effect. Bambi automatically determines how to predict for new groups based on the type of group. Defaults to `None`.

`random_seed: (int, RandomState or Generator) = None`  
Seed for the random number generator.

`progressbar: bool = False`  
Whether to display a progress bar. Defaults to `False`.

`draws: int or None = None`  
The number of posterior draws per chain used to obtain predictions. The draws are evenly spaced, and the returned `DataTree` only contains the draws that were used. Cannot be used together with `thin`. Requires `inplace=False`. Defaults to `None`, which uses all the posterior draws.

`thin: int or None = None`  
Keep only every `thin`-th posterior draw (see `arviz_stats.thin`). The returned `DataTree` only contains the draws that were used. Cannot be used together with `draws`. Requires `inplace=False`. Defaults to `None`.

#### Returns

`DataTree or None`  

### prior_predictive()

Generate samples from the prior predictive distribution.

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L1186-L1214)

``` python
prior_predictive(
    draws=500,
    var_names=None,
    omit_offsets=True,
    random_seed=None,
)
```

#### Parameters

`draws: int = 500`  
Number of draws to sample from the prior predictive distribution. Defaults to 500.

`var_names: str, list of str or None = None`  
A list of names of variables for which to compute the prior predictive distribution. Defaults to `None` which means both observed and unobserved RVs.

`omit_offsets: bool = True`  
Whether to omit offset terms in the plot. Defaults to `True`.

`random_seed: int or None = None`  
Seed for the random number generator.

#### Returns

`DataTree`  
`DataTree` object with the groups `prior`, [prior_predictive](../reference/Model.prior_predictive.md) and `observed_data`, and, when applicable, `constant_data`.

### r2_score()

Bayesian R² for regression models.

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L1384-L1492)

``` python
r2_score(
    idata,
    summary=True,
)
```

The R², or coefficient of determination, is defined as the proportion of variance in the data that is explained by the model. For details, see the reference below.

All the variance terms come from the model. For each posterior draw $`s`$,

``` math
R^2_s = \frac{V_{n=1}^N y_n^{\mathrm{pred}\,s}}
{V_{n=1}^N y_n^{\mathrm{pred}\,s} + \mathrm{var}_{\mathrm{res}}^s}
```

where $`y_n^{\mathrm{pred}\,s} = E(\tilde y_n \mid X_n, \theta^s)`$ is the modeled predictive mean and $`\mathrm{var}_{\mathrm{res}}^s = \frac{1}{N}\sum_{n=1}^N
\mathrm{Var}(\tilde y_n \mid X_n, \theta^s)`$ is the modeled residual variance. The operator $`V_{n=1}^N`$ denotes the sample variance across observations. Both are computed on the response scale (after applying the inverse link functions) using the mean and variance of the response distribution of the family. For example, the conditional variance is $`\sigma^2`$ for the Gaussian family, $`p(1 - p)`$ for the Bernoulli family, and $`\mu`$ for the Poisson family. For the von Mises family, the circular variance $`1 - I_1(\kappa) / I_0(\kappa)`$ is used and the circular $`R^2`$ is computed (see `arviz_stats.bayesian_r2`).

When the modeled mean or variance is infinite for some posterior draws (e.g. a Student's t with $`\nu \le 2`$), the Bayesian R² is not defined and the residual R², which uses the variance of the residuals $`y_n - y_n^{\mathrm{pred}\,s}`$, is returned instead with a warning.

#### Parameters

`idata: DataTree`  
The `DataTree` instance returned by `.fit()`. If its `posterior` group does not contain the parameters of the response distribution, they are computed with `.predict(idata, kind="response_params")` and added to `idata`.

`summary: bool = True`  
If `True`, it returns a summary of the R². Otherwise, it returns the posterior draws of the R².

#### Returns

`namedtuple or np.ndarray`  
If `summary=True`, a named tuple with a point estimate and the bounds of a credible interval. Otherwise, an array with the R² for each posterior draw.

#### Raises

`NotImplementedError`  
If the conditional variance is not defined or not implemented for the family (e.g. categorical, ordinal, multivariate, and mixture cure responses), or the response is censored, truncated, constrained, or has competing risks.

#### References

Gelman, A., Goodrich, B., Gabry, J., and Vehtari, A. (2019). *R-squared for Bayesian regression models*. The American Statistician, 73(3), 307-309. <https://doi.org/10.1080/00031305.2018.1549100>

### set_alias()

Set aliases for the terms and auxiliary parameters in the model

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L861-L1005)

``` python
set_alias(aliases)
```

#### Parameters

`aliases: dict`  
Map original names to aliases. For distributional and nonlinear models, use nested dictionaries keyed by modeled parameter names. Inside each dictionary, map term names or the parameter's own name to strings. Response and marginal parameter aliases use strings directly, as do marginal coefficients. For example, `{"a": {"a": "baseline", "Intercept": "a0"}, "mu": {"mu": "mean"}, "y": "response"}` aliases a nonlinear coefficient, its intercept, the parent, and the response. Formulas and prior dictionaries continue to use original names. The model must be rebuilt after setting aliases.

#### Returns

`None`  

### set_priors()

Set priors for one or more existing terms.

Usage

[Source](https://github.com/bambinos/bambi/blob/main/bambi/models.py#L680-L741)

``` python
set_priors(
    priors=None,
    common=None,
    group_specific=None,
)
```

#### Parameters

`priors: dict or None = None`  
Dictionary of priors to update. Accepts the same specification as the `priors` argument of [Model](../reference/Model.md), and entries here take precedence over the `common` and `group_specific` arguments. Names that don't match any term or component are reported with a warning; set `bmb.config["UNUSED_PRIORS"]` to `"error"` or `"ignore"` to change that.

`common: (Prior, int, float or None) = None`  
A prior specification to apply to all common terms included in the model.

`group_specific: (Prior, int, float or None) = None`  
A prior specification to apply to all group specific terms included in the model.
