econml.dr.SparseLinearDRLearner
- class econml.dr.SparseLinearDRLearner(*, model_propensity='auto', model_regression='auto', featurizer=None, fit_cate_intercept=True, discrete_outcome=False, alpha='auto', n_alphas=100, alpha_cov='auto', n_alphas_cov=10, max_iter=1000, tol=0.0001, n_jobs=None, min_propensity=1e-06, categories='auto', cv=2, mc_iters=None, mc_agg='mean', random_state=None, allow_missing=False, use_ray=False, ray_remote_func_options=None)[source]
Bases:
DebiasedLassoCateEstimatorDiscreteMixin
,DRLearner
Special case of the
DRLearner
where the final stage is a Debiased Lasso Regression.In this case, inference can be performed via the debiased lasso approach and its asymptotic normal characterization of the estimated parameters. This is computationally faster than bootstrap inference. Leave the default
inference='auto'
unchanged, or explicitly setinference='debiasedlasso'
at fit time to enable inference via asymptotic normality.More concretely, this estimator assumes that the final cate model for each treatment takes a linear form:
\[\theta_t(X) = \left\langle \theta_t, \phi(X) \right\rangle + \beta_t\]where \(\phi(X)\) is the outcome features of the featurizers, or X if featurizer is None. \(\beta_t\) is a an intercept of the CATE, which is included if
fit_cate_intercept=True
(Default). It fits this by running a debiased lasso regression (i.e. \(\ell_1\)-penalized regression with debiasing), regressing the doubly robust outcome differences on X: i.e. first solves the penalized square loss problem\[\min_{\theta_t, \beta_t} E_n\left[\left(Y_{i, t}^{DR} - Y_{i, 0}^{DR} - \left\langle \theta_t, \phi(X_i) \right\rangle - \beta_t\right)^2\right] + \lambda \left\lVert \theta_t \right\rVert_1\]and then adds a debiasing correction to the solution. If alpha=’auto’ (recommended), then the penalty weight \(\lambda\) is set optimally via cross-validation.
This approach is valid even if the CATE model is not linear in \(\phi(X)\). In this case it performs inference on the best sparse linear approximation of the CATE model.
- Parameters:
model_propensity (estimator, default
'auto'
) – Classifier for Pr[T=t | X, W]. Trained by regressing treatments on (features, controls) concatenated.If
'auto'
, the model will be the best-fitting of a set of linear and forest modelsOtherwise, see Model Selection for the range of supported options
model_regression (estimator, default
'auto'
) – Estimator for E[Y | X, W, T]. Trained by regressing Y on (features, controls, one-hot-encoded treatments) concatenated. The one-hot-encoding excludes the baseline treatment.If
'auto'
, the model will be the best-fitting of a set of linear and forest modelsOtherwise, see Model Selection for the range of supported options; if a single model is specified it should be a classifier if discrete_outcome is True and a regressor otherwise
featurizer (transformer, optional) – Must support fit_transform and transform. Used to create composite features in the final CATE regression. It is ignored if X is None. The final CATE will be trained on the outcome of featurizer.fit_transform(X). If featurizer=None, then CATE is trained on X.
fit_cate_intercept (bool, default True) – Whether the linear CATE model should have a constant term.
discrete_outcome (bool, default False) – Whether the outcome should be treated as binary
alpha (str | float, optional., default ‘auto’.) – CATE L1 regularization applied through the debiased lasso in the final model. ‘auto’ corresponds to a CV form of the
DebiasedLasso
.n_alphas (int, default 100) – How many alphas to try if alpha=’auto’
alpha_cov (str | float, default ‘auto’) – The regularization alpha that is used when constructing the pseudo inverse of the covariance matrix Theta used to for correcting the final state lasso coefficient in the debiased lasso. Each such regression corresponds to the regression of one feature on the remainder of the features.
n_alphas_cov (int, default 10) – How many alpha_cov to try if alpha_cov=’auto’.
max_iter (int, default 1000) – The maximum number of iterations in the Debiased Lasso
tol (float, default 1e-4) – The tolerance for the optimization: if the updates are smaller than
tol
, the optimization code checks the dual gap for optimality and continues until it is smaller thantol
.n_jobs (int or None, optional) – The number of jobs to run in parallel for both fit and predict.
None
means 1 unless in ajoblib.parallel_backend()
context.-1
means using all processors.min_propensity (float, default
1e-6
) – The minimum propensity at which to clip propensity estimates to avoid dividing by zero.categories (‘auto’ or list, default ‘auto’) – The categories to use when encoding discrete treatments (or ‘auto’ to use the unique sorted values). The first category will be treated as the control treatment.
cv (int, cross-validation generator or an iterable, default 2) – Determines the cross-validation splitting strategy. Possible inputs for cv are:
None, to use the default 3-fold cross-validation,
integer, to specify the number of folds.
An iterable yielding (train, test) splits as arrays of indices.
For integer/None inputs, if the treatment is discrete
StratifiedKFold
is used, else,KFold
is used (with a random shuffle in either case).Unless an iterable is used, we call split(X,T) to generate the splits.
mc_iters (int, optional) – The number of times to rerun the first stage models to reduce the variance of the nuisances.
mc_agg ({‘mean’, ‘median’}, default ‘mean’) – How to aggregate the nuisance value for each sample across the mc_iters monte carlo iterations of cross-fitting.
random_state (int,
RandomState
instance or None) – If int, random_state is the seed used by the random number generator; IfRandomState
instance, random_state is the random number generator; If None, the random number generator is theRandomState
instance used bynp.random
.allow_missing (bool) – Whether to allow missing values in W. If True, will need to supply model_propensity and model_regression that can handle missing values.
use_ray (bool, default False) – Whether to use Ray to parallelize the cross-validation step. If True, Ray must be installed.
ray_remote_func_options (dict, default None) – Options to pass to the remote function when using Ray. See https://docs.ray.io/en/latest/ray-core/api/doc/ray.remote.html
Examples
A simple example with the default models:
from econml.dr import DRLearner, SparseLinearDRLearner np.random.seed(123) X = np.random.normal(size=(1000, 3)) T = np.random.binomial(2, scipy.special.expit(X[:, 0])) y = (1 + .5*X[:, 0]) * T + X[:, 0] + np.random.normal(size=(1000,)) est = SparseLinearDRLearner() est.fit(y, T, X=X, W=None)
>>> est.effect(X[:3]) array([ 0.43..., 0.35..., -0.08...]) >>> est.effect_interval(X[:3]) (array([-0.01..., -0.26..., -0.81...]), array([0.87..., 0.98..., 0.65...])) >>> est.coef_(T=1) array([ 0.44..., -0.00..., 0.07...]) >>> est.coef__interval(T=1) (array([ 0.19... , -0.24..., -0.17...]), array([0.70..., 0.22..., 0.32...])) >>> est.intercept_(T=1) np.float64(0.90...) >>> est.intercept__interval(T=1) (np.float64(0.66...), np.float64(1.14...))
- score_
The MSE in the final doubly robust potential outcome regressions, i.e.
\[\frac{1}{n_t} \sum_{t=1}^{n_t} \frac{1}{n} \sum_{i=1}^n (Y_{i, t}^{DR} - \hat{\theta}_t(X_i))^2\]where n_t is the number of treatments (excluding control).
If sample_weight is not None at fit time, then a weighted average across samples is returned.
- Type:
- __init__(*, model_propensity='auto', model_regression='auto', featurizer=None, fit_cate_intercept=True, discrete_outcome=False, alpha='auto', n_alphas=100, alpha_cov='auto', n_alphas_cov=10, max_iter=1000, tol=0.0001, n_jobs=None, min_propensity=1e-06, categories='auto', cv=2, mc_iters=None, mc_agg='mean', random_state=None, allow_missing=False, use_ray=False, ray_remote_func_options=None)[source]
Methods
__init__
(*[, model_propensity, ...])ate
([X, T0, T1])Calculate the average treatment effect \(E_X[\tau(X, T0, T1)]\).
ate_inference
([X, T0, T1])Inference results for the quantity \(E_X[\tau(X, T0, T1)]\) produced by the model.
ate_interval
([X, T0, T1, alpha])Confidence intervals for the quantity \(E_X[\tau(X, T0, T1)]\) produced by the model.
cate_feature_names
([feature_names])Get the output feature names.
cate_output_names
([output_names])Public interface for getting output names.
cate_treatment_names
([treatment_names])Get treatment names.
coef_
(T)Get the coefficients in the linear model of the constant marginal treatment effect associated with treatment T.
Get inference results for the coefficients in the linear model of the constant marginal treatment effect.
coef__interval
(T, *[, alpha])Get the confidence interval for the coefficients in the linear model of the constant marginal treatment effect.
const_marginal_ate
([X])Calculate the average constant marginal CATE \(E_X[\theta(X)]\).
Inference results for the quantities \(E_X[\theta(X)]\) produced by the model.
const_marginal_ate_interval
([X, alpha])Confidence intervals for the quantities \(E_X[\theta(X)]\) produced by the model.
Calculate the constant marginal CATE \(\theta(·)\).
Inference results for the quantities \(\theta(X)\) produced by the model.
const_marginal_effect_interval
([X, alpha])Confidence intervals for the quantities \(\theta(X)\) produced by the model.
effect
([X, T0, T1])Calculate the heterogeneous treatment effect \(\tau(X, T0, T1)\).
effect_inference
([X, T0, T1])Inference results for the quantities \(\tau(X, T0, T1)\) produced by the model.
effect_interval
([X, T0, T1, alpha])Confidence intervals for the quantities \(\tau(X, T0, T1)\) produced by the model.
fit
(Y, T, *[, X, W, sample_weight, groups, ...])Estimate the counterfactual model from data, i.e. estimates function \(\theta(\cdot)\).
intercept_
(T)Get the intercept in the linear model of the constant marginal treatment effect associated with treatment T.
Get inference results for the intercept in the linear model of the constant marginal treatment effect.
intercept__interval
(T, *[, alpha])Get the intercept in the linear model of the constant marginal treatment effect.
marginal_ate
(T[, X])Calculate the average marginal effect \(E_{T, X}[\partial\tau(T, X)]\).
marginal_ate_inference
(T[, X])Inference results for the quantities \(E_{T,X}[\partial \tau(T, X)]\) produced by the model.
marginal_ate_interval
(T[, X, alpha])Confidence intervals for the quantities \(E_{T,X}[\partial \tau(T, X)]\) produced by the model.
marginal_effect
(T[, X])Calculate the heterogeneous marginal effect \(\partial\tau(T, X)\).
marginal_effect_inference
(T[, X])Inference results for the quantities \(\partial \tau(T, X)\) produced by the model.
marginal_effect_interval
(T[, X, alpha])Confidence intervals for the quantities \(\partial \tau(T, X)\) produced by the model.
model_cate
([T])Get the fitted final CATE model.
refit_final
(*[, inference])Estimate the counterfactual model using a new final model specification but with cached first stage results.
robustness_value
(T[, null_hypothesis, ...])Calculate the robustness value for the ATE for a given treatment category.
score
(Y, T[, X, W, sample_weight])Score the fitted CATE model on a new data set.
sensitivity_interval
(T[, alpha, c_y, c_t, ...])Calculate the sensitivity interval for the ATE for a given treatment category.
sensitivity_summary
(T[, null_hypothesis, ...])Generate a summary of the sensitivity analysis for the ATE for a given treatment.
shap_values
(X, *[, feature_names, ...])Shap value for the final stage models (const_marginal_effect).
summary
(T, *[, alpha, value, decimals, ...])Get a summary of coefficient and intercept in the linear model of the constant marginal treatment effect.
Attributes
Get a
DoWhyWrapper
to enable functionality (e.g. causal graph, refutation test, etc.) from dowhy.Get the fitted featurizer.
fit_cate_intercept_
fitted_models_final
model_final
model_final_
models_nuisance_
Get the fitted propensity models.
Get the fitted regression models.
Get the fitted final CATE model.
multitask_model_final
Get the score for the propensity model on out-of-sample training data.
Get the score for the regression model on out-of-sample training data.
ortho_learner_model_final_
transformer
- ate(X=None, *, T0=0, T1=1)
Calculate the average treatment effect \(E_X[\tau(X, T0, T1)]\).
The effect is calculated between the two treatment points and is averaged over the population of X variables.
- Parameters:
T0 ((m, d_t) matrix or vector of length m) – Base treatments for each sample
T1 ((m, d_t) matrix or vector of length m) – Target treatments for each sample
X ((m, d_x) matrix, optional) – Features for each sample
- Returns:
τ – Average treatment effects on each outcome Note that when Y is a vector rather than a 2-dimensional array, the result will be a scalar
- Return type:
float or (d_y,) array
- ate_inference(X=None, *, T0=0, T1=1)
Inference results for the quantity \(E_X[\tau(X, T0, T1)]\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
X ((m, d_x) matrix, optional) – Features for each sample
T0 ((m, d_t) matrix or vector of length m, default 0) – Base treatments for each sample
T1 ((m, d_t) matrix or vector of length m, default 1) – Target treatments for each sample
- Returns:
PopulationSummaryResults – The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results.
- Return type:
- ate_interval(X=None, *, T0=0, T1=1, alpha=0.05)
Confidence intervals for the quantity \(E_X[\tau(X, T0, T1)]\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
X ((m, d_x) matrix, optional) – Features for each sample
T0 ((m, d_t) matrix or vector of length m, default 0) – Base treatments for each sample
T1 ((m, d_t) matrix or vector of length m, default 1) – Target treatments for each sample
alpha (float in [0, 1], default 0.05) – The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported.
- Returns:
lower, upper – The lower and the upper bounds of the confidence interval for each quantity.
- Return type:
tuple(type of
ate(X, T0, T1)
, type ofate(X, T0, T1))
)
- cate_feature_names(feature_names=None)
Get the output feature names.
- Parameters:
feature_names (list of str of length X.shape[1] or None) – The names of the input features. If None and X is a dataframe, it defaults to the column names from the dataframe.
- Returns:
out_feature_names – The names of the output features \(\phi(X)\), i.e. the features with respect to which the final CATE model for each treatment is linear. It is the names of the features that are associated with each entry of the
coef_()
parameter. Available only when the featurizer is not None and has a method: get_feature_names(feature_names). Otherwise None is returned.- Return type:
- cate_output_names(output_names=None)
Public interface for getting output names.
To be overriden by estimators that apply transformations the outputs.
- cate_treatment_names(treatment_names=None)
Get treatment names.
If the treatment is discrete or featurized, it will return expanded treatment names.
- Parameters:
treatment_names (list of str of length T.shape[1], optional) – The names of the treatments. If None and the T passed to fit was a dataframe, it defaults to the column names from the dataframe.
- Returns:
out_treatment_names – Returns (possibly expanded) treatment names.
- Return type:
- coef_(T)
Get the coefficients in the linear model of the constant marginal treatment effect associated with treatment T.
- Parameters:
T (alphanumeric) – The input treatment for which we want the coefficients.
- Returns:
coef – Where n_x is the number of features that enter the final model (either the dimension of X or the dimension of featurizer.fit_transform(X) if the CATE estimator has a featurizer.)
- Return type:
(n_x,) or (n_y, n_x) array_like
- coef__inference(T)
Get inference results for the coefficients in the linear model of the constant marginal treatment effect.
- Parameters:
T (alphanumeric) – The input treatment for which we want the coefficients.
- Returns:
InferenceResults – The inference of the coefficients in the final linear model
- Return type:
- coef__interval(T, *, alpha=0.05)
Get the confidence interval for the coefficients in the linear model of the constant marginal treatment effect.
- Parameters:
T (alphanumeric) – The input treatment for which we want the coefficients.
alpha (float in [0, 1], default 0.05) – The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported.
- Returns:
lower, upper – The lower and upper bounds of the confidence interval for each quantity.
- Return type:
- const_marginal_ate(X=None)
Calculate the average constant marginal CATE \(E_X[\theta(X)]\).
- Parameters:
X ((m, d_x) matrix, optional) – Features for each sample.
- Returns:
theta – Average constant marginal CATE of each treatment on each outcome. Note that when Y or T is a vector rather than a 2-dimensional array, the corresponding singleton dimensions in the output will be collapsed (e.g. if both are vectors, then the output of this method will be a scalar)
- Return type:
(d_y, d_t) matrix
- const_marginal_ate_inference(X=None)
Inference results for the quantities \(E_X[\theta(X)]\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
X ((m, d_x) matrix, optional) – Features for each sample
- Returns:
PopulationSummaryResults – The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results.
- Return type:
- const_marginal_ate_interval(X=None, *, alpha=0.05)
Confidence intervals for the quantities \(E_X[\theta(X)]\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
X ((m, d_x) matrix, optional) – Features for each sample
alpha (float in [0, 1], default 0.05) – The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported.
- Returns:
lower, upper – The lower and the upper bounds of the confidence interval for each quantity.
- Return type:
tuple(type of
const_marginal_ate(X)
, type ofconst_marginal_ate(X)
)
- const_marginal_effect(X=None)
Calculate the constant marginal CATE \(\theta(·)\).
The marginal effect is conditional on a vector of features on a set of m test samples X[i].
- Parameters:
X ((m, d_x) matrix, optional) – Features for each sample.
- Returns:
theta – Constant marginal CATE of each treatment on each outcome for each sample X[i]. Note that when Y or T is a vector rather than a 2-dimensional array, the corresponding singleton dimensions in the output will be collapsed (e.g. if both are vectors, then the output of this method will also be a vector)
- Return type:
(m, d_y, d_t) matrix or (d_y, d_t) matrix if X is None
- const_marginal_effect_inference(X=None)
Inference results for the quantities \(\theta(X)\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
X ((m, d_x) matrix, optional) – Features for each sample
- Returns:
InferenceResults – The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results.
- Return type:
- const_marginal_effect_interval(X=None, *, alpha=0.05)
Confidence intervals for the quantities \(\theta(X)\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
X ((m, d_x) matrix, optional) – Features for each sample
alpha (float in [0, 1], default 0.05) – The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported.
- Returns:
lower, upper – The lower and the upper bounds of the confidence interval for each quantity.
- Return type:
tuple(type of
const_marginal_effect(X)
, type ofconst_marginal_effect(X)
)
- effect(X=None, *, T0=0, T1=1)
Calculate the heterogeneous treatment effect \(\tau(X, T0, T1)\).
The effect is calculated between the two treatment points conditional on a vector of features on a set of m test samples \(\{T0_i, T1_i, X_i\}\).
- Parameters:
T0 ((m, d_t) matrix or vector of length m) – Base treatments for each sample
T1 ((m, d_t) matrix or vector of length m) – Target treatments for each sample
X ((m, d_x) matrix, optional) – Features for each sample
- Returns:
τ – Heterogeneous treatment effects on each outcome for each sample Note that when Y is a vector rather than a 2-dimensional array, the corresponding singleton dimension will be collapsed (so this method will return a vector)
- Return type:
(m, d_y) matrix
- effect_inference(X=None, *, T0=0, T1=1)
Inference results for the quantities \(\tau(X, T0, T1)\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
X ((m, d_x) matrix, optional) – Features for each sample
T0 ((m, d_t) matrix or vector of length m, default 0) – Base treatments for each sample
T1 ((m, d_t) matrix or vector of length m, default 1) – Target treatments for each sample
- Returns:
InferenceResults – The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results.
- Return type:
- effect_interval(X=None, *, T0=0, T1=1, alpha=0.05)
Confidence intervals for the quantities \(\tau(X, T0, T1)\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
X ((m, d_x) matrix, optional) – Features for each sample
T0 ((m, d_t) matrix or vector of length m, default 0) – Base treatments for each sample
T1 ((m, d_t) matrix or vector of length m, default 1) – Target treatments for each sample
alpha (float in [0, 1], default 0.05) – The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported.
- Returns:
lower, upper – The lower and the upper bounds of the confidence interval for each quantity.
- Return type:
tuple(type of
effect(X, T0, T1)
, type ofeffect(X, T0, T1))
)
- fit(Y, T, *, X=None, W=None, sample_weight=None, groups=None, cache_values=False, inference='auto')[source]
Estimate the counterfactual model from data, i.e. estimates function \(\theta(\cdot)\).
- Parameters:
Y ((n,) vector of length n) – Outcomes for each sample
T ((n,) vector of length n) – Treatments for each sample
X ((n, d_x) matrix, optional) – Features for each sample
W ((n, d_w) matrix, optional) – Controls for each sample
sample_weight ((n,) array_like or None) – Individual weights for each sample. If None, it assumes equal weight.
groups ((n,) vector, optional) – All rows corresponding to the same group will be kept together during splitting. If groups is not None, the cv argument passed to this class’s initializer must support a ‘groups’ argument to its split method.
cache_values (bool, default False) – Whether to cache inputs and first stage results, which will allow refitting a different final model
inference (str,
Inference
instance, or None) – Method for performing inference. This estimator supports'bootstrap'
(or an instance ofBootstrapInference
) and'debiasedlasso'
(or an instance ofLinearModelInferenceDiscrete
).
- Returns:
self
- Return type:
DRLearner instance
- intercept_(T)
Get the intercept in the linear model of the constant marginal treatment effect associated with treatment T.
- Parameters:
T (alphanumeric) – The input treatment for which we want the intercept.
- Returns:
intercept
- Return type:
float or (n_y,) array_like
- intercept__inference(T)
Get inference results for the intercept in the linear model of the constant marginal treatment effect.
- Parameters:
T (alphanumeric) – The input treatment for which we want the intercept.
- Returns:
InferenceResults – The inference of the intercept in the final linear model
- Return type:
- intercept__interval(T, *, alpha=0.05)
Get the intercept in the linear model of the constant marginal treatment effect.
- Parameters:
T (alphanumeric) – The input treatment for which we want the intercept.
alpha (float in [0, 1], default 0.05) – The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported.
- Returns:
lower, upper – The lower and upper bounds of the confidence interval.
- Return type:
tuple(type of
intercept_(T)
, type ofintercept_(T)
)
- marginal_ate(T, X=None)
Calculate the average marginal effect \(E_{T, X}[\partial\tau(T, X)]\).
The marginal effect is calculated around a base treatment point and averaged over the population of X.
- Parameters:
T ((m, d_t) matrix) – Base treatments for each sample
X ((m, d_x) matrix, optional) – Features for each sample
- Returns:
grad_tau – Average marginal effects on each outcome Note that when Y or T is a vector rather than a 2-dimensional array, the corresponding singleton dimensions in the output will be collapsed (e.g. if both are vectors, then the output of this method will be a scalar)
- Return type:
(d_y, d_t) array
- marginal_ate_inference(T, X=None)
Inference results for the quantities \(E_{T,X}[\partial \tau(T, X)]\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
T ((m, d_t) matrix) – Base treatments for each sample
X ((m, d_x) matrix, optional) – Features for each sample
- Returns:
PopulationSummaryResults – The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results.
- Return type:
- marginal_ate_interval(T, X=None, *, alpha=0.05)
Confidence intervals for the quantities \(E_{T,X}[\partial \tau(T, X)]\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
T ((m, d_t) matrix) – Base treatments for each sample
X ((m, d_x) matrix, optional) – Features for each sample
alpha (float in [0, 1], default 0.05) – The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported.
- Returns:
lower, upper – The lower and the upper bounds of the confidence interval for each quantity.
- Return type:
tuple(type of
marginal_ate(T, X)
, type ofmarginal_ate(T, X)
)
- marginal_effect(T, X=None)
Calculate the heterogeneous marginal effect \(\partial\tau(T, X)\).
The marginal effect is calculated around a base treatment point conditional on a vector of features on a set of m test samples \(\{T_i, X_i\}\). If treatment_featurizer is None, the base treatment is ignored in this calculation and the result is equivalent to const_marginal_effect.
- Parameters:
T ((m, d_t) matrix) – Base treatments for each sample
X ((m, d_x) matrix, optional) – Features for each sample
- Returns:
grad_tau – Heterogeneous marginal effects on each outcome for each sample Note that when Y or T is a vector rather than a 2-dimensional array, the corresponding singleton dimensions in the output will be collapsed (e.g. if both are vectors, then the output of this method will also be a vector)
- Return type:
(m, d_y, d_t) array
- marginal_effect_inference(T, X=None)
Inference results for the quantities \(\partial \tau(T, X)\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
T ((m, d_t) matrix) – Base treatments for each sample
X ((m, d_x) matrix, optional) – Features for each sample
- Returns:
InferenceResults – The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results.
- Return type:
- marginal_effect_interval(T, X=None, *, alpha=0.05)
Confidence intervals for the quantities \(\partial \tau(T, X)\) produced by the model.
Available only when
inference
is notNone
, when calling the fit method.- Parameters:
T ((m, d_t) matrix) – Base treatments for each sample
X ((m, d_x) matrix, optional) – Features for each sample
alpha (float in [0, 1], default 0.05) – The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported.
- Returns:
lower, upper – The lower and the upper bounds of the confidence interval for each quantity.
- Return type:
tuple(type of
marginal_effect(T, X)
, type ofmarginal_effect(T, X)
)
- model_cate(T=1)
Get the fitted final CATE model.
- Parameters:
T (alphanumeric) – The treatment with respect to which we want the fitted CATE model.
- Returns:
model_cate – An instance of the model_final object that was fitted after calling fit which corresponds to the CATE model for treatment T=t, compared to baseline. Available when multitask_model_final=False.
- Return type:
- refit_final(*, inference='auto')
Estimate the counterfactual model using a new final model specification but with cached first stage results.
In order for this to succeed,
fit
must have been called withcache_values=True
. This call will only refit the final model. This call we use the current setting of any parameters that change the final stage estimation. If any parameters that change how the first stage nuisance estimates has also been changed then it will have no effect. You need to call fit again to change the first stage estimation results.- Parameters:
inference (inference method, optional) – The string or object that represents the inference method
- Returns:
self – This instance
- Return type:
- robustness_value(T, null_hypothesis=0, alpha=0.05, interval_type='ci')
Calculate the robustness value for the ATE for a given treatment category.
The robustness value is the level of confounding (between 0 and 1) in both the treatment and outcome that would result in enough omitted variable bias such that we can no longer reject the null hypothesis. When null_hypothesis is the default of 0, the robustness value has the interpretation that it is the level of confounding that would make the ATE statistically insignificant.
A higher value indicates a more robust estimate.
Returns 0 if the original interval already includes the null_hypothesis.
Based on [Chernozhukov2022]
- Parameters:
T (alphanumeric) – The treatment with respect to calculate the robustness value.
null_hypothesis (float, default 0) – The null_hypothesis value for the ATE.
alpha (float, default 0.05) – The significance level for the robustness value.
interval_type (str, default ‘ci’) – The type of interval to return. Can be ‘ci’ or ‘theta’
- Returns:
The robustness value
- Return type:
- score(Y, T, X=None, W=None, sample_weight=None)
Score the fitted CATE model on a new data set.
Generates nuisance parameters for the new data set based on the fitted residual nuisance models created at fit time. It uses the mean prediction of the models fitted by the different crossfit folds. Then calculates the MSE of the final residual Y on residual T regression.
If model_final does not have a score method, then it raises an
AttributeError
- Parameters:
Y ((n,) vector of length n) – Outcomes for each sample
T ((n,) vector of length n) – Treatments for each sample
X ((n, d_x) matrix, optional) – Features for each sample
W ((n, d_w) matrix, optional) – Controls for each sample
sample_weight ((n,) vector, optional) – Weights for each samples
- Returns:
score – The MSE of the final CATE model on the new data.
- Return type:
- sensitivity_interval(T, alpha=0.05, c_y=0.05, c_t=0.05, rho=1.0, interval_type='ci')
Calculate the sensitivity interval for the ATE for a given treatment category.
The sensitivity interval is the range of values for the ATE that are consistent with the observed data, given a specified level of confounding.
Based on [Chernozhukov2022]
- Parameters:
T (alphanumeric) – The treatment with respect to calculate the sensitivity interval.
alpha (float, default 0.05) – The significance level for the sensitivity interval.
c_y (float, default 0.05) – The level of confounding in the outcome. Ranges from 0 to 1.
c_d (float, default 0.05) – The level of confounding in the treatment. Ranges from 0 to 1.
interval_type (str, default ‘ci’) – The type of interval to return. Can be ‘ci’ or ‘theta’
- Returns:
(lb, ub) – sensitivity interval for the ATE for treatment T
- Return type:
tuple of floats
- sensitivity_summary(T, null_hypothesis=0, alpha=0.05, c_y=0.05, c_t=0.05, rho=1.0, decimals=3)
Generate a summary of the sensitivity analysis for the ATE for a given treatment.
- Parameters:
null_hypothesis (float, default 0) – The null_hypothesis value for the ATE.
alpha (float, default 0.05) – The significance level for the sensitivity interval.
c_y (float, default 0.05) – The level of confounding in the outcome. Ranges from 0 to 1.
c_d (float, default 0.05) – The level of confounding in the treatment. Ranges from 0 to 1.
decimals (int, default 3) – Number of decimal places to round each column to.
- shap_values(X, *, feature_names=None, treatment_names=None, output_names=None, background_samples=100)
Shap value for the final stage models (const_marginal_effect).
- Parameters:
X ((m, d_x) matrix) – Features for each sample. Should be in the same shape of fitted X in final stage.
feature_names (list of str of length X.shape[1], optional) – The names of input features.
treatment_names (list, optional) – The name of featurized treatment. In discrete treatment scenario, the name should not include the name of the baseline treatment (i.e. the control treatment, which by default is the alphabetically smaller)
output_names (list, optional) – The name of the outcome.
background_samples (int , default 100) – How many samples to use to compute the baseline effect. If None then all samples are used.
- Returns:
shap_outs – A nested dictionary by using each output name (e.g. ‘Y0’, ‘Y1’, … when output_names=None) and each treatment name (e.g. ‘T0’, ‘T1’, … when treatment_names=None) as key and the shap_values explanation object as value. If the input data at fit time also contain metadata, (e.g. are pandas DataFrames), then the column metatdata for the treatments, outcomes and features are used instead of the above defaults (unless the user overrides with explicitly passing the corresponding names).
- Return type:
nested dictionary of Explanation object
- summary(T, *, alpha=0.05, value=0, decimals=3, feature_names=None, treatment_names=None, output_names=None)
Get a summary of coefficient and intercept in the linear model of the constant marginal treatment effect.
- Parameters:
T (alphanumeric) – The input treatment for which we want the summary.
alpha (float in [0, 1], default 0.05) – The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported.
value (float, default 0) – The mean value of the metric you’d like to test under null hypothesis.
decimals (int, default 3) – Number of decimal places to round each column to.
feature_names (list of str, optional) – The input of the feature names
treatment_names (list of str, optional) – The names of the treatments
output_names (list of str, optional) – The names of the outputs
- Returns:
smry – this holds the summary tables and text, which can be printed or converted to various output formats.
- Return type:
Summary instance
- property dowhy
Get a
DoWhyWrapper
to enable functionality (e.g. causal graph, refutation test, etc.) from dowhy.- Returns:
DoWhyWrapper – An instance of
DoWhyWrapper
- Return type:
instance
- property featurizer_
Get the fitted featurizer.
- Returns:
featurizer – An instance of the fitted featurizer that was used to preprocess X in the final CATE model training. Available only when featurizer is not None and X is not None.
- Return type:
object of type(featurizer)
- property models_propensity
Get the fitted propensity models.
- Returns:
models_propensity – A nested list of instances of the model_propensity object. Number of sublist equals to number of monte carlo iterations, each element in the sublist corresponds to a crossfitting fold and is the model instance that was fitted for that training fold.
- Return type:
nested list of objects of type(model_propensity)
- property models_regression
Get the fitted regression models.
- Returns:
model_regression – A nested list of instances of the model_regression object. Number of sublist equals to number of monte carlo iterations, each element in the sublist corresponds to a crossfitting fold and is the model instance that was fitted for that training fold.
- Return type:
nested list of objects of type(model_regression)
- property multitask_model_cate
Get the fitted final CATE model.
- Returns:
multitask_model_cate – An instance of the model_final object that was fitted after calling fit which corresponds whose vector of outcomes correspond to the CATE model for each treatment, compared to baseline. Available only when multitask_model_final=True.
- Return type:
object of type(model_final)
- property nuisance_scores_propensity
Get the score for the propensity model on out-of-sample training data.
- property nuisance_scores_regression
Get the score for the regression model on out-of-sample training data.