econml.dml.CausalForestDML¶

class
econml.dml.
CausalForestDML
(*, model_y='auto', model_t='auto', featurizer=None, discrete_treatment=False, categories='auto', cv=2, mc_iters=None, mc_agg='mean', drate=True, n_estimators=100, criterion='mse', max_depth=None, min_samples_split=10, min_samples_leaf=5, min_weight_fraction_leaf=0.0, min_var_fraction_leaf=None, min_var_leaf_on_val=False, max_features='auto', min_impurity_decrease=0.0, max_samples=0.45, min_balancedness_tol=0.45, honest=True, inference=True, fit_intercept=True, subforest_size=4, n_jobs= 1, random_state=None, verbose=0)[source]¶ Bases:
econml.dml.dml._BaseDML
A Causal Forest [cfdml1] combined with double machine learning based residualization of the treatment and outcome variables. It fits a forest that solves the local moment equation problem:
E[ (Y  E[YX, W]  <theta(x), T  E[TX, W]>  beta(x)) (T;1)  X=x] = 0
where E[YX, W] and E[TX, W] are fitted in a first stage in a crossfitting manner.
 Parameters
model_y (estimator or ‘auto’, optional (default is ‘auto’)) – The estimator for fitting the response to the features. Must implement fit and predict methods. If ‘auto’
WeightedLassoCV
/WeightedMultiTaskLassoCV
will be chosen.model_t (estimator or ‘auto’, optional (default is ‘auto’)) – The estimator for fitting the treatment to the features. If estimator, it must implement fit and predict methods; If ‘auto’,
LogisticRegressionCV
will be applied for discrete treatment, andWeightedLassoCV
/WeightedMultiTaskLassoCV
will be applied for continuous treatment.featurizer (transformer, optional, default None) – 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.
discrete_treatment (bool, optional (default is
False
)) – Whether the treatment values should be treated as categorical, rather than continuous, quantitiescategories (‘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, crossvalidation generator or an iterable, optional (Default=2)) – Determines the crossvalidation splitting strategy. Possible inputs for cv are:
None, to use the default 3fold crossvalidation,
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 (default=None)) – The number of times to rerun the first stage models to reduce the variance of the nuisances.
mc_agg ({‘mean’, ‘median’}, optional (default=’mean’)) – How to aggregate the nuisance value for each sample across the mc_iters monte carlo iterations of crossfitting.
drate (bool, default=True) – Whether to calculate doubly robust average treatment effect estimate on training data at fit time. This happens only if discrete_treatment=True. Doubly robust ATE estimation on the training data is not available for continuous treatments.
n_estimators (int, default=100) – Number of trees
criterion ({
"mse"
,"het"
}, default=”mse”) – The function to measure the quality of a split. Supported criteria are"mse"
for the mean squared error in a linear moment estimation tree and"het"
for heterogeneity score.The
"mse"
criterion finds splits that minimize the scoresum_{child} E[(Y  <theta(child), T>  beta(child))^2  X=child] weight(child)
Internally, for the case of more than two treatments or for the case of two treatments with
fit_intercept=True
then this criterion is approximated by computationally simpler variants for computational purposes. In particular, it is replaced by:sum_{child} weight(child) * rho(child).T @ E[(T;1) @ (T;1).T  X in child] @ rho(child)
where:
rho(child) := E[(T;1) @ (T;1).T  X in parent]^{1} * E[(Y  <theta(x), T>  beta(x)) (T;1)  X in child]
This can be thought as a heterogeneity inducing score, but putting more weight on scores with a large minimum eigenvalue of the child jacobian
E[(T;1) @ (T;1).T  X in child]
, which leads to smaller variance of the estimate and stronger identification of the parameters.The “het” criterion finds splits that maximize the pure parameter heterogeneity score
sum_{child} weight(child) * rho(child)[:n_T].T @ rho(child)[:n_T]
This can be thought as an approximation to the ideal heterogeneity score:
weight(left) * weight(right)  theta(left)  theta(right)_2^2 / weight(parent)^2
as outlined in [cfdml1]
max_depth (int, default=None) – 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 or float, default=10) – The minimum number of 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 or float, default=5) – 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
training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression.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.0) – The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided.
min_var_fraction_leaf (None or float in (0, 1], default=None) – A constraint on some proxy of the variation of the treatment vector that should be contained within each leaf as a percentage of the total variance of the treatment vector on the whole sample. This avoids performing splits where either the variance of the treatment is small and hence the local parameter is not well identified and has high variance. The proxy of variance is different for different criterion, primarily for computational efficiency reasons. If
criterion='het'
, then this constraint translates to:for all i in {1, ..., T.shape[1]}: Var(T[i]  X in leaf) > `min_var_fraction_leaf` * Var(T[i])
If
criterion='mse'
, because the criterion stores more information about the leaf for every candidate split, then this constraint imposes further constraints on the pairwise correlations of different coordinates of each treatment, i.e.:for all i neq j: sqrt( Var(T[i]X in leaf) * Var(T[j]X in leaf) * ( 1  rho(T[i], T[j] in leaf)^2 ) ) > `min_var_fraction_leaf` sqrt( Var(T[i]) * Var(T[j]) * (1  rho(T[i], T[j])^2 ) )
where rho(X, Y) is the Pearson correlation coefficient of two random variables X, Y. Thus this constraint also enforces that no two pairs of treatments be very colinear within a leaf. This extra constraint primarily has bite in the case of more than two input treatments and also avoids leafs where the parameter estimate has large variance due to local colinearities of the treatments.
min_var_leaf_on_val (bool, default=False) – Whether the min_var_fraction_leaf constraint should also be enforced to hold on the validation set of the honest split too. If
min_var_leaf=None
then this flag does nothing. Setting this to True should be done with caution, as this partially violates the honesty structure, since the treatment variable of the validation set is used to inform the split structure of the tree. However, this is a benign dependence as it only uses local correlation structure of the treatment T to decide whether a split is feasible.max_features (int, float or {“auto”, “sqrt”, “log2”}, default=None) – 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.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 samples,N_t
is the number of samples at the current node,N_t_L
is the number of samples in the left child, andN_t_R
is the number of 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, 1], 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.
If
inference=True
, then max_samples must either be an integer smaller than n_samples//2 or a float less than or equal to .5.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 each tree should be trained in an honest manner, i.e. the training set is split into two equal sized subsets, the train and the val set. All samples in train are used to create the split structure and all samples in val are used to calculate the value of each node in the tree.
inference (bool, default=True) – Whether inference (i.e. confidence interval construction and uncertainty quantification of the estimates) should be enabled. If
inference=True
, then the estimator uses a bootstrapoflittlebags approach to calculate the covariance of the parameter vector, with am objective Bayesian debiasing correction to ensure that variance quantities are positive.fit_intercept (bool, default=True) – Whether we should fit an intercept nuisance parameter beta(x).
subforest_size (int, default=4,) – The number of trees in each subforest that is used in the bootstrapoflittlebags 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 parallel jobs to be used for parallelism; follows joblib semantics. n_jobs=1 means all available cpu cores. n_jobs=None means no parallelism.
random_state (int, RandomState instance or None, default=None) – Controls the randomness of the estimator. The features are always randomly permuted at each split. When
max_features < n_features
, the algorithm will selectmax_features
at random at each split before finding the best split among them. But the best found split may vary across different runs, even ifmax_features=n_features
. That is the case, if the improvement of the criterion is identical for several splits and one split has to be selected at random. To obtain a deterministic behaviour during fitting,random_state
has to be fixed to an integer.verbose (int, default=0) – Controls the verbosity when fitting and predicting.

