econml.dr.DRLearner

class econml.dr.DRLearner(*, model_propensity='auto', model_regression='auto', model_final=StatsModelsLinearRegression(), discrete_outcome=False, multitask_model_final=False, featurizer=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: _OrthoLearner

CATE estimator that uses doubly-robust correction to account for selection bias between the treatment arms.

The estimator is a special case of an _OrthoLearner estimator, so it follows the two stage process, where a set of nuisance functions are estimated in the first stage in a crossfitting manner and a final stage estimates the CATE model. See the documentation of _OrthoLearner for a description of this two stage process.

In this estimator, the CATE is estimated by using the following estimating equations. If we let:

\[Y_{i, t}^{DR} = E[Y | X_i, W_i, T_i=t] + \frac{Y_i - E[Y | X_i, W_i, T_i=t]}{Pr[T_i=t | X_i, W_i]} \cdot 1\{T_i=t\}\]

Then the following estimating equation holds:

\[E\left[Y_{i, t}^{DR} - Y_{i, 0}^{DR} | X_i\right] = \theta_t(X_i)\]

Thus if we estimate the nuisance functions \(h(X, W, T) = E[Y | X, W, T]\) and \(p_t(X, W)=Pr[T=t | X, W]\) in the first stage, we can estimate the final stage cate for each treatment t, by running a regression, regressing \(Y_{i, t}^{DR} - Y_{i, 0}^{DR}\) on \(X_i\).

The problem of estimating the nuisance function \(p\) is a simple multi-class classification problem of predicting the label \(T\) from \(X, W\). The DRLearner class takes as input the parameter model_propensity, which is an arbitrary scikit-learn classifier, that is internally used to solve this classification problem.

The second nuisance function \(h\) is a simple regression problem and the DRLearner class takes as input the parameter model_regressor, which is an arbitrary scikit-learn regressor that is internally used to solve this regression problem.

The final stage is multi-task regression problem with outcomes the labels \(Y_{i, t}^{DR} - Y_{i, 0}^{DR}\) for each non-baseline treatment t. The DRLearner takes as input parameter model_final, which is any scikit-learn regressor that is internally used to solve this multi-task regresion problem. If the parameter multitask_model_final is False, then this model is assumed to be a mono-task regressor, and separate clones of it are used to solve each regression target separately.

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 models

    • Otherwise, 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 models

    • Otherwise, 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_final – estimator for the final cate model. Trained on regressing the doubly robust potential outcomes on (features X).

    • If X is None, then the fit method of model_final should be able to handle X=None.

    • If featurizer is not None and X is not None, then it is trained on the outcome of featurizer.fit_transform(X).

    • If multitask_model_final is True, then this model must support multitasking and it is trained by regressing all doubly robust target outcomes on (featurized) features simultanteously.

    • The output of the predict(X) of the trained model will contain the CATEs for each treatment compared to baseline treatment (lexicographically smallest). If multitask_model_final is False, it is assumed to be a mono-task model and a separate clone of the model is trained for each outcome. Then predict(X) of the t-th clone will be the CATE of the t-th lexicographically ordered treatment compared to the baseline.

  • discrete_outcome (bool, default False) – Whether the outcome should be treated as binary

  • multitask_model_final (bool, default False) – Whether the model_final should be treated as a multi-task model. See description of model_final.

  • 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.

  • 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.

    • CV splitter

    • 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) – 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 the RandomState instance used by np.random.

  • allow_missing (bool) – Whether to allow missing values in X, W. If True, will need to supply model_propensity, model_regression, and model_final that can handle missing values.

  • use_ray (bool, default False) – Whether to use Ray to parallelize the cross-fitting 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

np.random.seed(123)
X = np.random.normal(size=(1000, 3))
T = np.random.binomial(2, scipy.special.expit(X[:, 0]))
sigma = 0.001
y = (1 + .5*X[:, 0]) * T + X[:, 0] + np.random.normal(0, sigma, size=(1000,))
est = DRLearner()
est.fit(y, T, X=X, W=None)
>>> est.const_marginal_effect(X[:2])
array([[0.516888..., 0.995747...],
       [0.356386..., 0.671889...]])
