Skip to content

Support for custom priors via Prior class #488

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 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
15 changes: 13 additions & 2 deletions causalpy/pymc_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ class PyMCModel(pm.Model):
def default_priors(self):
return {}

def priors_from_data(self, X, y) -> Dict[str, Any]:
return {}

def __init__(
self,
sample_kwargs: Optional[Dict[str, Any]] = None,
Expand Down Expand Up @@ -122,6 +125,8 @@ def fit(self, X, y, coords: Optional[Dict[str, Any]] = None) -> None:
# sample_posterior_predictive() if provided in sample_kwargs.
random_seed = self.sample_kwargs.get("random_seed", None)

self.priors = {**self.priors_from_data(X, y), **self.priors}

self.build_model(X, y, coords)
with self:
self.idata = pm.sample(**self.sample_kwargs)
Expand Down Expand Up @@ -295,16 +300,22 @@ class WeightedSumFitter(PyMCModel):
"y_hat": Prior("Normal", sigma=Prior("HalfNormal", sigma=1), dims="obs_ind"),
}

def priors_from_data(self, X, y) -> Dict[str, Any]:
n_predictors = X.shape[1]

return {
"beta": Prior("Dirichlet", a=np.ones(n_predictors), dims="coeffs"),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just realised that n_predictors will equal length of the "coeffs" dim. Does that have to be the case in fact? If so, do we need priors_from_data?

Not saying I don't want it, it could be really cool. But just wondering more generally if it's needed or not. Will try to think more with a fresh head in the morning, but does this spark off any thoughts?

}

def build_model(self, X, y, coords):
"""
Defines the PyMC model
"""
with self:
self.add_coords(coords)
n_predictors = X.shape[1]
X = pm.Data("X", X, dims=["obs_ind", "coeffs"])
y = pm.Data("y", y[:, 0], dims="obs_ind")
beta = pm.Dirichlet("beta", a=np.ones(n_predictors), dims="coeffs")
beta = self.priors["beta"].create_variable("beta")
mu = pm.Deterministic("mu", pm.math.dot(X, beta), dims="obs_ind")
self.priors["y_hat"].create_likelihood_variable("y_hat", mu=mu, observed=y)

Expand Down
6 changes: 3 additions & 3 deletions docs/source/_static/interrogate_badge.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.