INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Extract sample_stats from PyMC3 trace. | def sample_stats_to_xarray(self):
"""Extract sample_stats from PyMC3 trace."""
rename_key = {"model_logp": "lp"}
data = {}
for stat in self.trace.stat_names:
name = rename_key.get(stat, stat)
data[name] = np.array(self.trace.get_sampler_stats(stat, combine=False))... |
Convert posterior_predictive samples to xarray. | def posterior_predictive_to_xarray(self):
"""Convert posterior_predictive samples to xarray."""
data = {k: np.expand_dims(v, 0) for k, v in self.posterior_predictive.items()}
return dict_to_dataset(data, library=self.pymc3, coords=self.coords, dims=self.dims) |
Convert prior samples to xarray. | def prior_to_xarray(self):
"""Convert prior samples to xarray."""
return dict_to_dataset(
{k: np.expand_dims(v, 0) for k, v in self.prior.items()},
library=self.pymc3,
coords=self.coords,
dims=self.dims,
) |
Convert observed data to xarray. | def observed_data_to_xarray(self):
"""Convert observed data to xarray."""
# This next line is brittle and may not work forever, but is a secret
# way to access the model from the trace.
model = self.trace._straces[0].model # pylint: disable=protected-access
observations = {obs.... |
Plot Posterior densities in the style of John K. Kruschke's book.
Parameters
----------
data : obj
Any object that can be converted to an az.InferenceData object
Refer to documentation of az.convert_to_dataset for details
var_names : list of variable names
Variables to be plotte... | def plot_posterior(
data,
var_names=None,
coords=None,
figsize=None,
textsize=None,
credible_interval=0.94,
round_to=1,
point_estimate="mean",
rope=None,
ref_val=None,
kind="kde",
bw=4.5,
bins=None,
ax=None,
**kwargs
):
"""Plot Posterior densities in the s... |
Artist to draw posterior. | def _plot_posterior_op(
values,
var_name,
selection,
ax,
bw,
linewidth,
bins,
kind,
point_estimate,
round_to,
credible_interval,
ref_val,
rope,
ax_labelsize,
xt_labelsize,
**kwargs
): # noqa: D202
"""Artist to draw posterior."""
def format_as_per... |
r"""Calculate the estimated Bayesian fraction of missing information (BFMI).
BFMI quantifies how well momentum resampling matches the marginal energy distribution. For more
information on BFMI, see https://arxiv.org/pdf/1604.00695v1.pdf. The current advice is that
values smaller than 0.3 indicate poor samp... | def bfmi(energy):
r"""Calculate the estimated Bayesian fraction of missing information (BFMI).
BFMI quantifies how well momentum resampling matches the marginal energy distribution. For more
information on BFMI, see https://arxiv.org/pdf/1604.00695v1.pdf. The current advice is that
values smaller than ... |
r"""Compare models based on WAIC or LOO cross validation.
WAIC is Widely applicable information criterion, and LOO is leave-one-out
(LOO) cross-validation. Read more theory here - in a paper by some of the
leading authorities on model selection - dx.doi.org/10.1111/1467-9868.00353
Parameters
-----... | def compare(
dataset_dict,
ic="waic",
method="BB-pseudo-BMA",
b_samples=1000,
alpha=1,
seed=None,
scale="deviance",
):
r"""Compare models based on WAIC or LOO cross validation.
WAIC is Widely applicable information criterion, and LOO is leave-one-out
(LOO) cross-validation. Read... |
Store the previously computed pointwise predictive accuracy values (ics) in a 2D matrix. | def _ic_matrix(ics, ic_i):
"""Store the previously computed pointwise predictive accuracy values (ics) in a 2D matrix."""
cols, _ = ics.shape
rows = len(ics[ic_i].iloc[0])
ic_i_val = np.zeros((rows, cols))
for idx, val in enumerate(ics.index):
ic = ics.loc[val][ic_i]
if len(ic) != ... |
Calculate highest posterior density (HPD) of array for given credible_interval.
The HPD is the minimum width Bayesian credible interval (BCI). This implementation works only
for unimodal distributions.
Parameters
----------
x : Numpy array
An array containing posterior samples
credible... | def hpd(x, credible_interval=0.94, circular=False):
"""
Calculate highest posterior density (HPD) of array for given credible_interval.
The HPD is the minimum width Bayesian credible interval (BCI). This implementation works only
for unimodal distributions.
Parameters
----------
x : Numpy ... |
Stable logsumexp when b >= 0 and b is scalar.
b_inv overwrites b unless b_inv is None. | def _logsumexp(ary, *, b=None, b_inv=None, axis=None, keepdims=False, out=None, copy=True):
"""Stable logsumexp when b >= 0 and b is scalar.
b_inv overwrites b unless b_inv is None.
"""
# check dimensions for result arrays
ary = np.asarray(ary)
if ary.dtype.kind == "i":
ary = ary.astype... |
Pareto-smoothed importance sampling leave-one-out cross-validation.
Calculates leave-one-out (LOO) cross-validation for out of sample predictive model fit,
following Vehtari et al. (2017). Cross-validation is computed using Pareto-smoothed
importance sampling (PSIS).
Parameters
----------
data... | def loo(data, pointwise=False, reff=None, scale="deviance"):
"""Pareto-smoothed importance sampling leave-one-out cross-validation.
Calculates leave-one-out (LOO) cross-validation for out of sample predictive model fit,
following Vehtari et al. (2017). Cross-validation is computed using Pareto-smoothed
... |
Pareto smoothed importance sampling (PSIS).
Parameters
----------
log_weights : array
Array of size (n_samples, n_observations)
reff : float
relative MCMC efficiency, `ess / n`
Returns
-------
lw_out : array
Smoothed log weights
kss : array
Pareto tail i... | def psislw(log_weights, reff=1.0):
"""
Pareto smoothed importance sampling (PSIS).
Parameters
----------
log_weights : array
Array of size (n_samples, n_observations)
reff : float
relative MCMC efficiency, `ess / n`
Returns
-------
lw_out : array
Smoothed lo... |
Estimate the parameters for the Generalized Pareto Distribution (GPD).
Empirical Bayes estimate for the parameters of the generalized Pareto
distribution given the data.
Parameters
----------
x : array
sorted 1D data array
Returns
-------
k : float
estimated shape para... | def _gpdfit(x):
"""Estimate the parameters for the Generalized Pareto Distribution (GPD).
Empirical Bayes estimate for the parameters of the generalized Pareto
distribution given the data.
Parameters
----------
x : array
sorted 1D data array
Returns
-------
k : float
... |
R² for Bayesian regression models. Only valid for linear models.
Parameters
----------
y_true: : array-like of shape = (n_samples) or (n_samples, n_outputs)
Ground truth (correct) target values.
y_pred : array-like of shape = (n_samples) or (n_samples, n_outputs)
Estimated target values... | def r2_score(y_true, y_pred):
"""R² for Bayesian regression models. Only valid for linear models.
Parameters
----------
y_true: : array-like of shape = (n_samples) or (n_samples, n_outputs)
Ground truth (correct) target values.
y_pred : array-like of shape = (n_samples) or (n_samples, n_out... |
Make ufunc from function. | def _make_ufunc(func, index=Ellipsis, **kwargs): # noqa: D202
"""Make ufunc from function."""
def _ufunc(ary):
target = np.empty(ary.shape[:-2])
for idx in np.ndindex(target.shape):
target[idx] = np.asarray(func(ary[idx].ravel(), **kwargs))[index]
return target
return ... |
Calculate the simulation standard error, accounting for non-independent samples.
The trace is divided into batches, and the standard deviation of the batch
means is calculated.
Parameters
----------
x : Numpy array
An array containing MCMC samples
batches : integer
Number of ba... | def _mc_error(x, batches=5, circular=False):
"""Calculate the simulation standard error, accounting for non-independent samples.
The trace is divided into batches, and the standard deviation of the batch
means is calculated.
Parameters
----------
x : Numpy array
An array containing MCM... |
Calculate the widely available information criterion.
Also calculates the WAIC's standard error and the effective number of
parameters of the samples in trace from model. Read more theory here - in
a paper by some of the leading authorities on model selection
dx.doi.org/10.1111/1467-9868.00353
Par... | def waic(data, pointwise=False, scale="deviance"):
"""Calculate the widely available information criterion.
Also calculates the WAIC's standard error and the effective number of
parameters of the samples in trace from model. Read more theory here - in
a paper by some of the leading authorities on model... |
Plot posterior of traces as violin plot.
Notes
-----
If multiple chains are provided for a variable they will be combined
Parameters
----------
data : obj
Any object that can be converted to an az.InferenceData object
Refer to documentation of az.convert_to_dataset for details
... | def plot_violin(
data,
var_names=None,
quartiles=True,
credible_interval=0.94,
shade=0.35,
bw=4.5,
sharey=True,
figsize=None,
textsize=None,
ax=None,
kwargs_shade=None,
):
"""Plot posterior of traces as violin plot.
Notes
-----
If multiple chains are provided... |
Auxiliary function to plot violinplots. | def _violinplot(val, shade, bw, ax, **kwargs_shade):
"""Auxiliary function to plot violinplots."""
density, low_b, up_b = _fast_kde(val, bw=bw)
x = np.linspace(low_b, up_b, len(density))
x = np.concatenate([x, x[::-1]])
density = np.concatenate([-density, density[::-1]])
ax.fill_betweenx(x, de... |
Auxiliary function to plot discrete-violinplots. | def cat_hist(val, shade, ax, **kwargs_shade):
"""Auxiliary function to plot discrete-violinplots."""
bins = get_bins(val)
binned_d, _ = np.histogram(val, bins=bins, normed=True)
bin_edges = np.linspace(np.min(val), np.max(val), len(bins))
centers = 0.5 * (bin_edges + np.roll(bin_edges, 1))[:-1]
... |
Plot a scatter or hexbin of two variables with their respective marginals distributions.
Parameters
----------
data : obj
Any object that can be converted to an az.InferenceData object
Refer to documentation of az.convert_to_dataset for details
var_names : Iter of 2 e.g. (var_1, var_2)
... | def plot_joint(
data,
var_names=None,
coords=None,
figsize=None,
textsize=None,
kind="scatter",
gridsize="auto",
contour=True,
fill_last=True,
joint_kwargs=None,
marginal_kwargs=None,
):
"""
Plot a scatter or hexbin of two variables with their respective marginals dis... |
Plot hpd intervals for regression data.
Parameters
----------
x : array-like
Values to plot
y : array-like
values from which to compute the hpd
credible_interval : float, optional
Credible interval to plot. Defaults to 0.94.
color : str
Color used for the limit... | def plot_hpd(
x,
y,
credible_interval=0.94,
color="C1",
circular=False,
smooth=True,
smooth_kwargs=None,
fill_kwargs=None,
plot_kwargs=None,
ax=None,
):
"""
Plot hpd intervals for regression data.
Parameters
----------
x : array-like
Values to plot
... |
r"""Calculate estimate of the effective sample size.
Parameters
----------
data : obj
Any object that can be converted to an az.InferenceData object
Refer to documentation of az.convert_to_dataset for details
At least 2 posterior chains are needed to compute this diagnostic of one o... | def effective_sample_size(data, *, var_names=None):
r"""Calculate estimate of the effective sample size.
Parameters
----------
data : obj
Any object that can be converted to an az.InferenceData object
Refer to documentation of az.convert_to_dataset for details
At least 2 posteri... |
Ufunc for computing effective sample size.
This can be used on an xarray Dataset, using
`xr.apply_ufunc(_ess_ufunc, ..., input_core_dims=(('chain', 'draw'),)) | def _ess_ufunc(ary):
"""Ufunc for computing effective sample size.
This can be used on an xarray Dataset, using
`xr.apply_ufunc(_ess_ufunc, ..., input_core_dims=(('chain', 'draw'),))
"""
target = np.empty(ary.shape[:-2])
for idx in np.ndindex(target.shape):
target[idx] = _get_ess(ary[id... |
Compute the effective sample size for a 2D array. | def _get_ess(sample_array):
"""Compute the effective sample size for a 2D array."""
shape = sample_array.shape
if len(shape) != 2:
raise TypeError("Effective sample size calculation requires 2 dimensional arrays.")
n_chain, n_draws = shape
if n_chain <= 1:
raise TypeError("Effective ... |
r"""Compute estimate of Split R-hat for a set of traces.
The Split R-hat diagnostic tests for lack of convergence by comparing the variance between
multiple chains to the variance within each chain. If convergence has been achieved, the
between-chain and within-chain variances should be identical. To be mo... | def rhat(data, var_names=None):
r"""Compute estimate of Split R-hat for a set of traces.
The Split R-hat diagnostic tests for lack of convergence by comparing the variance between
multiple chains to the variance within each chain. If convergence has been achieved, the
between-chain and within-chain var... |
Ufunc for computing effective sample size.
This can be used on an xarray Dataset, using
`xr.apply_ufunc(_neff_ufunc, ..., input_core_dims=(('chain', 'draw'),)) | def _rhat_ufunc(ary):
"""Ufunc for computing effective sample size.
This can be used on an xarray Dataset, using
`xr.apply_ufunc(_neff_ufunc, ..., input_core_dims=(('chain', 'draw'),))
"""
target = np.empty(ary.shape[:-2])
for idx in np.ndindex(target.shape):
target[idx] = _get_split_rh... |
Compute the split-rhat for a 2d array. | def _get_split_rhat(values, round_to=2):
"""Compute the split-rhat for a 2d array."""
shape = values.shape
if len(shape) != 2:
raise TypeError("Effective sample size calculation requires 2 dimensional arrays.")
_, num_samples = shape
num_split = num_samples // 2
# Calculate split chain m... |
r"""Compute z-scores for convergence diagnostics.
Compare the mean of the first % of series with the mean of the last % of series. x is divided
into a number of segments for which this difference is computed. If the series is converged,
this score should oscillate between -1 and 1.
Parameters
----... | def geweke(values, first=0.1, last=0.5, intervals=20):
r"""Compute z-scores for convergence diagnostics.
Compare the mean of the first % of series with the mean of the last % of series. x is divided
into a number of segments for which this difference is computed. If the series is converged,
this score ... |
Display a summary of Pareto tail indices.
Parameters
----------
pareto_tail_indices : array
Pareto tail indices.
Returns
-------
df_k : dataframe
Dataframe containing k diagnostic values. | def ks_summary(pareto_tail_indices):
"""Display a summary of Pareto tail indices.
Parameters
----------
pareto_tail_indices : array
Pareto tail indices.
Returns
-------
df_k : dataframe
Dataframe containing k diagnostic values.
"""
kcounts, _ = np.histogram(pareto_tail_... |
Plot distribution (histogram or kernel density estimates) and sampled values.
If `divergences` data is available in `sample_stats`, will plot the location of divergences as
dashed vertical lines.
Parameters
----------
data : obj
Any object that can be converted to an az.InferenceData objec... | def plot_trace(
data,
var_names=None,
coords=None,
divergences="bottom",
figsize=None,
textsize=None,
lines=None,
combined=False,
plot_kwargs=None,
fill_kwargs=None,
rug_kwargs=None,
hist_kwargs=None,
trace_kwargs=None,
):
"""Plot distribution (histogram or kernel... |
Add a histogram for the data to the axes. | def _histplot_op(ax, data, **kwargs):
"""Add a histogram for the data to the axes."""
bins = get_bins(data)
ax.hist(data, bins=bins, align="left", density=True, **kwargs)
return ax |
Concatenate InferenceData objects on a group level.
Supports only concatenating with independent unique groups.
Parameters
----------
*args : InferenceData
Variable length InferenceData list or
Sequence of InferenceData.
copy : bool
If True, groups are copied to the new Inf... | def concat(*args, copy=True, inplace=False):
"""Concatenate InferenceData objects on a group level.
Supports only concatenating with independent unique groups.
Parameters
----------
*args : InferenceData
Variable length InferenceData list or
Sequence of InferenceData.
copy : bo... |
Initialize object from a netcdf file.
Expects that the file will have groups, each of which can be loaded by xarray.
Parameters
----------
filename : str
location of netcdf file
Returns
-------
InferenceData object | def from_netcdf(filename):
"""Initialize object from a netcdf file.
Expects that the file will have groups, each of which can be loaded by xarray.
Parameters
----------
filename : str
location of netcdf file
Returns
-------
InferenceData obj... |
Write InferenceData to file using netcdf4.
Parameters
----------
filename : str
Location to write to
compress : bool
Whether to compress result. Note this saves disk space, but may make
saving and loading somewhat slower (default: True).
Retu... | def to_netcdf(self, filename, compress=True):
"""Write InferenceData to file using netcdf4.
Parameters
----------
filename : str
Location to write to
compress : bool
Whether to compress result. Note this saves disk space, but may make
saving a... |
Convert Dictionary data into an InferenceData object.
Parameters
----------
posterior : dict
posterior_predictive : dict
sample_stats : dict
"log_likelihood" variable for stats needs to be here.
prior : dict
prior_predictive : dict
observed_data : dict
coords : dict[str, ite... | def from_dict(
posterior=None,
*,
posterior_predictive=None,
sample_stats=None,
prior=None,
prior_predictive=None,
sample_stats_prior=None,
observed_data=None,
coords=None,
dims=None
):
"""Convert Dictionary data into an InferenceData object.
Parameters
----------
... |
Convert posterior samples to xarray. | def posterior_to_xarray(self):
"""Convert posterior samples to xarray."""
data = self.posterior
if not isinstance(data, dict):
raise TypeError("DictConverter.posterior is not a dictionary")
if "log_likelihood" in data:
warnings.warn(
"log_likeliho... |
Convert sample_stats samples to xarray. | def sample_stats_to_xarray(self):
"""Convert sample_stats samples to xarray."""
data = self.sample_stats
if not isinstance(data, dict):
raise TypeError("DictConverter.sample_stats is not a dictionary")
return dict_to_dataset(data, library=None, coords=self.coords, dims=self.... |
Convert posterior_predictive samples to xarray. | def posterior_predictive_to_xarray(self):
"""Convert posterior_predictive samples to xarray."""
data = self.posterior_predictive
if not isinstance(data, dict):
raise TypeError("DictConverter.posterior_predictive is not a dictionary")
return dict_to_dataset(data, library=None... |
Convert prior samples to xarray. | def prior_to_xarray(self):
"""Convert prior samples to xarray."""
data = self.prior
if not isinstance(data, dict):
raise TypeError("DictConverter.prior is not a dictionary")
return dict_to_dataset(data, library=None, coords=self.coords, dims=self.dims) |
Convert sample_stats_prior samples to xarray. | def sample_stats_prior_to_xarray(self):
"""Convert sample_stats_prior samples to xarray."""
data = self.sample_stats_prior
if not isinstance(data, dict):
raise TypeError("DictConverter.sample_stats_prior is not a dictionary")
return dict_to_dataset(data, library=None, coords... |
Convert prior_predictive samples to xarray. | def prior_predictive_to_xarray(self):
"""Convert prior_predictive samples to xarray."""
data = self.prior_predictive
if not isinstance(data, dict):
raise TypeError("DictConverter.prior_predictive is not a dictionary")
return dict_to_dataset(data, library=None, coords=self.co... |
Convert observed_data to xarray. | def observed_data_to_xarray(self):
"""Convert observed_data to xarray."""
data = self.observed_data
if not isinstance(data, dict):
raise TypeError("DictConverter.observed_data is not a dictionary")
if self.dims is None:
dims = {}
else:
dims = s... |
Summary plot for model comparison.
This plot is in the style of the one used in the book Statistical Rethinking (Chapter 6)
by Richard McElreath.
Notes
-----
Defaults to comparing Widely Accepted Information Criterion (WAIC) if present in comp_df column,
otherwise compares Leave-one-ou... | def plot_compare(
comp_df,
insample_dev=True,
plot_standard_error=True,
plot_ic_diff=True,
figsize=None,
textsize=None,
plot_kwargs=None,
ax=None,
):
"""
Summary plot for model comparison.
This plot is in the style of the one used in the book Statistical Rethink... |
Plot parallel coordinates plot showing posterior points with and without divergences.
Described by https://arxiv.org/abs/1709.01449, suggested by Ari Hartikainen
Parameters
----------
data : obj
Any object that can be converted to an az.InferenceData object
Refer to documentation of az... | def plot_parallel(
data,
var_names=None,
coords=None,
figsize=None,
textsize=None,
legend=True,
colornd="k",
colord="C1",
shadend=0.025,
ax=None,
norm_method=None,
):
"""
Plot parallel coordinates plot showing posterior points with and without divergences.
Descri... |
Extract sampling information. | def _process_configuration(comments):
"""Extract sampling information."""
num_samples = None
num_warmup = None
save_warmup = None
for comment in comments:
comment = comment.strip("#").strip()
if comment.startswith("num_samples"):
num_samples = int(comment.strip("num_sampl... |
Read CmdStan output.csv.
Parameters
----------
path : str
Returns
-------
List[DataFrame, DataFrame, List[str], List[str], List[str]]
pandas.DataFrame
Sample data
pandas.DataFrame
Sample stats
List[str]
Configuration information
... | def _read_output(path):
"""Read CmdStan output.csv.
Parameters
----------
path : str
Returns
-------
List[DataFrame, DataFrame, List[str], List[str], List[str]]
pandas.DataFrame
Sample data
pandas.DataFrame
Sample stats
List[str]
... |
Transform datastring to key, values pair.
All values are transformed to floating point values.
Parameters
----------
string : str
Returns
-------
Tuple[Str, Str]
key, values pair | def _process_data_var(string):
"""Transform datastring to key, values pair.
All values are transformed to floating point values.
Parameters
----------
string : str
Returns
-------
Tuple[Str, Str]
key, values pair
"""
key, var = string.split("<-")
if "structure" in ... |
Read Rdump output and transform to Python dictionary.
Parameters
----------
path : str
Returns
-------
Dict
key, values pairs from Rdump formatted data. | def _read_data(path):
"""Read Rdump output and transform to Python dictionary.
Parameters
----------
path : str
Returns
-------
Dict
key, values pairs from Rdump formatted data.
"""
data = {}
with open(path, "r") as f_obj:
var = ""
for line in f_obj:
... |
Transform a list of pandas.DataFrames to dictionary containing ndarrays.
Parameters
----------
dfs : List[pandas.DataFrame]
Returns
-------
Dict
key, values pairs. Values are formatted to shape = (nchain, ndraws, *shape) | def _unpack_dataframes(dfs):
"""Transform a list of pandas.DataFrames to dictionary containing ndarrays.
Parameters
----------
dfs : List[pandas.DataFrame]
Returns
-------
Dict
key, values pairs. Values are formatted to shape = (nchain, ndraws, *shape)
"""
col_groups = defa... |
Convert CmdStan data into an InferenceData object.
Parameters
----------
posterior : List[str]
List of paths to output.csv files.
CSV file can be stacked csv containing all the chains
cat output*.csv > combined_output.csv
posterior_predictive : str, List[Str]
Poste... | def from_cmdstan(
posterior=None,
*,
posterior_predictive=None,
prior=None,
prior_predictive=None,
observed_data=None,
observed_data_var=None,
log_likelihood=None,
coords=None,
dims=None
):
"""Convert CmdStan data into an InferenceData object.
Parameters
----------
... |
Read csv paths to list of dataframes. | def _parse_posterior(self):
"""Read csv paths to list of dataframes."""
paths = self.posterior_
if isinstance(paths, str):
paths = [paths]
chain_data = []
for path in paths:
parsed_output = _read_output(path)
for sample, sample_stats, config, a... |
Read csv paths to list of dataframes. | def _parse_prior(self):
"""Read csv paths to list of dataframes."""
paths = self.prior_
if isinstance(paths, str):
paths = [paths]
chain_data = []
for path in paths:
parsed_output = _read_output(path)
for sample, sample_stats, config, adaptatio... |
Extract posterior samples from output csv. | def posterior_to_xarray(self):
"""Extract posterior samples from output csv."""
columns = self.posterior[0].columns
# filter posterior_predictive and log_likelihood
posterior_predictive = self.posterior_predictive
if posterior_predictive is None or (
isinstance(poste... |
Extract sample_stats from fit. | def sample_stats_to_xarray(self):
"""Extract sample_stats from fit."""
dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}
# copy dims and coords
dims = deepcopy(self.dims) if self.dims is not None else {}
coords = deepcopy(self.coords) if self.coor... |
Convert posterior_predictive samples to xarray. | def posterior_predictive_to_xarray(self):
"""Convert posterior_predictive samples to xarray."""
posterior_predictive = self.posterior_predictive
columns = self.posterior[0].columns
if (
isinstance(posterior_predictive, (tuple, list))
and posterior_predictive[0].en... |
Convert prior samples to xarray. | def prior_to_xarray(self):
"""Convert prior samples to xarray."""
# filter prior_predictive
prior_predictive = self.prior_predictive
columns = self.prior[0].columns
if prior_predictive is None or (
isinstance(prior_predictive, str) and prior_predictive.lower().endswit... |
Extract sample_stats from fit. | def sample_stats_prior_to_xarray(self):
"""Extract sample_stats from fit."""
dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}
# copy dims and coords
dims = deepcopy(self.dims) if self.dims is not None else {}
coords = deepcopy(self.coords) if sel... |
Convert prior_predictive samples to xarray. | def prior_predictive_to_xarray(self):
"""Convert prior_predictive samples to xarray."""
prior_predictive = self.prior_predictive
if (
isinstance(prior_predictive, (tuple, list)) and prior_predictive[0].endswith(".csv")
) or (isinstance(prior_predictive, str) and prior_predic... |
Convert observed data to xarray. | def observed_data_to_xarray(self):
"""Convert observed data to xarray."""
observed_data_raw = _read_data(self.observed_data)
variables = self.observed_data_var
if isinstance(variables, str):
variables = [variables]
observed_data = {}
for key, vals in observed_... |
Extract draws from PyStan fit. | def get_draws(fit, variables=None, ignore=None):
"""Extract draws from PyStan fit."""
if ignore is None:
ignore = []
if fit.mode == 1:
msg = "Model in mode 'test_grad'. Sampling is not conducted."
raise AttributeError(msg)
if fit.mode == 2 or fit.sim.get("samples") is No... |
Extract sample stats from PyStan fit. | def get_sample_stats(fit, log_likelihood=None):
"""Extract sample stats from PyStan fit."""
dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}
ndraws = [s - w for s, w in zip(fit.sim["n_save"], fit.sim["warmup2"])]
extraction = OrderedDict()
for chain, (pyhold... |
Extract draws from PyStan3 fit. | def get_draws_stan3(fit, model=None, variables=None, ignore=None):
"""Extract draws from PyStan3 fit."""
if ignore is None:
ignore = []
dtypes = {}
if model is not None:
dtypes = infer_dtypes(fit, model)
if variables is None:
variables = fit.param_names
elif ... |
Extract sample stats from PyStan3 fit. | def get_sample_stats_stan3(fit, model=None, log_likelihood=None):
"""Extract sample stats from PyStan3 fit."""
dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}
data = OrderedDict()
for key in fit.sample_and_sampler_param_names:
new_shape = -1, fit.num_chai... |
Infer dtypes from Stan model code.
Function strips out generated quantities block and searchs for `int`
dtypes after stripping out comments inside the block. | def infer_dtypes(fit, model=None):
"""Infer dtypes from Stan model code.
Function strips out generated quantities block and searchs for `int`
dtypes after stripping out comments inside the block.
"""
pattern_remove_comments = re.compile(
r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\... |
Convert PyStan data into an InferenceData object.
Parameters
----------
posterior : StanFit4Model or stan.fit.Fit
PyStan fit object for posterior.
posterior_predictive : str, a list of str
Posterior predictive samples for the posterior.
prior : StanFit4Model or stan.fit.Fit
... | def from_pystan(
posterior=None,
*,
posterior_predictive=None,
prior=None,
prior_predictive=None,
observed_data=None,
log_likelihood=None,
coords=None,
dims=None,
posterior_model=None,
prior_model=None
):
"""Convert PyStan data into an InferenceData object.
... |
Extract posterior samples from fit. | def posterior_to_xarray(self):
"""Extract posterior samples from fit."""
posterior = self.posterior
# filter posterior_predictive and log_likelihood
posterior_predictive = self.posterior_predictive
if posterior_predictive is None:
posterior_predictive = []
... |
Extract sample_stats from posterior. | def sample_stats_to_xarray(self):
"""Extract sample_stats from posterior."""
posterior = self.posterior
# copy dims and coords
dims = deepcopy(self.dims) if self.dims is not None else {}
coords = deepcopy(self.coords) if self.coords is not None else {}
# log_lik... |
Convert posterior_predictive samples to xarray. | def posterior_predictive_to_xarray(self):
"""Convert posterior_predictive samples to xarray."""
posterior = self.posterior
posterior_predictive = self.posterior_predictive
data = get_draws(posterior, variables=posterior_predictive)
return dict_to_dataset(data, library=self.p... |
Convert prior samples to xarray. | def prior_to_xarray(self):
"""Convert prior samples to xarray."""
prior = self.prior
# filter posterior_predictive and log_likelihood
prior_predictive = self.prior_predictive
if prior_predictive is None:
prior_predictive = []
elif isinstance(prior_predi... |
Extract sample_stats_prior from prior. | def sample_stats_prior_to_xarray(self):
"""Extract sample_stats_prior from prior."""
prior = self.prior
data = get_sample_stats(prior)
return dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=self.dims) |
Convert prior_predictive samples to xarray. | def prior_predictive_to_xarray(self):
"""Convert prior_predictive samples to xarray."""
prior = self.prior
prior_predictive = self.prior_predictive
data = get_draws(prior, variables=prior_predictive)
return dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=... |
Extract posterior samples from fit. | def posterior_to_xarray(self):
"""Extract posterior samples from fit."""
posterior = self.posterior
posterior_model = self.posterior_model
# filter posterior_predictive and log_likelihood
posterior_predictive = self.posterior_predictive
if posterior_predictive is No... |
Extract sample_stats from posterior. | def sample_stats_to_xarray(self):
"""Extract sample_stats from posterior."""
posterior = self.posterior
posterior_model = self.posterior_model
# copy dims and coords
dims = deepcopy(self.dims) if self.dims is not None else {}
coords = deepcopy(self.coords) if self.c... |
Convert posterior_predictive samples to xarray. | def posterior_predictive_to_xarray(self):
"""Convert posterior_predictive samples to xarray."""
posterior = self.posterior
posterior_model = self.posterior_model
posterior_predictive = self.posterior_predictive
data = get_draws_stan3(posterior, model=posterior_model, variabl... |
Convert prior samples to xarray. | def prior_to_xarray(self):
"""Convert prior samples to xarray."""
prior = self.prior
prior_model = self.prior_model
# filter posterior_predictive and log_likelihood
prior_predictive = self.prior_predictive
if prior_predictive is None:
prior_predictive =... |
Extract sample_stats_prior from prior. | def sample_stats_prior_to_xarray(self):
"""Extract sample_stats_prior from prior."""
prior = self.prior
prior_model = self.prior_model
data = get_sample_stats_stan3(prior, model=prior_model)
return dict_to_dataset(data, library=self.stan, coords=self.coords, dims=self.dims) |
Convert prior_predictive samples to xarray. | def prior_predictive_to_xarray(self):
"""Convert prior_predictive samples to xarray."""
prior = self.prior
prior_model = self.prior_model
prior_predictive = self.prior_predictive
data = get_draws_stan3(prior, model=prior_model, variables=prior_predictive)
return dic... |
Convert observed data to xarray. | def observed_data_to_xarray(self):
"""Convert observed data to xarray."""
posterior_model = self.posterior_model
if self.dims is None:
dims = {}
else:
dims = self.dims
observed_names = self.observed_data
if isinstance(observed_names, str):
... |
Extract latent and observed variable names from pyro.MCMC.
Parameters
----------
posterior : pyro.MCMC
Fitted MCMC object from Pyro
Returns
-------
list[str], list[str]
observed and latent variable names from the MCMC trace. | def _get_var_names(posterior):
"""Extract latent and observed variable names from pyro.MCMC.
Parameters
----------
posterior : pyro.MCMC
Fitted MCMC object from Pyro
Returns
-------
list[str], list[str]
observed and latent variable names from the MCMC trace.
"""
sample_... |
Convert pyro data into an InferenceData object.
Parameters
----------
posterior : pyro.MCMC
Fitted MCMC object from Pyro
coords : dict[str] -> list[str]
Map of dimensions to coordinates
dims : dict[str] -> list[str]
Map variable names to their coordinates | def from_pyro(posterior=None, *, coords=None, dims=None):
"""Convert pyro data into an InferenceData object.
Parameters
----------
posterior : pyro.MCMC
Fitted MCMC object from Pyro
coords : dict[str] -> list[str]
Map of dimensions to coordinates
dims : dict[str] -> list[str]
... |
Convert the posterior to an xarray dataset. | def posterior_to_xarray(self):
"""Convert the posterior to an xarray dataset."""
# Do not make pyro a requirement
from pyro.infer import EmpiricalMarginal
try: # Try pyro>=0.3 release syntax
data = {
name: np.expand_dims(samples.enumerate_support().squeeze()... |
Bar plot of the autocorrelation function for a sequence of data.
Useful in particular for posteriors from MCMC samples which may display correlation.
Parameters
----------
data : obj
Any object that can be converted to an az.InferenceData object
Refer to documentation of az.convert_to_... | def plot_autocorr(data, var_names=None, max_lag=100, combined=False, figsize=None, textsize=None):
"""Bar plot of the autocorrelation function for a sequence of data.
Useful in particular for posteriors from MCMC samples which may display correlation.
Parameters
----------
data : obj
Any o... |
Plot energy transition distribution and marginal energy distribution in HMC algorithms.
This may help to diagnose poor exploration by gradient-based algorithms like HMC or NUTS.
Parameters
----------
data : xarray dataset, or object that can be converted (must represent
`sample_stats` and h... | def plot_energy(
data,
kind="kde",
bfmi=True,
figsize=None,
legend=True,
fill_alpha=(1, 0.75),
fill_color=("C0", "C5"),
bw=4.5,
textsize=None,
fill_kwargs=None,
plot_kwargs=None,
ax=None,
):
"""Plot energy transition distribution and marginal energy distribution in HM... |
From itertools cookbook. [a, b, c, ...] -> (a, b), (b, c), ... | def pairwise(iterable):
"""From itertools cookbook. [a, b, c, ...] -> (a, b), (b, c), ..."""
first, second = tee(iterable)
next(second, None)
return zip(first, second) |
Forest plot to compare credible intervals from a number of distributions.
Generates a forest plot of 100*(credible_interval)% credible intervals from
a trace or list of traces.
Parameters
----------
data : obj or list[obj]
Any object that can be converted to an az.InferenceData object
... | def plot_forest(
data,
kind="forestplot",
model_names=None,
var_names=None,
combined=False,
credible_interval=0.94,
rope=None,
quartiles=True,
ess=False,
r_hat=False,
colors="cycle",
textsize=None,
linewidth=None,
markersize=None,
ridgeplot_alpha=None,
rid... |
Initialize an object for each variable to be plotted. | def make_plotters(self):
"""Initialize an object for each variable to be plotted."""
plotters, y = {}, 0
for var_name in self.var_names:
plotters[var_name] = VarHandler(
var_name,
self.data,
y,
model_names=self.model_nam... |
Collect labels and ticks from plotters. | def labels_and_ticks(self):
"""Collect labels and ticks from plotters."""
labels, idxs = [], []
for plotter in self.plotters.values():
sub_labels, sub_idxs, _, _ = plotter.labels_ticks_and_vals()
labels.append(sub_labels)
idxs.append(sub_idxs)
return n... |
Display ROPE when more than one interval is provided. | def display_multiple_ropes(self, rope, ax, y, linewidth, rope_var):
"""Display ROPE when more than one interval is provided."""
vals = dict(rope[rope_var][0])["rope"]
ax.plot(
vals,
(y + 0.05, y + 0.05),
lw=linewidth * 2,
color="C2",
so... |
Draw ridgeplot for each plotter.
Parameters
----------
mult : float
How much to multiply height by. Set this to greater than 1 to have some overlap.
linewidth : float
Width of line on border of ridges
alpha : float
Transparency of ridges
... | def ridgeplot(self, mult, linewidth, alpha, ax):
"""Draw ridgeplot for each plotter.
Parameters
----------
mult : float
How much to multiply height by. Set this to greater than 1 to have some overlap.
linewidth : float
Width of line on border of ridges
... |
Draw forestplot for each plotter.
Parameters
----------
credible_interval : float
How wide each line should be
quartiles : bool
Whether to mark quartiles
xt_textsize : float
Size of tick text
titlesize : float
Size of title... | def forestplot(
self, credible_interval, quartiles, xt_labelsize, titlesize, linewidth, markersize, ax, rope
):
"""Draw forestplot for each plotter.
Parameters
----------
credible_interval : float
How wide each line should be
quartiles : bool
... |
Draw effective n for each plotter. | def plot_neff(self, ax, xt_labelsize, titlesize, markersize):
"""Draw effective n for each plotter."""
for plotter in self.plotters.values():
for y, ess, color in plotter.ess():
if ess is not None:
ax.plot(
ess,
... |
Draw r-hat for each plotter. | def plot_rhat(self, ax, xt_labelsize, titlesize, markersize):
"""Draw r-hat for each plotter."""
for plotter in self.plotters.values():
for y, r_hat, color in plotter.r_hat():
if r_hat is not None:
ax.plot(r_hat, y, "o", color=color, markersize=markersize,... |
Draw shaded horizontal bands for each plotter. | def make_bands(self, ax):
"""Draw shaded horizontal bands for each plotter."""
y_vals, y_prev, is_zero = [0], None, False
prev_color_index = 0
for plotter in self.plotters.values():
for y, *_, color in plotter.iterator():
if self.colors.index(color) < prev_col... |
Figure out the height of this plot. | def fig_height(self):
"""Figure out the height of this plot."""
# hand-tuned
return (
4
+ len(self.data) * len(self.var_names)
- 1
+ 0.1 * sum(1 for j in self.plotters.values() for _ in j.iterator())
) |
Iterate over models and chains for each variable. | def iterator(self):
"""Iterate over models and chains for each variable."""
if self.combined:
grouped_data = [[(0, datum)] for datum in self.data]
skip_dims = {"chain"}
else:
grouped_data = [datum.groupby("chain") for datum in self.data]
skip_dims ... |
Get data for each treeplot for the variable. | def treeplot(self, qlist, credible_interval):
"""Get data for each treeplot for the variable."""
for y, _, label, values, color in self.iterator():
ntiles = np.percentile(values.flatten(), qlist)
ntiles[0], ntiles[-1] = hpd(values.flatten(), credible_interval)
yield y... |
Get labels, ticks, values, and colors for the variable. | def labels_ticks_and_vals(self):
"""Get labels, ticks, values, and colors for the variable."""
y_ticks = defaultdict(list)
for y, label, _, vals, color in self.iterator():
y_ticks[label].append((y, vals, color))
labels, ticks, vals, colors = [], [], [], []
for label, ... |
Get data for each ridgeplot for the variable. | def ridgeplot(self, mult):
"""Get data for each ridgeplot for the variable."""
xvals, yvals, pdfs, colors = [], [], [], []
for y, *_, values, color in self.iterator():
yvals.append(y)
colors.append(color)
values = values.flatten()
density, lower, u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.