InstrumentalVariable#
- class causalpy.experiments.instrumental_variable.InstrumentalVariable[source]#
A class to analyse instrumental variable style experiments.
- Parameters:
instruments_data (
NativeDataFrame) – Instruments for our treatment variable, as any eager dataframe Narwhals supports, such as pandas, Polars, or PyArrow. Should contain instruments Z, and treatment t. Converted to pandas internally.data (
NativeDataFrame) – Covariates for fitting the focal regression of interest, as any eager dataframe Narwhals supports. Should contain covariates X including treatment t and outcome y. Converted to pandas internally.instruments_formula (
str) – A statistical model formula for the instrumental stage regression, e.g.t ~ 1 + z1 + z2 + z3.formula (
str) – A statistical model formula for the focal regression, e.g.y ~ 1 + t + x1 + x2 + x3.model (
InstrumentalVariableRegression|None) – A PyMC model. Defaults to InstrumentalVariableRegression.priors (
dict|None) – Dictionary of priors for the mus and sigmas of both regressions. If priors are not specified we will substitute MLE estimates for the beta coefficients. Example:priors = {"mus": [0, 0], "sigmas": [1, 1], "eta": 2, "lkj_sd": 2}.vs_prior_type (str or None, default=None) – Type of variable selection prior: ‘spike_and_slab’, ‘horseshoe’, or None. If None, uses standard normal priors.
vs_hyperparams (dict, optional) – Hyperparameters for variable selection priors. Only used if vs_prior_type is not None.
binary_treatment (bool, default=False) – A indicator for whether the treatment to be modelled is binary or not. Determines which PyMC model we use to model the joint outcome and treatment.
Notes
Lazy lifecycle
Construction validates the inputs, builds the design matrices, and runs the deterministic OLS/2SLS reference fits — no sampling happens. Call
fit()to build the model graph and draw posterior samples. Prior predictive sampling is unavailable: theInstrumentalVariableRegressionbackend declares no prior phase, sosample_prior_predictive()raisesPriorPredictiveNotSupportedException.Estimate extraction
The class computes naive OLS and two-stage least-squares reference fits, then fits a joint Bayesian model for the treatment and outcome equations. Under the instrumental-variable assumptions, the causal quantity is read from the outcome-stage coefficient associated with the instrumented treatment; no counterfactual prediction or population standardization is performed. For binary treatments, its LATE interpretation applies to the complier population induced by the instrument; continuous treatments require the corresponding structural IV interpretation.
Examples
>>> import pandas as pd >>> import causalpy as cp >>> from causalpy.pymc_models import InstrumentalVariableRegression >>> import numpy as np >>> N = 100 >>> e1 = np.random.normal(0, 3, N) >>> e2 = np.random.normal(0, 1, N) >>> Z = np.random.uniform(0, 1, N) >>> ## Ensure the endogeneity of the the treatment variable >>> X = -1 + 4 * Z + e2 + 2 * e1 >>> y = 2 + 3 * X + 3 * e1 >>> test_data = pd.DataFrame({"y": y, "X": X, "Z": Z}) >>> sample_kwargs = { ... "tune": 1, ... "draws": 5, ... "chains": 2, ... "cores": 1, ... "target_accept": 0.95, ... "progressbar": False, ... } >>> instruments_formula = "X ~ 1 + Z" >>> formula = "y ~ 1 + X" >>> instruments_data = test_data[["X", "Z"]] >>> data = test_data[["y", "X"]] >>> iv = cp.InstrumentalVariable( ... instruments_data=instruments_data, ... data=data, ... instruments_formula=instruments_formula, ... formula=formula, ... model=InstrumentalVariableRegression(sample_kwargs=sample_kwargs), ... ).fit() >>> # With variable selection >>> iv = cp.InstrumentalVariable( ... instruments_data=instruments_data, ... data=data, ... instruments_formula=instruments_formula, ... formula=formula, ... model=InstrumentalVariableRegression(sample_kwargs=sample_kwargs), ... vs_prior_type="spike_and_slab", ... vs_hyperparams={"slab_sigma": 5.0}, ... ).fit()
Methods
No-op: IV constructs its graph lazily inside the model's fit.
InstrumentalVariable.effect_summary(*[, group])Raise because unified effect summaries are unavailable.
InstrumentalVariable.fit(**kwargs)Build the IV model graph and sample the posterior phase.
InstrumentalVariable.generate_report(*[, ...])Generate a self-contained HTML report for this experiment.
Two Stage Least Squares Fit.
Naive Ordinary Least Squares.
Validate the input data and model formula for correctness.
InstrumentalVariable.plot(*[, show, ...])Plot the results.
Ask the model to print its posterior coefficients.
Run the optional prior phase and populate
prior_result.Set optional maketables rendering options for this experiment.
InstrumentalVariable.summary([round_to])Print summary of main results and model coefficients.
Attributes
has_prior_predictiveWhether the prior phase has run (draws, and bundle where kept).
idataReturn fitted DataTree when the model backend supports it.
is_builtWhether the model graph / fit design exists (no draws implied).
is_configureddesign matrices are ready.
is_fittedWhether posterior draws and the posterior result bundle exist.
modelThe underlying model instance.
prior_resultPrior-group result bundle; raises before prior sampling.
resultPosterior-group result bundle; raises before
fit().supports_bayessupports_olssupports_pymc_forecastlabelsdata- __init__(instruments_data, data, instruments_formula, formula, model=None, priors=None, vs_prior_type=None, vs_hyperparams=None, binary_treatment=False)[source]#
- Parameters:
instruments_data (DataFrameLike)
data (DataFrameLike)
instruments_formula (str)
formula (str)
model (InstrumentalVariableRegression | None)
priors (dict | None)
- Return type:
None
- classmethod __new__(*args, **kwargs)#