ate_
¶ The average constant marginal treatment effect of each treatment for each outcome, averaged over the training data and with a doubly robust correction. Available only when discrete_treatment=True and oob=True.
 Type
ndarray of shape (n_outcomes, n_treatments)

ate_stderr_
¶ The standard error of the ate_ attribute.
 Type
ndarray of shape (n_outcomes, n_treatments)

feature_importances_
¶ The feature importances based on the amount of parameter heterogeneity they create. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total heterogeneity that the feature creates. Each split that the feature was chosen adds:
parent_weight * (left_weight * right_weight) * mean((value_left[k]  value_right[k])**2) / parent_weight**2
to the importance of the feature. Each such quantity is also weighted by the depth of the split. By default splits below max_depth=4 are not used in this calculation and also each split at depth depth, is reweighted by 1 / (1 + depth)**2.0. See the method
feature_importances
for a method that allows one to change these defaults. Type
ndarray of shape (n_features,)
References
 cfdml1(1,2)
Athey, Susan, Julie Tibshirani, and Stefan Wager. “Generalized random forests.” The Annals of Statistics 47.2 (2019): 11481178 https://arxiv.org/pdf/1610.01271.pdf

__init__
(*, model_y='auto', model_t='auto', featurizer=None, discrete_treatment=False, categories='auto', cv=2, mc_iters=None, mc_agg='mean', drate=True, n_estimators=100, criterion='mse', max_depth=None, min_samples_split=10, min_samples_leaf=5, min_weight_fraction_leaf=0.0, min_var_fraction_leaf=None, min_var_leaf_on_val=False, max_features='auto', min_impurity_decrease=0.0, max_samples=0.45, min_balancedness_tol=0.45, honest=True, inference=True, fit_intercept=True, subforest_size=4, n_jobs= 1, random_state=None, verbose=0)[source]¶ Initialize self. See help(type(self)) for accurate signature.
Methods
__init__
(*[, model_y, model_t, featurizer, …])Initialize self.
ate
([X, T0, T1])Calculate the average treatment effect \(E_X[\tau(X, T0, T1)]\).
 returns
