Skip to content

ENH: traceplot for author model #57

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions bayesalpha/author_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,8 @@ def fit_authors(data,
sampler_type : str
Whether to use Markov chain Monte Carlo or variational inference.
Either 'mcmc' or 'vi'. Defaults to 'mcmc'.
sampler_args : dict
Additional parameters for `pm.sample`.
save_data : bool
Whether to store the dataset in the result object.
seed : int
Expand Down
70 changes: 70 additions & 0 deletions bayesalpha/author_plotting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import numpy as np
import warnings
import functools
try:
import matplotlib.pyplot as plt
import seaborn as sns
_has_mpl = True
except ImportError:
warnings.warn('Could not import matplotlib: Plotting unavailable.')
_has_mpl = False
plt = None
sns = None


def _require_mpl(func):
@functools.wraps(func)
def inner(*args, **kwargs):
if not _has_mpl:
raise RuntimeError('Matplotlib is unavailable.')
return func(*args, **kwargs)

return inner


@_require_mpl
def plot_trace(trace, varname, title=None, ax=None, **kwargs):
"""
Plot samples from trace for a specific variable.

Parameters
----------
trace : AuthorModelResult object
Result from ba.fit_authors
varname : str
Name of variable to plot. Must be one of ['mu_global', 'mu_author',
'mu_algo', 'alpha_author', 'alpha_algo']
title : str (optional)
Title of plot
ax : plt.axis object (optional)
Axis on which to plot
kwargs : dict (optional)
Additional keyword args to pass to sns.distplot
"""

if varname not in ['mu_global', 'mu_author', 'mu_algo',
'alpha_author', 'alpha_algo']:
raise ValueError("`varname` must be one of ['mu_global', 'mu_author', "
"'mu_algo', 'alpha_author', 'alpha_algo']")

if ax is None:
_, ax = plt.subplots(figsize=[12, 4])

for i in trace.trace[varname]['chain']:
if varname == 'mu_global':
sns.distplot(trace.trace['mu_global'].sel({'chain': i}).values,
**kwargs)
else:
suffix = varname.split('_')[-1] # Either 'author' or 'algo'
for j in trace.trace[varname][suffix]:
sns.distplot(trace.trace[varname].sel({'chain': i,
suffix: j}).values,
**kwargs)

if title:
ax.set_title(title)

plt.xlabel(varname)
plt.ylabel('Probability')

return ax
File renamed without changes.