pymc-devs / pymc-devs/pymc-examples

PyMC3 Examples Known Errors & Notes (March 2021)

Open
#43 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

good first issue
Dominant language
Python
Stars
398
Forks
325
Avg merge
9d 15m
Merged PRs (30d)
1

Description

Summary

The following are existing issues & suggestions in the pymc3-examples repo after going through an iteration of renaming plot dependencies from pm. to arviz.

Note: This is similar to the pre-existing #34 issue.

Installs

  • Pymc3: v3.11
  • theano-pymc (aesara): v 1.1.2

Issues

General Issues

  • Have param returninference =True

File-specific Issues

  • examples/pymc3_howto/lasso_block_update.ipynb
Issue

"return_inferencedata should be manually set, either to True or to False, but one of the two to avoid the warning.

If False, an inferencedata should be created within the model context, and passed to arviz. This will

  1. avoid the warning of conversion without the model context and
  2. push forward arviz best practices, it is probably not too relevant here but conversion may not be cheap for some models because it requires computing all the pointwise log likelihood values. az.plot_xyz(trace) works because ArviZ internally converts the data to inferencedata, then plots."
  • examples/pymc3_howto/data_container.ipynb
Issue We should have "keep_size=True to avoid the warning in the cell below, also because in a future ArviZ release the behaviour of hdi will change for 2d arrays (not for 1d or 3d+ arrays), so using 3d arrays with chain, draw, *shape should be used."
  • examples/pymc3_howto/sampling_conjugate_step.ipynb
Code
traces = []
models = []
names = ["Partial conjugate sampling", "Full NUTS"]

for use_conjugate in [True, False]:
    with pm.Model() as model:
        tau = pm.Exponential("tau", lam=1, testval=1.0)
        alpha = pm.Deterministic("alpha", tau * np.ones([N, J]))
        p = pm.Dirichlet("p", a=alpha)

        if use_conjugate:
            # If we use the conjugate sampling, we don't need to define the likelihood
            # as it's already taken into account in our custom step method
            step = [ConjugateStep(p.transformed, counts, tau)]

        else:
            x = pm.Multinomial("x", n=ncounts, p=p, observed=counts)
            step = []

        trace = pm.sample(step=step, chains=2, cores=1, return_inferencedata=True)
        traces.append(trace)

    assert all(az.summary(trace)["r_hat"] < 1.1)
    models.append(model)
Issue

"Since we are not storing the summary dataframe anywhere and we only want the rhat, we should use rhat instead. The assertion can be done with:

assert (az.rhat(trace).to_array() < 1.1).all()"

  • examples/ode_models/ODE_with_manual_gradients.ipynb
Code

Similar to PR 43, for line 33 at variable trace =

    Y_obs = pm.Lognormal("Y_obs", mu=pm.math.log(forward), sigma=sigma, observed=Y)

    trace = pm.sample(1500, init="jitter+adapt_diag", cores=1)
trace["diverging"].sum()

I changed init from adapt_diag to jitter+adapt_diag & added param cores=1.

Issue I get a sampling error when using adapt_diagor other adapter types....unsure why.

The error:

SamplingError: Bad initial energy

Seen here
Screen Shot 2021-03-14 at 6 56 40 PM

  • examples/generalized_linear_models/GLM-model-selection.ipynb
Issue 1
Code

ax = (
    dfll["log_likelihood"]
    .unstack()
    .plot.bar(subplots=True, layout=(1, 2), figsize=(12, 6), sharex=True)
)

ax[0, 0].set_xticks(range(5))
ax[0, 0].set_xticklabels(["k1", "k2", "k3", "k4", "k5"])
ax[0, 0].set_xlim(-0.25, 4.25);

Issue

One dependency errors out, this making remainder of notebook not run.
Errors on missing sd_log__, and therefore cannot run entire notebook due to dependency.

Particularly

GLM-model-selection KeyError: 'var names: "['sd_log__'] are not present" in dataset'

More details here

Issue 2
Code
dfll = pd.DataFrame(index=["k1", "k2", "k3", "k4", "k5"], columns=["lin", "quad"])
dfll.index.name = "model"

for nm in dfll.index:
    dfll.loc[nm, "lin"] = -models_lin[nm].logp(
        az.summary(traces_lin[nm], traces_lin[nm].varnames)["mean"].to_dict()
    )

    dfll.loc[nm, "quad"] = -models_quad[nm].logp(
        az.summary(traces_quad[nm], traces_quad[nm].varnames)["mean"].to_dict()
    )

dfll = pd.melt(dfll.reset_index(), id_vars=["model"], var_name="poly", value_name="log_likelihood")
dfll.index = pd.MultiIndex.from_frame(dfll[["model", "poly"]])
Issue I'm not familiar with this notebook and find the pandas stuff happening above quite confusing. The model selection should be simplified with newer ArviZ features. Having to work with straces directly is not something we should need to teach 😬

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the listed notebook files and the stated PyMC3 3.11/theano-pymc 1.1.2 environment; inspect each marked cell and the linked PR #24 discussion for context. Update the notebooks so the listed warnings, sampling failure, and missing sd_log__ dependency no longer block execution, and verify the model-selection example runs through its final plot.

Written by the indexing model from the issue text.

Assessment

Tech stack
jupyter-notebook, python
Domain
documentation, machine-learning
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.