ate__inference – Inference results information for the ate_ attribute, which is the average
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.
att_
(*, T) Parameters
T (int) – The index of the treatment for which to get the ATT. It corresponds to the
att__inference
(*, T) Parameters
T (int) – The index of the treatment for which to get the ATT. It corresponds to the
att_stderr_
(*, T) Parameters
T (int) – The index of the treatment for which to get the ATT. It corresponds to the
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.
feature_importances
([max_depth, …])fit
(Y, T[, X, W, sample_weight, groups, …])Estimate the counterfactual model from data, i.e.
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[, X, W])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)
summary
([alpha, value, decimals, …])The summary of coefficient and intercept in the linear model of the constant marginal treatment effect.
tune
(Y, T, *[, X, W, sample_weight, groups, …])Tunes the major hyperparameters of the final stage causal forest based on outofsample Rscore performance.
Attributes
Get an instance of
DoWhyWrapper
to allow other functionalities from dowhy package.featurizer_
Get the fitted final CATE model.
model_final
model_final_
models_nuisance_
Get the fitted models for E[T  X, W].
Get the fitted models for E[Y  X, W].
nuisance_scores_t
nuisance_scores_y
original_featurizer
ortho_learner_model_final_
A tuple (y_res, T_res, X, W), of the residuals from the first stage estimation along with the associated X and W.
rlearner_model_final_
transformer
tunable_params

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 (optional (m, d_x) matrix) – Features for each sample
 Returns
τ – Average treatment effects on each outcome Note that when Y is a vector rather than a 2dimensional array, the result will be a scalar
 Return type
float or (d_y,) array

ate__inference
()[source]¶  Returns
ate__inference – Inference results information for the ate_ attribute, which is the average constant marginal treatment effect of each treatment for each outcome, averaged over the training data and with a doubly robust correction. Available only when discrete_treatment=True and drate=True.
 Return type

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 (optional (m, d_x) matrix) – Features for each sample
T0 (optional (m, d_t) matrix or vector of length m (Default=0)) – Base treatments for each sample
T1 (optional (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.1)¶ 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 (optional (m, d_x) matrix) – Features for each sample
T0 (optional (m, d_t) matrix or vector of length m (Default=0)) – Base treatments for each sample
T1 (optional (m, d_t) matrix or vector of length m (Default=1)) – Target treatments for each sample
alpha (optional float in [0, 1] (Default=0.1)) – The overall level of confidence of the reported interval. The alpha/2, 1alpha/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))
)

