text stringlengths 81 112k |
|---|
Compute the derivatives of the predicted latent function with respect
to X*
Given a set of points at which to predict X* (size [N*,Q]), compute the
derivatives of the mean and variance. Resulting arrays are sized:
dmu_dX* -- [N*, Q ,D], where D is the number of output in this GP
... |
Compute the derivatives of the posterior of the GP.
Given a set of points at which to predict X* (size [N*,Q]), compute the
mean and variance of the derivative. Resulting arrays are sized:
dL_dX* -- [N*, Q ,D], where D is the number of output in this GP (usually one).
Note that this... |
Predict the wishart embedding G of the GP. This is the density of the
input of the GP defined by the probabilistic function mapping f.
G = J_mean.T*J_mean + output_dim*J_cov.
:param array-like Xnew: The points at which to evaluate the magnification.
:param :py:class:`~GPy.kern.Kern` ker... |
Predict the magnification factor as
sqrt(det(G))
for each point N in Xnew.
:param bool mean: whether to include the mean of the wishart embedding.
:param bool covariance: whether to include the covariance of the wishart embedding.
:param array-like dimensions: which dimensions... |
Samples the posterior GP at the points X.
:param X: The points at which to take the samples.
:type X: np.ndarray (Nnew x self.input_dim)
:param size: the number of a posteriori samples.
:type size: int.
:returns: set of simulations
:rtype: np.ndarray (Nnew x D x samples)... |
Samples the posterior GP at the points X.
:param X: the points at which to take the samples.
:type X: np.ndarray (Nnew x self.input_dim.)
:param size: the number of a posteriori samples.
:type size: int.
:param noise_model: for mixed noise likelihood, the noise model to use in t... |
Optimize the model using self.log_likelihood and self.log_likelihood_gradient, as well as self.priors.
kwargs are passed to the optimizer. They can be:
:param max_iters: maximum number of function evaluations
:type max_iters: int
:param messages: whether to display during optimisation
... |
Infer X for the new observed data *Y_new*.
:param Y_new: the new observed data for inference
:type Y_new: numpy.ndarray
:param optimize: whether to optimize the location of new X (True by default)
:type optimize: boolean
:return: a tuple containing the posterior estimation of X ... |
Calculation of the log predictive density
.. math:
p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*})
:param x_test: test locations (x_{*})
:type x_test: (Nx1) array
:param y_test: test observations (y_{*})
:type y_test: (Nx1) array
:param Y_metadata... |
Calculation of the log predictive density by sampling
.. math:
p(y_{*}|D) = p(y_{*}|f_{*})p(f_{*}|\mu_{*}\\sigma^{2}_{*})
:param x_test: test locations (x_{*})
:type x_test: (Nx1) array
:param y_test: test observations (y_{*})
:type y_test: (Nx1) array
:para... |
Computes the posterior covariance between points.
:param X1: some input observations
:param X2: other input observations
def posterior_covariance_between_points(self, X1, X2):
"""
Computes the posterior covariance between points.
:param X1: some input observations
:par... |
Generate default dimensions and coordinates for a variable.
Parameters
----------
shape : tuple[int]
Shape of the variable
var_name : str
Name of the variable. Used in the default name, if necessary
dims : list
List of dimensions for the variable
coords : dict[str] -> li... |
Convert a numpy array to an xarray.DataArray.
The first two dimensions will be (chain, draw), and any remaining
dimensions will be "shape".
If the numpy array is 1d, this dimension is interpreted as draw
If the numpy array is 2d, it is interpreted as (chain, draw)
If the numpy array is 3 or more di... |
Convert a dictionary of numpy arrays to an xarray.Dataset.
Parameters
----------
data : dict[str] -> ndarray
Data to convert. Keys are variable names.
attrs : dict
Json serializable metadata to attach to the dataset, in addition to defaults.
library : module
Library used for... |
Make standard attributes to attach to xarray datasets.
Parameters
----------
attrs : dict (optional)
Additional attributes to add or overwrite
Returns
-------
dict
attrs
def make_attrs(attrs=None, library=None):
"""Make standard attributes to attach to xarray datasets.
... |
Return the path of the arviz data dir.
This folder is used by some dataset loaders to avoid downloading the
data several times.
By default the data dir is set to a folder named 'arviz_data' in the
user home folder.
Alternatively, it can be set by the 'ARVIZ_DATA' environment
variable or progr... |
Calculate the sha256 hash of the file at path.
def _sha256(path):
"""Calculate the sha256 hash of the file at path."""
sha256hash = hashlib.sha256()
chunk_size = 8192
with open(path, "rb") as buff:
while True:
buffer = buff.read(chunk_size)
if not buffer:
... |
Load a local or remote pre-made dataset.
Run with no parameters to get a list of all available models.
The directory to save to can also be set with the environement
variable `ARVIZ_HOME`. The checksum of the dataset is checked against a
hardcoded value to watch for data corruption.
Run `az.clear... |
Get a string representation of all available datasets with descriptions.
def list_datasets():
"""Get a string representation of all available datasets with descriptions."""
lines = []
for name, resource in itertools.chain(LOCAL_DATASETS.items(), REMOTE_DATASETS.items()):
if isinstance(resource, Lo... |
Make sure var_names and arg_names are assigned reasonably.
This is meant to run before loading emcee objects into InferenceData.
In case var_names or arg_names is None, will provide defaults. If they are
not None, it verifies there are the right number of them.
Throws a ValueError in case validation f... |
Convert emcee data into an InferenceData object.
Parameters
----------
sampler : emcee.EnsembleSampler
Fitted sampler from emcee.
var_names : list[str] (Optional)
A list of names for variables in the sampler
arg_names : list[str] (Optional)
A list of names for args in the sa... |
Convert the posterior to an xarray dataset.
def posterior_to_xarray(self):
"""Convert the posterior to an xarray dataset."""
data = {}
for idx, var_name in enumerate(self.var_names):
# Use emcee3 syntax, else use emcee2
data[var_name] = (
self.sampler.get... |
Convert observed data to xarray.
def observed_data_to_xarray(self):
"""Convert observed data to xarray."""
data = {}
for idx, var_name in enumerate(self.arg_names):
# Use emcee3 syntax, else use emcee2
data[var_name] = (
self.sampler.log_prob_fn.args[idx]... |
Convert tfp data into an InferenceData object.
def from_tfp(
posterior=None,
*,
var_names=None,
model_fn=None,
feed_dict=None,
posterior_predictive_samples=100,
posterior_predictive_size=1,
observed=None,
coords=None,
dims=None
):
"""Convert tfp data into an Infe... |
Convert the posterior to an xarray dataset.
def posterior_to_xarray(self):
"""Convert the posterior to an xarray dataset."""
data = {}
for i, var_name in enumerate(self.var_names):
data[var_name] = np.expand_dims(self.posterior[i], axis=0)
return dict_to_dataset(data, l... |
Convert observed data to xarray.
def observed_data_to_xarray(self):
"""Convert observed data to xarray."""
if self.observed is None:
return None
observed_data = {}
if isinstance(self.observed, self.tf.Tensor):
with self.tf.Session() as sess:
... |
Convert posterior_predictive samples to xarray.
def posterior_predictive_to_xarray(self):
"""Convert posterior_predictive samples to xarray."""
if self.model_fn is None:
return None
posterior_preds = []
sample_size = self.posterior[0].shape[0]
for i in np.a... |
Extract sample_stats from tfp trace.
def sample_stats_to_xarray(self):
"""Extract sample_stats from tfp trace."""
if self.model_fn is None or self.observed is None:
return None
log_likelihood = []
sample_size = self.posterior[0].shape[0]
for i in range(samp... |
Convert all available data to an InferenceData object.
Note that if groups can not be created (i.e., there is no `trace`, so
the `posterior` and `sample_stats` can not be extracted), then the InferenceData
will not have those groups.
def to_inference_data(self):
"""Convert all ava... |
Convert pymc3 data into an InferenceData object.
def from_pymc3(trace=None, *, prior=None, posterior_predictive=None, coords=None, dims=None):
"""Convert pymc3 data into an InferenceData object."""
return PyMC3Converter(
trace=trace,
prior=prior,
posterior_predictive=posterior_predictiv... |
Compute log likelihood of each observation.
Return None if there is not exactly 1 observed random variable.
def _extract_log_likelihood(self):
"""Compute log likelihood of each observation.
Return None if there is not exactly 1 observed random variable.
"""
# This next line is... |
Convert the posterior to an xarray dataset.
def posterior_to_xarray(self):
"""Convert the posterior to an xarray dataset."""
var_names = self.pymc3.util.get_default_varnames( # pylint: disable=no-member
self.trace.varnames, include_transformed=False
)
data = {}
for ... |
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... |
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, dim... |
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-ac... |
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... |
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... |
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... |
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
-----... |
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... |
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... |
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 r... |
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... |
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... |
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... |
Inverse Generalized Pareto distribution function.
def _gpinv(probs, kappa, sigma):
"""Inverse Generalized Pareto distribution function."""
x = np.full_like(probs, np.nan)
if sigma <= 0:
return x
ok = (probs > 0) & (probs < 1)
if np.all(ok):
if np.abs(kappa) < np.finfo(float).eps:
... |
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... |
Create a data frame with summary statistics.
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
Names of variables to include in summary
include_circ : b... |
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]
... |
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... |
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... |
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
... |
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, 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 = ... |
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)
... |
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... |
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... |
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... |
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
i... |
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... |
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_uf... |
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_sa... |
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
----... |
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.
Pa... |
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... |
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... |
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):
... |
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... |
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... |
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:
warnin... |
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, lib... |
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")
... |
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... |
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")
re... |
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_... |
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 = {}
... |
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... |
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... |
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... |
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
... |
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 t... |
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
... |
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.D... |
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... |
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)
... |
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 ... |
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_predicti... |
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 = de... |
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, ... |
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) an... |
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 {}
coord... |
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 (isins... |
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 = {}
... |
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... |
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 ... |
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:
varia... |
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_name... |
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 `... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.