econml.iv.dr.ForestDRIV
- class econml.iv.dr.ForestDRIV(*, model_y_xw='auto', model_t_xw='auto', model_z_xw='auto', model_t_xwz='auto', model_tz_xw='auto', fit_cov_directly=True, flexible_model_effect='auto', prel_cate_approach='driv', prel_cv=1, prel_opt_reweighted=True, projection=False, featurizer=None, n_estimators=1000, max_depth=None, min_samples_split=5, min_samples_leaf=5, min_weight_fraction_leaf=0.0, max_features='auto', min_impurity_decrease=0.0, max_samples=0.45, min_balancedness_tol=0.45, honest=True, subforest_size=4, n_jobs=- 1, verbose=0, cov_clip=0.001, opt_reweighted=False, discrete_outcome=False, discrete_instrument=False, discrete_treatment=False, treatment_featurizer=None, 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:
econml._cate_estimator.ForestModelFinalCateEstimatorMixin
,econml.iv.dr._dr.DRIV
Instance of DRIV with a
RegressionForest
as a final model, so as to enable non-parametric inference.- Parameters
model_y_xw (estimator, default
'auto'
) – Determines how to fit the outcome to the features and controls (\(\E[Y | X, W]\)).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
model_t_xw (estimator, default
'auto'
) – Determines how to fit the treatment to the features and controls (\(\E[T | X, W]\)).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_treatment is True and a regressor otherwise
model_z_xw (estimator, default
'auto'
) – Determines how to fit the instrument to the features and controls (\(\E[Z | X, W]\)).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_instrument is True and a regressor otherwise
model_t_xwz (estimator, default
'auto'
) – Determines how to fit the treatment to the features, controls, and instrument (\(\E[T | X, W, Z]\)).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_treatment is True and a regressor otherwise
model_tz_xw (estimator, default
'auto'
) – Determines how to fit the covariance to the features and controls (\(\E[T*Z | X, W]\) or \(\E[\tilde{T}*\tilde{Z} | X, W]\) depending on fit_cov_directly).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_treatment is True and a regressor otherwise
fit_cov_directly (bool, default True) – Whether to fit \(\E[\tilde{T}*\tilde{Z} | X, W]\) instead of \(\E[T*Z | X, W]\). Otherwise, we compute \(\E[\tilde{T}*\tilde{Z} | X, W]\) from \(\E[T*Z | X, W] - \E[T | X, W] \E[Z | X, W]\).
flexible_model_effect (estimator or ‘auto’ (default is ‘auto’)) – a flexible model for a preliminary version of the CATE, must accept sample_weight at fit time. If ‘auto’,
StatsModelsLinearRegression
will be applied.prel_cate_approach (one of {‘driv’, ‘dmliv’}, default ‘driv’) – model that estimates a preliminary version of the CATE. If ‘driv’,
_DRIV
will be used. If ‘dmliv’,NonParamDMLIV
will be usedprel_cv (int, cross-validation generator or an iterable, default 1) – Determines the cross-validation splitting strategy for the preliminary effect model.
prel_opt_reweighted (bool, default True) – Whether to reweight the samples to minimize variance for the preliminary effect model.
projection (bool, default False) – If True, we fit a slight variant of DRIV where we use E[T|X, W, Z] as the instrument as opposed to Z, model_z_xw will be disabled; If False, model_t_xwz will be disabled.
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.
n_estimators (int, default 100) – The total number of trees in the forest. The forest consists of a forest of sqrt(n_estimators) sub-forests, where each sub-forest contains sqrt(n_estimators) trees.
max_depth (int or None, optional) – The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.
min_samples_split (int, float, default 2) – The minimum number of splitting samples required to split an internal node.
If int, then consider min_samples_split as the minimum number.
If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the minimum number of samples for each split.
min_samples_leaf (int, float, default 1) – The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least
min_samples_leaf
splitting samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. After construction the tree is also pruned so that there are at least min_samples_leaf estimation samples on each leaf.If int, then consider min_samples_leaf as the minimum number.
If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node.
min_weight_fraction_leaf (float, default 0.) – The minimum weighted fraction of the sum total of weights (of all splitting samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. After construction the tree is pruned so that the fraction of the sum total weight of the estimation samples contained in each leaf node is at least min_weight_fraction_leaf
max_features (int, float, str, or None, default “auto”) – The number of features to consider when looking for the best split:
If int, then consider max_features features at each split.
If float, then max_features is a fraction and int(max_features * n_features) features are considered at each split.
If “auto”, then max_features=n_features.
If “sqrt”, then max_features=sqrt(n_features).
If “log2”, then max_features=log2(n_features).
If None, then max_features=n_features.
Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than
max_features
features.min_impurity_decrease (float, default 0.) – A node will be split if this split induces a decrease of the impurity greater than or equal to this value.
The weighted impurity decrease equation is the following:
N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity)
where
N
is the total number of split samples,N_t
is the number of split samples at the current node,N_t_L
is the number of split samples in the left child, andN_t_R
is the number of split samples in the right child.N
,N_t
,N_t_R
andN_t_L
all refer to the weighted sum, ifsample_weight
is passed.max_samples (int or float in (0, .5], default .45,) – The number of samples to use for each subsample that is used to train each tree:
If int, then train each tree on max_samples samples, sampled without replacement from all the samples
If float, then train each tree on ceil(max_samples * n_samples), sampled without replacement from all the samples.
min_balancedness_tol (float in [0, .5], default .45) – How imbalanced a split we can tolerate. This enforces that each split leaves at least (.5 - min_balancedness_tol) fraction of samples on each side of the split; or fraction of the total weight of samples, when sample_weight is not None. Default value, ensures that at least 5% of the parent node weight falls in each side of the split. Set it to 0.0 for no balancedness and to .5 for perfectly balanced splits. For the formal inference theory to be valid, this has to be any positive constant bounded away from zero.
honest (bool, default True) – Whether to use honest trees, i.e. half of the samples are used for creating the tree structure and the other half for the estimation at the leafs. If False, then all samples are used for both parts.
subforest_size (int, default 4,) – The number of trees in each sub-forest that is used in the bootstrap-of-little-bags calculation. The parameter n_estimators must be divisible by subforest_size. Should typically be a small constant.
n_jobs (int or None, default -1) – 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. See Glossary for more details.verbose (int, default 0) – Controls the verbosity when fitting and predicting.
cov_clip (float, default 0.1) – clipping of the covariate for regions with low “overlap”, to reduce variance
opt_reweighted (bool, default False) – Whether to reweight the samples to minimize variance. If True then model_final.fit must accept sample_weight as a kw argument. If True then assumes the model_final is flexible enough to fit the true CATE model. Otherwise, it method will return a biased projection to the model_final space, biased to give more weight on parts of the feature space where the instrument is strong.
discrete_outcome (bool, default False) – Whether the outcome should be treated as binary
discrete_instrument (bool, default False) – Whether the instrument values should be treated as categorical, rather than continuous, quantities
discrete_treatment (bool, default False) – Whether the treatment values should be treated as categorical, rather than continuous, quantities
treatment_featurizer (transformer, optional) – Must support fit_transform and transform. Used to create composite treatment in the final CATE regression. The final CATE will be trained on the outcome of featurizer.fit_transform(T). If featurizer=None, then CATE is trained on T.
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(concat[W, X], T) to generate the splits. If all W, X are None, then we call split(ones((T.shape[0], 1)), T).
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, default None) – If int, random_state is the seed used by the random number generator; If
RandomState
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 nuisance models 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.iv.dr import ForestDRIV # Define the data generation functions def dgp(n, p, true_fn): X = np.random.normal(0, 1, size=(n, p)) Z = np.random.binomial(1, 0.5, size=(n,)) nu = np.random.uniform(0, 10, size=(n,)) coef_Z = 0.8 C = np.random.binomial( 1, coef_Z * scipy.special.expit(0.4 * X[:, 0] + nu) ) # Compliers when recomended C0 = np.random.binomial( 1, 0.06 * np.ones(X.shape[0]) ) # Non-compliers when not recommended T = C * Z + C0 * (1 - Z) y = true_fn(X) * T + 2 * nu + 5 * (X[:, 3] > 0) + 0.1 * np.random.uniform(0, 1, size=(n,)) return y, T, Z, X def true_heterogeneity_function(X): return 5 * X[:, 0] np.random.seed(123) y, T, Z, X = dgp(1000, 5, true_heterogeneity_function) est = ForestDRIV(discrete_treatment=True, discrete_instrument=True, random_state=42) est.fit(Y=y, T=T, Z=Z, X=X)
>>> est.effect(X[:3]) array([-2.11667..., 6.31903..., -3.65700...]) >>> est.effect_interval(X[:3]) (array([-5.53359..., 2.40420..., -7.14977...]), array([ 1.30025..., 10.23385..., -0.16424...]))
- __init__(*, model_y_xw='auto', model_t_xw='auto', model_z_xw='auto', model_t_xwz='auto', model_tz_xw='auto', fit_cov_directly=True, flexible_model_effect='auto', prel_cate_approach='driv', prel_cv=1, prel_opt_reweighted=True, projection=False, featurizer=None, n_estimators=1000, max_depth=None, min_samples_split=5, min_samples_leaf=5, min_weight_fraction_leaf=0.0, max_features='auto', min_impurity_decrease=0.0, max_samples=0.45, min_balancedness_tol=0.45, honest=True, subforest_size=4, n_jobs=- 1, verbose=0, cov_clip=0.001, opt_reweighted=False, discrete_outcome=False, discrete_instrument=False, discrete_treatment=False, treatment_featurizer=None, 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_y_xw, model_t_xw, ...])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.
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, *, Z[, X, W, sample_weight, ...])Estimate the counterfactual model from data, i.e. estimates function \(\theta(\cdot)\).
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.
refit_final
(*[, inference])Estimate the counterfactual model using a new final model specification but with cached first stage results.
score
(Y, T, Z[, X, W, sample_weight])Score the fitted CATE model on a new data set.
shap_values
(X, *[, feature_names, ...])Shap value for the final stage models (const_marginal_effect)
Attributes
Get an instance of
DoWhyWrapper
to allow other functionalities from dowhy package.feature_importances_
Get the fitted featurizer.
Get the fitted final CATE model.
model_final
model_final_
models_nuisance_
Get the fitted preliminary CATE estimator.
Get the fitted models for \(\E[T | X]\).
Get the fitted models for \(\E[Z | X]\).
Get the fitted models for \(\E[T*Z | X]\).
Get the fitted models for \(\E[Y | X]\).
Get the fitted models for \(\E[Z | X]\).
Get the scores for prel_model_effect model on the out-of-sample training data
Get the scores for t_xw model on the out-of-sample training data
Get the scores for z_xw model on the out-of-sample training data
Get the scores for tz_xw model on the out-of-sample training data
Get the scores for y_xw model on the out-of-sample training data
Get the scores for z_xw model on the out-of-sample training data
original_featurizer
ortho_learner_model_final_
A tuple (prel_theta, Y_res, T_res, Z_res, cov, X, W, Z), of the residuals from the first stage estimation along with the associated X, W and Z.
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
list of str or None
- cate_output_names(output_names=None)
Public interface for getting output names.
To be overriden by estimators that apply transformations the outputs.
- Parameters
output_names (list of str of length Y.shape[1] or None) – The names of the outcomes. If None and the Y passed to fit was a dataframe, it defaults to the column names from the dataframe.
- Returns
output_names – Returns output names.
- Return type
list of str
- 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
list of str
- 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 featurized-T (or T if treatment_featurizer is None) 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 scalar)
- Return type
(d_y, d_f_t) matrix where d_f_t is the dimension of the featurized treatment. If treatment_featurizer is None, d_f_t = d_t.
- 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 featurized treatment on each outcome for each sample X[i]. Note that when Y or featurized-T (or T if treatment_featurizer is None) 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_f_t) matrix or (d_y, d_f_t) matrix if X is None where d_f_t is the dimension of the featurized treatment. If treatment_featurizer is None, d_f_t = d_t.
- 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, *, Z, 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
Z ((n, d_z) matrix) – Instruments 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, optional) – 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 of
BootstrapInference
) and ‘blb’ (for Bootstrap-of-Little-Bags based inference)
- Return type
self
- 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)
)
- 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
- score(Y, T, Z, 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, d_y) matrix or vector of length n) – Outcomes for each sample
T ((n, d_t) matrix or vector of length n) – Treatments for each sample
Z ((n, d_z) matrix) – Instruments 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
- 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
- property dowhy
Get an instance of
DoWhyWrapper
to allow other functionalities from dowhy package. (e.g. causal graph, refutation test, etc.)- 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 model_cate
Get the fitted final CATE model.
- Returns
model_cate – An instance of the model_final object that was fitted after calling fit which corresponds to the constant marginal CATE model.
- Return type
object of type(model_final)
- property models_prel_model_effect
Get the fitted preliminary CATE estimator.
- Returns
prel_model_effect – A nested list of instances of the prel_model_effect 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(prel_model_effect)
- property models_t_xw
Get the fitted models for \(\E[T | X]\).
- Returns
models_t_xw – A nested list of instances of the model_t_xw 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_t_xw)
- property models_t_xwz
Get the fitted models for \(\E[Z | X]\).
- Returns
models_z_xw – A nested list of instances of the model_z_xw 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_z_xw)
- property models_tz_xw
Get the fitted models for \(\E[T*Z | X]\).
- Returns
models_tz_xw – A nested list of instances of the model_tz_xw 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_tz_xw)
- property models_y_xw
Get the fitted models for \(\E[Y | X]\).
- Returns
models_y_xw – A nested list of instances of the model_y_xw 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_y_xw)
- property models_z_xw
Get the fitted models for \(\E[Z | X]\).
- Returns
models_z_xw – A nested list of instances of the model_z_xw 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_z_xw)
- property nuisance_scores_prel_model_effect
Get the scores for prel_model_effect model on the out-of-sample training data
- property nuisance_scores_t_xw
Get the scores for t_xw model on the out-of-sample training data
- property nuisance_scores_t_xwz
Get the scores for z_xw model on the out-of-sample training data
- property nuisance_scores_tz_xw
Get the scores for tz_xw model on the out-of-sample training data
- property nuisance_scores_y_xw
Get the scores for y_xw model on the out-of-sample training data
- property nuisance_scores_z_xw
Get the scores for z_xw model on the out-of-sample training data
- property residuals_
A tuple (prel_theta, Y_res, T_res, Z_res, cov, X, W, Z), of the residuals from the first stage estimation along with the associated X, W and Z. Samples are not guaranteed to be in the same order as the input order.