INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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, library=self.tfp, coords=self.coords, dims=sel...
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: vals = sess.run(self.observed,...
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.arange(0, sample_size, int(sample_size / self.post...
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(sample_size): variables = {} ...
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 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. """ ...
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_predictive, coords=coords, dims=dims, )...
Compute log likelihood of each observation.
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 brittle and may not work forever, but is a secret # way to access the model from the trace. model = s...
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 var_name in var_names: data[var_n...
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.
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 ).
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.
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.
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.
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.
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 ).
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 ).
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 ...
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: x = -np.log1p(-probs) # pylint: disable=...
R² for Bayesian regression models. Only valid for linear models.
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...
Create a data frame with summary statistics.
def summary( data, var_names=None, fmt="wide", round_to=2, include_circ=None, stat_funcs=None, extend=True, credible_interval=0.94, order="C", ): """Create a data frame with summary statistics. Parameters ---------- data : obj Any object that can be converted...
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 - out ( loo ) Parameters ------...
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.
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.
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.
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.
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.
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.
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 PyStan fit object for prior. prior_predictive...
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.
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.
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.
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.
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.
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...