-
Notifications
You must be signed in to change notification settings - Fork 88
Add variable selection priors #568
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
NathanielF
wants to merge
27
commits into
pymc-labs:main
Choose a base branch
from
NathanielF:vs_module
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
1f4f695
adding vs module
NathanielF 2a01933
Merge branch 'main' into vs_module
NathanielF db1e81d
adding demo notebook
NathanielF db0522e
trying to fix doctests
NathanielF 1670af4
adding fix
NathanielF 83061e4
another fix
NathanielF 05dc20d
update fix
NathanielF 73e6a8d
adding tests
NathanielF 8d6251f
update adding more tests
NathanielF 4577106
add normal test vs_prior
NathanielF fd1bfb7
improving test coverage
NathanielF 7375aa5
updating notebook
NathanielF 896ee57
update index
NathanielF 1bb79d3
Merge branch 'main' into vs_module
NathanielF 068c922
update spelling
NathanielF 13b320e
add binary treatment case to IV model
NathanielF 6210116
adding more write up
NathanielF bf5b404
update heading
NathanielF b16ef30
hide cells
NathanielF b88271e
better story telling
NathanielF c452650
tidying
NathanielF a5dd60f
hide cell inputs
NathanielF 2578cce
Merge branch 'main' into vs_module
NathanielF a7c1090
fixing linting
NathanielF 78ed0ce
fix linting error
NathanielF 9e6ede0
update typing
NathanielF dbc8614
spell check
NathanielF File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -41,4 +41,5 @@ | |
| "RegressionKink", | ||
| "skl_models", | ||
| "SyntheticControl", | ||
| "variable_selection_priors", | ||
| ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,6 +26,7 @@ | |
| from pymc_extras.prior import Prior | ||
|
|
||
| from causalpy.utils import round_num | ||
| from causalpy.variable_selection_priors import VariableSelectionPrior | ||
|
|
||
|
|
||
| class PyMCModel(pm.Model): | ||
|
|
@@ -657,7 +658,9 @@ def build_model( # type: ignore | |
| y: np.ndarray, | ||
| t: np.ndarray, | ||
| coords: Dict[str, Any], | ||
| priors: Dict[str, Any], | ||
| priors, | ||
| vs_prior_type=None, | ||
| vs_hyperparams=None, | ||
| ) -> None: | ||
| """Specify model with treatment regression and focal regression | ||
| data and priors. | ||
|
|
@@ -680,23 +683,47 @@ def build_model( # type: ignore | |
| Dictionary of priors for the mus and sigmas of both | ||
| regressions. Example: ``priors = {"mus": [0, 0], | ||
| "sigmas": [1, 1], "eta": 2, "lkj_sd": 2}``. | ||
| :param vs_prior_type: An optional string. Can be "spike_and_slab" | ||
| or "horseshoe" or "normal | ||
| :param vs_hyperparams: An optional dictionary of priors for the | ||
| variable selection hyperparameters | ||
|
|
||
| """ | ||
|
|
||
| # --- Priors --- | ||
| with self: | ||
| self.add_coords(coords) | ||
| beta_t = pm.Normal( | ||
| name="beta_t", | ||
| mu=priors["mus"][0], | ||
| sigma=priors["sigmas"][0], | ||
| dims="instruments", | ||
| ) | ||
| beta_z = pm.Normal( | ||
| name="beta_z", | ||
| mu=priors["mus"][1], | ||
| sigma=priors["sigmas"][1], | ||
| dims="covariates", | ||
| ) | ||
|
|
||
| # Create coefficient priors | ||
| if vs_prior_type: | ||
| # Use variable selection priors | ||
| vs_prior_treatment = VariableSelectionPrior( | ||
| vs_prior_type, vs_hyperparams | ||
| ) | ||
| vs_prior_outcome = VariableSelectionPrior(vs_prior_type, vs_hyperparams) | ||
|
|
||
| beta_t = vs_prior_treatment.create_prior( | ||
| name="beta_t", n_params=Z.shape[1], dims="instruments", X=Z | ||
| ) | ||
|
|
||
| beta_z = vs_prior_outcome.create_prior( | ||
| name="beta_z", n_params=X.shape[1], dims="covariates", X=X | ||
| ) | ||
| else: | ||
| # Use standard normal priors | ||
| beta_t = pm.Normal( | ||
| name="beta_t", | ||
| mu=priors["mus"][0], | ||
| sigma=priors["sigmas"][0], | ||
| dims="instruments", | ||
| ) | ||
| beta_z = pm.Normal( | ||
| name="beta_z", | ||
| mu=priors["mus"][1], | ||
| sigma=priors["sigmas"][1], | ||
| dims="covariates", | ||
| ) | ||
|
|
||
| sd_dist = pm.Exponential.dist(priors["lkj_sd"], shape=2) | ||
| chol, corr, sigmas = pm.LKJCholeskyCov( | ||
| name="chol_cov", | ||
|
|
@@ -755,50 +782,32 @@ def sample_predictive_distribution(self, ppc_sampler: str | None = "jax") -> Non | |
| ) | ||
| ) | ||
|
|
||
| def fit( # type: ignore | ||
| def fit( | ||
| self, | ||
| X: np.ndarray, | ||
| Z: np.ndarray, | ||
| y: np.ndarray, | ||
| t: np.ndarray, | ||
| coords: Dict[str, Any], | ||
| priors: Dict[str, Any], | ||
| ppc_sampler: str | None = None, | ||
| ) -> az.InferenceData: | ||
| """Draw samples from posterior distribution and potentially from | ||
| the prior and posterior predictive distributions. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| X : np.ndarray | ||
| Array used to predict our outcome y. | ||
| Z : np.ndarray | ||
| Array used to predict our treatment variable t. | ||
| y : np.ndarray | ||
| Array of values representing our focal outcome y. | ||
| t : np.ndarray | ||
| Array representing the treatment variable. | ||
| coords : dict | ||
| Dictionary with coordinate names for named dimensions. | ||
| priors : dict | ||
| Dictionary of priors for the model. | ||
| ppc_sampler : str, optional | ||
| Sampler for posterior predictive distribution. Can be 'jax', | ||
| 'pymc', or None. Defaults to None, so the user can determine | ||
| if they wish to spend time sampling the posterior predictive | ||
| distribution independently. | ||
|
|
||
| Returns | ||
| ------- | ||
| az.InferenceData | ||
| InferenceData object containing the samples. | ||
| X, | ||
| Z, | ||
| y, | ||
| t, | ||
| coords, | ||
| priors, | ||
|
Comment on lines
+860
to
+865
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. type hints missing
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. also for return type hint |
||
| ppc_sampler=None, | ||
| vs_prior_type=None, | ||
| vs_hyperparams=None, | ||
| ): | ||
| """Draw samples from posterior distribution and potentially | ||
| from the prior and posterior predictive distributions. The | ||
| fit call can take values for the | ||
| ppc_sampler = ['jax', 'pymc', None] | ||
| We default to None, so the user can determine if they wish | ||
| to spend time sampling the posterior predictive distribution | ||
| independently. | ||
| """ | ||
|
|
||
| # Ensure random_seed is used in sample_prior_predictive() and | ||
| # sample_posterior_predictive() if provided in sample_kwargs. | ||
| # Use JAX for ppc sampling of multivariate likelihood | ||
|
|
||
| self.build_model(X, Z, y, t, coords, priors) | ||
| self.build_model(X, Z, y, t, coords, priors, vs_prior_type, vs_hyperparams) | ||
| with self: | ||
| self.idata = pm.sample(**self.sample_kwargs) | ||
| self.sample_predictive_distribution(ppc_sampler=ppc_sampler) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is sphinx format and not numpy
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should add that into
AGENTS.mdif it's not already there.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You got me. The doc strings were AI generated. Will fix.