att_
(*, T)[source]¶  Parameters
T (int) – The index of the treatment for which to get the ATT. It corresponds to the lexicographic rank of the discrete input treatments.
 Returns
att_ – The average constant marginal treatment effect of each treatment for each outcome, averaged over the training data treated with treatment T and with a doubly robust correction. Singleton dimensions are dropped if input variable was a vector.
 Return type
ndarray (n_y, n_t)

att__inference
(*, T)[source]¶  Parameters
T (int) – The index of the treatment for which to get the ATT. It corresponds to the lexicographic rank of the discrete input treatments.
 Returns
att__inference – Inference results information for the att_ attribute, which is the average constant marginal treatment effect of each treatment for each outcome, averaged over the training data treated with treatment T and with a doubly robust correction. Available only when discrete_treatment=True and oob=True.
 Return type

att_stderr_
(*, T)[source]¶  Parameters
T (int) – The index of the treatment for which to get the ATT. It corresponds to the lexicographic rank of the discrete input treatments.
 Returns
att_stderr_ – The standard error of the corresponding att_
 Return type
ndarray (n_y, n_t)

cate_feature_names
(feature_names=None)¶ Get the output feature names.
 Parameters
feature_names (list of strings 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 constant marginal CATE model is linear. It is the names of the features that are associated with each entry of the
coef_()
parameter. Not available when the featurizer is not None and does not have a method: get_feature_names(feature_names). Otherwise None is returned. Return type
list of strings 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 strings 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 strings

cate_treatment_names
(treatment_names=None)¶ Get treatment names.
If the treatment is discrete, it will return expanded treatment names.
 Parameters
treatment_names (list of strings of length T.shape[1] or None) – 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 strings

const_marginal_ate
(X=None)¶ Calculate the average constant marginal CATE \(E_X[\theta(X)]\).
 Parameters
X (optional (m, d_x) matrix or None (Default=None)) – 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 2dimensional 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 (optional (m, d_x) matrix or None (Default=None)) – 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.1)¶ 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 (optional (m, d_x) matrix or None (Default=None)) – Features for each sample
alpha (optional float in [0, 1] (Default=0.1)) – The overall level of confidence of the reported interval. The alpha/2, 1alpha/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 (optional (m, d_x) matrix or None (Default=None)) – 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 2dimensional 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 (optional (m, d_x) matrix or None (Default=None)) – 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.1)¶ Confidence intervals for the quantities \(\theta(X)\) produced by the model. Available only when
inference
is notNone
, when calling the fit method. Parameters
X (optional (m, d_x) matrix or None (Default=None)) – Features for each sample
alpha (optional float in [0, 1] (Default=0.1)) – The overall level of confidence of the reported interval. The alpha/2, 1alpha/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 (optional (m, d_x) matrix) – Features for each sample
 Returns
τ – Heterogeneous treatment effects on each outcome for each sample Note that when Y is a vector rather than a 2dimensional 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 (optional (m, d_x) matrix) – Features for each sample
T0 (optional (m, d_t) matrix or vector of length m (Default=0)) – Base treatments for each sample
T1 (optional (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.1)¶ 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 (optional (m, d_x) matrix) – Features for each sample
T0 (optional (m, d_t) matrix or vector of length m (Default=0)) – Base treatments for each sample
T1 (optional (m, d_t) matrix or vector of length m (Default=1)) – Target treatments for each sample
alpha (optional float in [0, 1] (Default=0.1)) – The overall level of confidence of the reported interval. The alpha/2, 1alpha/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 functions τ(·,·,·), ∂τ(·,·).
 Parameters
Y ((n × d_y) matrix or vector of length n) – Outcomes for each sample
T ((n × dₜ) matrix or vector of length n) – Treatments for each sample
X ((n × dₓ) matrix) – Features for each sample
W (optional (n × d_w) matrix) – 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 (string,
Inference
instance, or None) – Method for performing inference. This estimator supports ‘bootstrap’ (or an instance ofBootstrapInference
), ‘blb’ or ‘auto’ (for BootstrapofLittleBags based inference)
 Returns
 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 (optional (m, d_x) matrix) – 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 2dimensional 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 (optional (m, d_x) matrix or None (Default=None)) – 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.1)¶ 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 (optional (m, d_x) matrix or None (Default=None)) – Features for each sample
