Skip to content

fix bug: obs_indx -> obs_ind and improve PyMCModel._data_setter #462

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

Merged
merged 2 commits into from
Apr 21, 2025
Merged
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
2 changes: 1 addition & 1 deletion causalpy/experiments/diff_in_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def __init__(

# fit model
if isinstance(self.model, PyMCModel):
COORDS = {"coeffs": self.labels, "obs_indx": np.arange(self.X.shape[0])}
COORDS = {"coeffs": self.labels, "obs_ind": np.arange(self.X.shape[0])}
self.model.fit(X=self.X, y=self.y, coords=COORDS)
elif isinstance(self.model, RegressorMixin):
self.model.fit(X=self.X, y=self.y)
Expand Down
2 changes: 1 addition & 1 deletion causalpy/experiments/interrupted_time_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def __init__(

# fit the model to the observed (pre-intervention) data
if isinstance(self.model, PyMCModel):
COORDS = {"coeffs": self.labels, "obs_indx": np.arange(self.pre_X.shape[0])}
COORDS = {"coeffs": self.labels, "obs_ind": np.arange(self.pre_X.shape[0])}
self.model.fit(X=self.pre_X, y=self.pre_y, coords=COORDS)
elif isinstance(self.model, RegressorMixin):
self.model.fit(X=self.pre_X, y=self.pre_y)
Expand Down
2 changes: 1 addition & 1 deletion causalpy/experiments/prepostnegd.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def __init__(

# fit the model to the observed (pre-intervention) data
if isinstance(self.model, PyMCModel):
COORDS = {"coeffs": self.labels, "obs_indx": np.arange(self.X.shape[0])}
COORDS = {"coeffs": self.labels, "obs_ind": np.arange(self.X.shape[0])}
self.model.fit(X=self.X, y=self.y, coords=COORDS)
elif isinstance(self.model, RegressorMixin):
raise NotImplementedError("Not implemented for OLS model")
Expand Down
2 changes: 1 addition & 1 deletion causalpy/experiments/regression_discontinuity.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def __init__(
# fit model
if isinstance(self.model, PyMCModel):
# fit the model to the observed (pre-intervention) data
COORDS = {"coeffs": self.labels, "obs_indx": np.arange(self.X.shape[0])}
COORDS = {"coeffs": self.labels, "obs_ind": np.arange(self.X.shape[0])}
self.model.fit(X=self.X, y=self.y, coords=COORDS)
elif isinstance(self.model, RegressorMixin):
self.model.fit(X=self.X, y=self.y)
Expand Down
2 changes: 1 addition & 1 deletion causalpy/experiments/regression_kink.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def __init__(
self.y, self.X = np.asarray(y), np.asarray(X)
self.outcome_variable_name = y.design_info.column_names[0]

COORDS = {"coeffs": self.labels, "obs_indx": np.arange(self.X.shape[0])}
COORDS = {"coeffs": self.labels, "obs_ind": np.arange(self.X.shape[0])}
self.model.fit(X=self.X, y=self.y, coords=COORDS)

# score the goodness of fit to all data
Expand Down
2 changes: 1 addition & 1 deletion causalpy/experiments/synthetic_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def __init__(

# fit the model to the observed (pre-intervention) data
if isinstance(self.model, PyMCModel):
COORDS = {"coeffs": self.labels, "obs_indx": np.arange(self.pre_X.shape[0])}
COORDS = {"coeffs": self.labels, "obs_ind": np.arange(self.pre_X.shape[0])}
self.model.fit(X=self.pre_X, y=self.pre_y, coords=COORDS)
elif isinstance(self.model, RegressorMixin):
self.model.fit(X=self.pre_X, y=self.pre_y)
Expand Down
19 changes: 15 additions & 4 deletions causalpy/pymc_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,20 @@ def _data_setter(self, X) -> None:

This method is used internally to register new data for the model for
prediction.

NOTE: We are actively changing the `X`. Often, this matrix will have a different
number of rows than the original data. So to make the shapes work, we need to
update all data nodes in the model to have the correct shape. The values are not
used, so we set them to 0. In our case, we just have data nodes X and y, but if
in the future we get more complex models with more data nodes, then we'll need
to update all of them - ideally programmatically.
"""
new_no_of_observations = X.shape[0]
with self:
pm.set_data({"X": X})
pm.set_data(
{"X": X, "y": np.zeros(new_no_of_observations)},
coords={"obs_ind": np.arange(new_no_of_observations)},
)

def fit(self, X, y, coords: Optional[Dict[str, Any]] = None) -> None:
"""Draw samples from posterior, prior predictive, and posterior predictive
Expand All @@ -111,7 +122,7 @@ def fit(self, X, y, coords: Optional[Dict[str, Any]] = None) -> None:
)
return self.idata

def predict(self, X):
def predict(self, X: np.ndarray):
Copy link
Contributor

Choose a reason for hiding this comment

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

Is the type hint needed or always necessary?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It's not necessary, but in an upcoming PR, the X will be an xarray.DataArray` just for the synthetic control experiment. So at that point I was going to elaborate the type hints further. Goal was just to make it more explicit.

Maybe I'll remove this for now and just introduce type hints if/when the function starts to really need it for keeping readability high.

"""
Predict data given input data `X`

Expand Down Expand Up @@ -206,7 +217,7 @@ class LinearRegression(PyMCModel):
>>> lr = LinearRegression(sample_kwargs={"progressbar": False})
>>> lr.fit(X, y, coords={
... 'coeffs': ['x', 'treated'],
... 'obs_indx': np.arange(rd.shape[0])
... 'obs_ind': np.arange(rd.shape[0])
... },
... )
Inference data...
Expand Down Expand Up @@ -451,7 +462,7 @@ class PropensityScore(PyMCModel):
>>> ps = PropensityScore(sample_kwargs={"progressbar": False})
>>> ps.fit(X, t, coords={
... 'coeffs': ['age', 'race'],
... 'obs_indx': np.arange(df.shape[0])
... 'obs_ind': np.arange(df.shape[0])
... },
... )
Inference...
Expand Down