>>> est.effect(X[:2], T0=0, T1=1)
array([0.516888..., 0.356386...])
>>> est.score_
np.float64(2.845660...)
>>> est.score(y, T, X=X)
np.float64(1.062668...)
>>> est.model_cate(T=1).coef_
array([ 0.447146..., -0.001025...,  0.018984...])
>>> est.model_cate(T=2).coef_
array([ 0.925064..., -0.012351...,  0.033480...])
>>> est.cate_feature_names()
['X0', 'X1', 'X2']

Beyond default models:

from sklearn.linear_model import LassoCV
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from econml.dr import DRLearner

np.random.seed(123)
X = np.random.normal(size=(1000, 3))
T = np.random.binomial(2, scipy.special.expit(X[:, 0]))
sigma = 0.01
y = (1 + .5*X[:, 0]) * T + X[:, 0] + np.random.normal(0, sigma, size=(1000,))
est = DRLearner(model_propensity=RandomForestClassifier(n_estimators=100, min_samples_leaf=10),
                model_regression=RandomForestRegressor(n_estimators=100, min_samples_leaf=10),
                model_final=LassoCV(cv=3),
                featurizer=None)
est.fit(y, T, X=X, W=None)
>>> est.score_
np.float64(1.73...)
>>> est.const_marginal_effect(X[:3])
array([[0.68..., 1.10...],
       [0.56..., 0.79... ],
       [0.34..., 0.10... ]])
>>> est.model_cate(T=2).coef_
array([0.74..., 0.        , 0.        ])
>>> est.model_cate(T=2).intercept_
np.float64(1.9...)
>>> est.model_cate(T=1).coef_
array([0.24..., 0.00..., 0.        ])
>>> est.model_cate(T=1).intercept_
np.float64(0.94...)
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:

float

__init__(*, model_propensity='auto', model_regression='auto', model_final=StatsModelsLinearRegression(), discrete_outcome=False, multitask_model_final=False, featurizer=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.

const_marginal_ate([X])

Calculate the average constant marginal CATE \(E_X[\theta(X)]\).

const_marginal_ate_inference([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.

const_marginal_effect([X])

Calculate the constant marginal CATE \(\theta(·)\).

const_marginal_effect_inference([X])

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, ...])

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.

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).

Attributes

dowhy

Get a DoWhyWrapper to enable functionality (e.g. causal graph, refutation test, etc.) from dowhy.

featurizer_

Get the fitted featurizer.

fitted_models_final

model_final_

models_nuisance_

models_propensity

Get the fitted propensity models.

models_regression

Get the fitted regression models.

multitask_model_cate

Get the fitted final CATE model.

nuisance_scores_propensity

Get the score for the propensity model on out-of-sample training data.

nuisance_scores_regression

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 not None, 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:

object

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 not None, 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 of ate(X, T0, T1)) )

cate_feature_names(feature_names=None)[source]

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)[source]

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 not None, 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:

object

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 not None, 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 of const_marginal_ate(X) )

const_marginal_effect(X=None)[source]

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 not None, 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:

object

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 not None, 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 of const_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 not None, 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:

object

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 not None, 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 of effect(X, T0, T1)) )

fit(Y, T, *, X=None, W=None, sample_weight=None, freq_weight=None, sample_var=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, optional) – Individual weights for each sample. If None, it assumes equal weight.

  • freq_weight ((n,) array_like of int, optional) – Weight for the observation. Observation i is treated as the mean outcome of freq_weight[i] independent observations. When sample_var is not None, this should be provided.

  • sample_var ((n,) nd array_like, optional) – Variance of the outcome(s) of the original freq_weight[i] observations that were used to compute the mean outcome represented by observation i.

  • 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).

Returns:

self

Return type:

DRLearner instance

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 not None, 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:

object

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 not None, 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 of marginal_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 not None, 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:

object

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 not None, 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 of marginal_effect(T, X) )

model_cate(T=1)[source]

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:

object of type(model_final)

refit_final(*, inference='auto')[source]

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 with cache_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:

object

robustness_value(T, null_hypothesis=0, alpha=0.05, interval_type='ci')[source]

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:

float

score(Y, T, X=None, W=None, sample_weight=None)[source]

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:

float

sensitivity_interval(T, alpha=0.05, c_y=0.05, c_t=0.05, rho=1.0, interval_type='ci')[source]

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)[source]

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)[source]

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 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.