alpha (optional float in [0, 1] (Default=0.1)) – The overall level of confidence of the reported interval. The alpha/2, 1alpha/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\}\). Since this class assumes a linear model, the base treatment is ignored in this calculation.
 Parameters
T ((m, d_t) matrix) – Base treatments for each sample
X (optional (m, d_x) matrix) – 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 2dimensional 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 (optional (m, d_x) matrix or None (Default=None)) – 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.1)¶ 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 (optional (m, d_x) matrix or None (Default=None)) – Features for each sample
alpha (optional float in [0, 1] (Default=0.1)) – The overall level of confidence of the reported interval. The alpha/2, 1alpha/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')[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 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, X=None, W=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
X (optional(n, d_x) matrix or None (Default=None)) – Features for each sample
W (optional(n, d_w) matrix or None (Default=None)) – Controls for each sample
 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)[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 (optional None or list of strings of length X.shape[1] (Default=None)) – The names of input features.
treatment_names (optional None or list (Default=None)) – The name of 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 (optional None or list (Default=None)) – The name of the outcome.
background_samples (int or None, (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
(alpha=0.1, value=0, decimals=3, feature_names=None, treatment_names=None, output_names=None)[source]¶ The summary of coefficient and intercept in the linear model of the constant marginal treatment effect.
 Parameters
alpha (optional float in [0, 1] (default=0.1)) – The overall level of confidence of the reported interval. The alpha/2, 1alpha/2 confidence interval is reported.
value (optinal float (default=0)) – The mean value of the metric you’d like to test under null hypothesis.
decimals (optinal int (default=3)) – Number of decimal places to round each column to.
feature_names (optional list of strings or None (default is None)) – The input of the feature names
treatment_names (optional list of strings or None (default is None)) – The names of the treatments
output_names (optional list of strings or None (default is None)) – 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

tune
(Y, T, *, X=None, W=None, sample_weight=None, groups=None, params='auto')[source]¶ Tunes the major hyperparameters of the final stage causal forest based on outofsample Rscore performance. It trains small forests of size 100 trees on a grid of parameters and tests the out of sample Rscore. After the function is called, then all parameters of self have been set to the optimal hyperparameters found. The estimator however remains unfitted, so you need to call fit afterwards to fit the estimator with the chosen hyperparameters. The list of tunable parameters can be accessed via the property tunable_params.
 Parameters
Y ((n × d_y) matrix or vector of length n) – Outcomes for each sample
T ((n × dₜ) matrix or vector of length n) – Treatments for each sample
X ((n × dₓ) matrix) – Features for each sample
W (optional (n × d_w) matrix) – Controls for each sample
sample_weight (optional (n,) vector) – Weights for each row
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.
params (dict or ‘auto’, optional (default=’auto’)) – A dictionary that contains the grid of hyperparameters to try, i.e. {‘param1’: [value1, value2, …], ‘param2’: [value1, value2, …], …} If params=’auto’, then a default grid is used.
 Returns
self – The tuned causal forest object. This is the same object (not a copy) as the original one, but where all parameters of the object have been set to the best performing parameters from the tuning grid.
 Return type
CausalForestDML 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
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_t
¶ Get the fitted models for E[T  X, W].
 Returns
models_t – A nested list of instances of the model_y 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)

property
models_y
¶ Get the fitted models for E[Y  X, W].
 Returns
models_y – A nested list of instances of the model_y 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)

property
residuals_
¶ A tuple (y_res, T_res, X, W), of the residuals from the first stage estimation along with the associated X and W. Samples are not guaranteed to be in the same order as the input order.