X_train – (np.ndarray), training subsample of feature matrix, (n_train_sample, n_features)
X_test – (np.ndarray), test subsample of feature matrix, (n_train_sample, n_features)
inbag – (ndarray, optional),
The inbag matrix that fit the data. If set to None (default) it
will be inferred from the forest. However, this only works for trees
for which bootstrapping was set to True. That is, if sampling was
done with replacement. Otherwise, users need to provide their own
inbag matrix.
calibrate – (boolean, optional)
Whether to apply calibration to mitigate Monte Carlo noise.
Some variance estimates may be negative due to Monte Carlo effects if
the number of trees in the forest is too small. To use calibration,
Default: True
memory_constrained – (boolean, optional)
Whether or not there is a restriction on memory. If False, it is
assumed that a ndarray of shape (n_train_sample,n_test_sample) fits
in main memory. Setting to True can actually provide a speedup if
memory_limit is tuned to the optimal range.
memory_limit – (int, optional)
An upper bound for how much memory the intermediate matrices will take
up in Megabytes. This must be provided if memory_constrained=True.
Returns:
(np.ndarray), An array with the unbiased sampling variance for a RandomForest object.
Note
This method delegates to forestci (forest-confidence-interval), which
calls scikit-learn’s private _get_n_samples_bootstrap and
_generate_sample_indices with their pre-1.9 signatures. Under
scikit-learn >= 1.9 those helpers require an extra sample_weight
argument, so forestci (<= 0.7) would raise TypeError here. As a
temporary measure this call runs inside _forestci_sklearn19_compat(),
which patches those helpers to pass sample_weight=None (the pre-1.9
uniform-bootstrap default, so results are unchanged), pending the upstream
fix (forest-confidence-interval#122) and a forestci pin bump. The shim
is not thread-safe (see its docstring). See
https://github.com/uber/causalml/issues/906.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
with_outcomes (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for with_outcomes parameter in predict.
Configure whether metadata should be requested to be passed to the score method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to score.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.
A Causal Tree regressor class.
The Causal Tree is a decision tree regressor with a split criteria for treatment effects.
Details are available at Athey and Imbens (2015).
Run a pool of bootstraps
:param X: a feature matrix
:type X: np.ndarray
:param treatment: a treatment vector
:type treatment: np.ndarray
:param y: an outcome vector
:type y: np.ndarray
:param n_bootstraps: number of bootstrap iterations
:type n_bootstraps: int
:param bootstrap_size: number of samples per bootstrap
:type bootstrap_size: int
:param n_jobs: number of processes
:type n_jobs: int
:param verbose: whether to output progress logs
:type verbose: bool
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
check_input (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for check_input parameter in fit.
prepare_data (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for prepare_data parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
check_input (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for check_input parameter in predict.
with_outcomes (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for with_outcomes parameter in predict.
Configure whether metadata should be requested to be passed to the score method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to score.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.
Kernel-backed drop-in for the historical Cython
UpliftRandomForestClassifier (issue #955 switchover). The legacy
constructor names and defaults are preserved: evaluationFunction selects
the split criterion, max_features defaults to 10 (clamped to the
feature count, as the legacy forest did), and the fitted trees are exposed as
uplift_forest. predict returns the per-treatment uplift deltas
(full_output=True returns the full frame). Bags kernel-backed uplift
trees on scikit-learn’s ForestRegressor (see
_KernelUpliftRandomForestClassifier).
early_stopping_eval_diff_scale and fit’s X_val / treatment_val
/ y_val are accepted for backward compatibility but ignored: validation-set
early stopping is not implemented on the kernel trees.
n_jobs defaults to None (one worker). Peak memory during fit
grows roughly in proportion to the number of workers, since each concurrent
tree fit holds its own working set; see
_KernelUpliftRandomForestClassifier for measurements. Results are
unaffected by n_jobs.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
X_val (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for X_val parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
treatment_val (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment_val parameter in fit.
y_val (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for y_val parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
full_output (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for full_output parameter in predict.
Configure whether metadata should be requested to be passed to the score method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to score.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.
Kernel-backed drop-in for the historical Cython UpliftTreeClassifier
(issue #955 switchover). The legacy constructor names, defaults, and
predict semantics are preserved: evaluationFunction selects the split
criterion (KL / ED / Chi / CTS / DDP / IT / CIT /
IDDP); predict returns per-group P(Y=1|T=g) including the control
column; fill re-annotates the fitted tree with new data. The tree is
grown on the shared _tree Cython kernel (see
_KernelUpliftTreeClassifier).
early_stopping_eval_diff_scale and fit’s X_val / treatment_val
/ y_val are accepted for backward compatibility but ignored: validation-set
early stopping is not implemented on the kernel tree.
Non-negative normalized feature importances (sum to 1).
The kernel’s raw importances can be signed (an uplift split gain is not a
monotone impurity decrease); the legacy contract exposes non-negative
importances, so magnitudes are taken and renormalized.
Re-estimate leaf probabilities and node counts on new data.
Routes (X,treatment,y) through the fitted tree and overwrites each
leaf’s per-group P(Y=1|T=g) and every node’s per-group counts from
the supplied data (typically a validation set) using the existing group
encoding – mirroring the legacy UpliftTreeClassifier.fill used to
re-annotate the plotted tree. Returns self.
Per-group P(Y=1|T=g) for each row (control in column 0).
Preserves the historical UpliftTreeClassifier.predict return shape
(n_samples,n_groups); a leaf with no samples of an otherwise-present
group yields a NaN rate under min_samples_treatment=0, which is
zero-filled to match the legacy uplift_classification_results.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
X_val (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for X_val parameter in fit.
check_input (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for check_input parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
treatment_val (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment_val parameter in fit.
y_val (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for y_val parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
check_input (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for check_input parameter in predict.
Create distplot for tree leaves values
:param tree: (CausalTreeRegressor), Tree object
:param title: (str), plot title
:param figsize: (tuple), figure size
:param fontsize: (int), title font size
Predict treatment effects (classifier variant — uses predict_proba for outcomes).
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method.
treatment (np.array, pd.Series, or pl.Series, optional) – a treatment vector. Used for computing
classification metrics when y is also provided.
y (np.array, pd.Series, or pl.Series, optional) – an outcome vector. Used for computing
classification metrics when treatment is also provided.
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1). Currently not used in prediction but kept for API consistency.
return_components (bool, optional) – whether to return outcome probabilities for treatment and control
groups separately. Defaults to False.
verbose (bool, optional) – whether to output progress logs. Defaults to True.
Returns:
Predictions of treatment effects.
If return_components is True, also returns:
dict: Predicted probabilities for the control group (yhat_cs).
dict: Predicted probabilities for the treatment group (yhat_ts).
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
seed (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for seed parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
bootstrap(X, treatment, y, p=None, size=10000, rng=None, seed=None)[source]
Runs a single bootstrap with optional deterministic cross-fit seed.
Parameters:
X (np.matrix, np.array, pd.DataFrame, or pl.DataFrame) – a feature matrix.
Resampled natively via filter_index().
treatment (np.array) – a treatment vector (numpy)
y (np.array) – an outcome vector (numpy)
p (dict, optional) – a dict of {treatment group: propensity scores (numpy)}
size (int, optional) – number of samples to draw with replacement
rng (np.random.Generator, optional) – random number generator for
deterministic resampling
seed (int, optional) – random seed for cross-fitting within the
resampled fit() call
Returns:
Predictions of treatment effects on the full X
from a model trained on the resampled subset.
Return type:
(numpy.ndarray)
estimate_ate(X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000, seed=None, pretrain=False)[source]
Estimate the Average Treatment Effect (ATE).
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
bootstrap_ci (bool) – whether run bootstrap for confidence intervals
n_bootstraps (int) – number of bootstrap iterations
bootstrap_size (int) – number of samples per bootstrap
seed (int) – random seed for cross-fitting
pretrain (bool) – whether a model has been fit, default False.
Returns:
The mean and confidence interval (LB, UB) of the ATE estimate.
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method; the
feature matrix is otherwise kept in its native format throughout,
including the KFold partitions (sliced via filter_index()).
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
seed (int) – random seed for cross-fitting
fit_predict(X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True, seed=None)[source]
Fit the treatment effect and outcome models of the DR learner and predict treatment effects.
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
return_ci (bool) – whether to return confidence intervals
n_bootstraps (int) – number of bootstrap iterations
bootstrap_size (int) – number of samples per bootstrap
return_components (bool, optional) – whether to return outcome for treatment and control seperately
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
seed (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for seed parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
seed (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for seed parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
fit(X, treatment, y, p=None, sample_weight=None, verbose=True)[source]
Fit the R-learner classifier (uses predict_proba for outcome estimates).
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method.
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
sample_weight (np.array, pd.Series, or pl.Series, optional) – an array of sample weights indicating the
weight of each observation for effect_learner. If None, it assumes equal weight.
verbose (bool, optional) – whether to output progress logs
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix
treatment (np.array, pd.Series, or pl.Series) – only needed when pretrain=False, a treatment vector
y (np.array, pd.Series, or pl.Series) – only needed when pretrain=False, an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
sample_weight (np.array, pd.Series, or pl.Series, optional) – an array of sample weights indicating the
weight of each observation for effect_learner. If None, it assumes equal weight.
bootstrap_ci (bool) – whether run bootstrap for confidence intervals
n_bootstraps (int) – number of bootstrap iterations
bootstrap_size (int) – number of samples per bootstrap
pretrain (bool) – whether a model has been fit, default False.
Returns:
The mean and confidence interval (LB, UB) of the ATE estimate.
fit(X, treatment, y, p=None, sample_weight=None, verbose=True)[source]
Fit the treatment effect and outcome models of the R learner.
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method; the
feature matrix is otherwise kept in its native format throughout,
including the call to cross_val_predict (scikit-learn >= 1.6
accepts pandas and Polars DataFrames natively).
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
sample_weight (np.array, pd.Series, or pl.Series, optional) – an array of sample weights indicating the
weight of each observation for effect_learner. If None, it assumes equal weight.
verbose (bool, optional) – whether to output progress logs
fit_predict(X, treatment, y, p=None, sample_weight=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True)[source]
Fit the R learner and predict treatment effects.
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
sample_weight (np.array, pd.Series, or pl.Series, optional) – an array of sample weights indicating the
weight of each observation for effect_learner. If None, it assumes equal weight.
return_ci (bool) – whether to return confidence intervals
n_bootstraps (int) – number of bootstrap iterations
bootstrap_size (int) – number of samples per bootstrap
return_components (bool, optional) – whether to return the nuisance
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method; the
feature matrix is otherwise kept in its native format throughout.
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
fit_predict(X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True)[source]
Fit the inference model of the S learner and predict treatment effects.
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
return_ci (bool, optional) – whether to return confidence intervals
n_bootstraps (int, optional) – number of bootstrap iterations
bootstrap_size (int, optional) – number of samples per bootstrap
return_components (bool, optional) – whether to return outcome for treatment and control seperately
verbose (bool, optional) – whether to output progress logs
Returns:
Predictions of treatment effects. Output dim: [n_samples, n_treatment].
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
bootstrap_size (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for bootstrap_size parameter in fit.
n_bootstraps (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for n_bootstraps parameter in fit.
n_jobs (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for n_jobs parameter in fit.
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
random_state (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for random_state parameter in fit.
store_bootstraps (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for store_bootstraps parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_ci (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_ci parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
estimate_ate(X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000, pretrain=False)[source]
Estimate the Average Treatment Effect (ATE).
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
bootstrap_ci (bool) – whether to return confidence intervals
n_bootstraps (int) – number of bootstrap iterations
bootstrap_size (int) – number of samples per bootstrap
pretrain (bool) – whether a model has been fit, default False.
Returns:
The mean and confidence interval (LB, UB) of the ATE estimate.
fit(X, treatment, y, p=None, store_bootstraps=False, n_bootstraps=200, bootstrap_size=10000, random_state=None, n_jobs=1)[source]
Fit the inference model.
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method; the
feature matrix is otherwise kept in its native format throughout.
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p – unused, kept for API consistency
store_bootstraps (bool, optional) – if True, trains a bootstrap ensemble
during fit and stores it in self.bootstrap_models_ for post-fit CI
estimation via predict(return_ci=True). Default: False.
n_bootstraps (int, optional) – number of bootstrap iterations. Default: 200.
n_jobs (int, optional) – number of parallel jobs for bootstrap fitting.
-1 uses all available cores. Default: 1.
bootstrap_size (int, optional) – number of samples per bootstrap. Default: 10000.
random_state (int, optional) – random seed for reproducible bootstrap sampling.
fit_predict(X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True)[source]
Fit the inference model of the T learner and predict treatment effects.
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
return_ci (bool) – whether to return confidence intervals
n_bootstraps (int) – number of bootstrap iterations
bootstrap_size (int) – number of samples per bootstrap
return_components (bool, optional) – whether to return outcome for treatment and control seperately
verbose (str) – whether to output progress logs
Returns:
Predictions of treatment effects. Output dim: [n_samples, n_treatment].
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method.
treatment (np.array, pd.Series, or pl.Series, optional) – a treatment vector
y (np.array, pd.Series, or pl.Series, optional) – an outcome vector
return_components (bool, optional) – whether to return outcome for treatment and control seperately
verbose (bool, optional) – whether to output progress logs
return_ci (bool, optional) – whether to return confidence intervals
using the stored bootstrap ensemble. Requires fit() to have been
called with store_bootstraps=True.
Returns:
Predictions of treatment effects. If return_ci=True,
returns (te, te_lower, te_upper) each of shape [n_samples, n_treatment].
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
bootstrap_size (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for bootstrap_size parameter in fit.
n_bootstraps (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for n_bootstraps parameter in fit.
n_jobs (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for n_jobs parameter in fit.
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
random_state (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for random_state parameter in fit.
store_bootstraps (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for store_bootstraps parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_ci (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_ci parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
bootstrap_size (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for bootstrap_size parameter in fit.
n_bootstraps (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for n_bootstraps parameter in fit.
n_jobs (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for n_jobs parameter in fit.
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
random_state (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for random_state parameter in fit.
store_bootstraps (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for store_bootstraps parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_ci (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_ci parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method; the
feature matrix is otherwise kept in its native format throughout.
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in
the single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method.
treatment (np.array, pd.Series, or pl.Series, optional) – a treatment vector
y (np.array, pd.Series, or pl.Series, optional) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in
the single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
return_components (bool, optional) – whether to return outcome for treatment and control seperately
verbose (bool, optional) – whether to output progress logs
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
estimate_ate(X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000, pretrain=False)[source]
Estimate the Average Treatment Effect (ATE).
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in
the single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
bootstrap_ci (bool) – whether run bootstrap for confidence intervals
n_bootstraps (int) – number of bootstrap iterations
bootstrap_size (int) – number of samples per bootstrap
pretrain (bool) – whether a model has been fit, default False.
Returns:
The mean and confidence interval (LB, UB) of the ATE estimate.
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method; the
feature matrix is otherwise kept in its native format throughout.
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in
the single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
fit_predict(X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True)[source]
Fit the X-learner and predict treatment effects.
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in
the single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
return_ci (bool) – whether to return confidence intervals
n_bootstraps (int) – number of bootstrap iterations
bootstrap_size (int) – number of samples per bootstrap
return_components (bool, optional) – whether to return outcome for treatment and control seperately
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method.
treatment (np.array, pd.Series, or pl.Series, optional) – a treatment vector
y (np.array, pd.Series, or pl.Series, optional) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in
the single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
return_components (bool, optional) – whether to return outcome for treatment and control seperately
verbose (bool, optional) – whether to output progress logs
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
bootstrap_size (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for bootstrap_size parameter in fit.
n_bootstraps (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for n_bootstraps parameter in fit.
n_jobs (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for n_jobs parameter in fit.
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
random_state (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for random_state parameter in fit.
store_bootstraps (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for store_bootstraps parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_ci (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_ci parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
Ref: Gruber, S., & Van Der Laan, M. J. (2009). Targeted maximum likelihood estimation: A gentle introduction.
estimate_ate(X, treatment, y, p, segment=None, return_ci=False)[source]
Estimate the Average Treatment Effect (ATE).
Parameters:
X (np.matrix or np.array or pd.Dataframe) – a feature matrix
treatment (np.array or pd.Series) – a treatment vector
y (np.array or pd.Series) – an outcome vector
p (np.ndarray or pd.Series or dict) – an array of propensity scores of float (0,1) in the single-treatment
case; or, a dictionary of treatment groups that map to propensity vectors of float (0,1)
segment (np.array, optional) – An optional segment vector of int. If given, the ATE and its CI will be
estimated for each segment.
return_ci (bool, optional) – Whether to return confidence intervals
Returns:
The ATE and its confidence interval (LB, UB) for each treatment, t and segment, s
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
seed (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for seed parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
The outcome model is an XGBClassifier (its predict_proba drives the
outcome cross-fit) and the effect model is an XGBRegressor. Every
constructor argument is stored verbatim (scikit-learn convention) so that
get_params() / clone() work correctly; the XGBoost models are
constructed in fit().
fit(X, treatment, y, p=None, sample_weight=None, verbose=True)[source]
Build the XGBoost models, then fit as an R-learner classifier.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
Stores every constructor argument verbatim (scikit-learn convention) so
that get_params() / clone() work correctly. All XGBRegressor
construction is deferred to fit().
Additional XGBoost keyword arguments (e.g. max_depth, learning_rate)
are accepted via **xgb_kwargs and stored verbatim as self.xgb_kwargs,
so that get_params() surfaces them and clone() round-trips them
correctly.
fit(X, treatment, y, p=None, sample_weight=None, verbose=True)[source]
Fit using early-stopping XGBoost R-learner.
Parameters:
X (np.matrix, np.array, pd.DataFrame, pl.DataFrame, or pl.LazyFrame) – a feature matrix.
A pl.LazyFrame is collected once at the start of this method.
treatment (np.array, pd.Series, or pl.Series) – a treatment vector
y (np.array, pd.Series, or pl.Series) – an outcome vector
p (np.ndarray, pd.Series, pl.Series, or dict, optional) – an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of
float (0,1); if None will run ElasticNetPropensityModel() to generate the propensity scores.
sample_weight (np.array, pd.Series, or pl.Series, optional) – an array of sample weights indicating the
weight of each observation for effect_learner. If None, it assumes equal weight.
verbose (bool, optional) – whether to output progress logs
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
Stores XGBoost hyperparameters verbatim (scikit-learn convention) so that
get_params() / clone() work correctly; the XGBClassifier models
are constructed in fit().
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_ci (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_ci parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
Configure whether metadata should be requested to be passed to the fit method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to fit.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
bootstrap_size (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for bootstrap_size parameter in fit.
n_bootstraps (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for n_bootstraps parameter in fit.
n_jobs (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for n_jobs parameter in fit.
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in fit.
random_state (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for random_state parameter in fit.
store_bootstraps (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for store_bootstraps parameter in fit.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in fit.
Configure whether metadata should be requested to be passed to the predict method.
Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with enable_metadata_routing=True (see sklearn.set_config()).
Please check the User Guide on how the routing
mechanism works.
The options for each parameter are:
True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.
False: metadata is not requested and the meta-estimator will not pass it to predict.
None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (sklearn.utils.metadata_routing.UNCHANGED) retains the
existing request. This allows you to change the request for some
parameters and not others.
Added in version 1.3.
Parameters:
p (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for p parameter in predict.
return_ci (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_ci parameter in predict.
return_components (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_components parameter in predict.
treatment (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for treatment parameter in predict.
verbose (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for verbose parameter in predict.
Estimate the Average Treatment Effect (ATE) for compliers.
Parameters:
X (np.matrix or np.array or pd.Dataframe) – a feature matrix
assignment (np.array or pd.Series) – an assignment vector. The assignment is the
instrumental variable that does not depend on unknown confounders. The assignment status
influences treatment in a monotonic way, i.e. one can only be more likely to take the
treatment if assigned.
treatment (np.array or pd.Series) – a treatment vector
y (np.array or pd.Series) – an outcome vector
p (2-tuple of np.ndarray or pd.Series or dict, optional) – The first (second) element corresponds to
unassigned (assigned) units. Each is an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of float
(0,1). If None will run ElasticNetPropensityModel() to generate the propensity scores.
pZ (np.array or pd.Series, optional) – an array of assignment probability of float (0,1); if None
will run ElasticNetPropensityModel() to generate the assignment probability score.
bootstrap_ci (bool) – whether run bootstrap for confidence intervals
n_bootstraps (int) – number of bootstrap iterations
bootstrap_size (int) – number of samples per bootstrap
seed (int) – random seed for cross-fitting
Returns:
The mean and confidence interval (LB, UB) of the ATE estimate.
fit(X, assignment, treatment, y, p=None, pZ=None, seed=None, calibrate=True)[source]
Fit the inference model.
Parameters:
X (np.matrix or np.array or pd.Dataframe) – a feature matrix
assignment (np.array or pd.Series) – a (0,1)-valued assignment vector. The assignment is the
instrumental variable that does not depend on unknown confounders. The assignment status
influences treatment in a monotonic way, i.e. one can only be more likely to take the
treatment if assigned.
treatment (np.array or pd.Series) – a treatment vector
y (np.array or pd.Series) – an outcome vector
p (2-tuple of np.ndarray or pd.Series or dict, optional) – The first (second) element corresponds to
unassigned (assigned) units. Each is an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of float
(0,1). If None will run ElasticNetPropensityModel() to generate the propensity scores.
pZ (np.array or pd.Series, optional) – an array of assignment probability of float (0,1); if None
will run ElasticNetPropensityModel() to generate the assignment probability score.
Fit the treatment effect and outcome models of the R learner and predict treatment effects.
Parameters:
X (np.matrix or np.array or pd.Dataframe) – a feature matrix
assignment (np.array or pd.Series) – a (0,1)-valued assignment vector. The assignment is the
instrumental variable that does not depend on unknown confounders. The assignment status
influences treatment in a monotonic way, i.e. one can only be more likely to take the
treatment if assigned.
treatment (np.array or pd.Series) – a treatment vector
y (np.array or pd.Series) – an outcome vector
p (2-tuple of np.ndarray or pd.Series or dict, optional) – The first (second) element corresponds to
unassigned (assigned) units. Each is an array of propensity scores of float (0,1) in the
single-treatment case; or, a dictionary of treatment groups that map to propensity vectors of float
(0,1). If None will run ElasticNetPropensityModel() to generate the propensity scores.
pZ (np.array or pd.Series, optional) – an array of assignment probability of float (0,1); if None
will run ElasticNetPropensityModel() to generate the assignment probability score.
return_ci (bool) – whether to return confidence intervals
n_bootstraps (int) – number of bootstrap iterations
bootstrap_size (int) – number of samples per bootstrap
return_components (bool, optional) – whether to return outcome for treatment and control seperately
verbose (str) – whether to output progress logs
seed (int) – random seed for cross-fitting
Returns:
Predictions of treatment effects for compliers, , i.e. those individuals
who take the treatment only if they are assigned. Output dim: [n_samples, n_treatment]
If return_ci, returns CATE [n_samples, n_treatment], LB [n_samples, n_treatment],
UB [n_samples, n_treatment]
Builds a model (using X to predict estimated/actual tau), and then calculates feature importances
based on a specified method.
Currently supported methods are:
auto (calculates importance based on estimator’s default implementation of feature importance;
estimator must be tree-based)
Note: if none provided, it uses lightgbm’s LGBMRegressor as estimator, and “gain” as
importance type
permutation (calculates importance based on mean decrease in accuracy when a feature column is permuted;
estimator can be any form)
Hint: for permutation, downsample data for better performance especially if X.shape[1] is large
Parameters:
X (np.matrix or np.array or pd.Dataframe) – a feature matrix
tau (np.array) – a treatment effect vector (estimated/actual)
model_tau_feature (sklearn/lightgbm/xgboost model object) – an unfitted model object
features (np.array) – list/array of feature names. If None, an enumerated list will be used
method (str) – auto, permutation
normalize (bool) – normalize by sum of importances if method=auto (defaults to True)
test_size (float/int) – if float, represents the proportion of the dataset to include in the test split.
If int, represents the absolute number of test samples (used for estimating
permutation importance)
random_state (int/RandomState instance/None) – random state used in permutation importance estimation
Builds a model (using X to predict estimated/actual tau), and then calculates shapley values.
:param X: a feature matrix
:type X: np.matrix or np.array or pd.Dataframe
:param tau: a treatment effect vector (estimated/actual)
:type tau: np.array
:param model_tau_feature: an unfitted model object
:type model_tau_feature: sklearn/lightgbm/xgboost model object
:param features: list/array of feature names. If None, an enumerated list will be used.
:type features: optional, np.array
Builds a model (using X to predict estimated/actual tau), and then plots feature importances
based on a specified method.
Currently supported methods are:
auto (calculates importance based on estimator’s default implementation of feature importance;
estimator must be tree-based)
Note: if none provided, it uses lightgbm’s LGBMRegressor as estimator, and “gain” as
importance type
permutation (calculates importance based on mean decrease in accuracy when a feature column is permuted;
estimator can be any form)
Hint: for permutation, downsample data for better performance especially if X.shape[1] is large
Parameters:
X (np.matrix or np.array or pd.Dataframe) – a feature matrix
tau (np.array) – a treatment effect vector (estimated/actual)
model_tau_feature (sklearn/lightgbm/xgboost model object) – an unfitted model object
features (optional, np.array) – list/array of feature names. If None, an enumerated list will be used
method (str) – auto, permutation
normalize (bool) – normalize by sum of importances if method=auto (defaults to True)
test_size (float/int) – if float, represents the proportion of the dataset to include in the test split.
If int, represents the absolute number of test samples (used for estimating
permutation importance)
random_state (int/RandomState instance/None) – random state used in permutation importance estimation
Plots dependency of shapley values for a specified feature, colored by an interaction feature.
If shapley values have been pre-computed, pass it through the shap_dict parameter.
If shap_dict is not provided, this builds a new model (using X to predict estimated/actual tau),
and then calculates shapley values.
This plots the value of the feature on the x-axis and the SHAP value of the same feature
on the y-axis. This shows how the model depends on the given feature, and is like a
richer extension of the classical partial dependence plots. Vertical dispersion of the
data points represents interaction effects.
Parameters:
treatment_group (str or int) – name of treatment group to create dependency plot on
feature_idx (str or int) – feature index / name to create dependency plot on
X (np.matrix or np.array or pd.Dataframe) – a feature matrix
tau (np.array) – a treatment effect vector (estimated/actual)
model_tau_feature (sklearn/lightgbm/xgboost model object) – an unfitted model object
features (optional, np.array) – list/array of feature names. If None, an enumerated list will be used.
shap_dict (optional, dict) – a dict of shapley value matrices. If None, shap_dict will be computed.
interaction_idx (optional, str or int) – feature index / name used in coloring scheme as interaction feature.
If “auto” then shap.common.approximate_interactions is used to pick what seems to be the
strongest interaction (note that to find to true strongest interaction you need to compute
the SHAP interaction values).
If shapley values have been pre-computed, pass it through the shap_dict parameter.
If shap_dict is not provided, this builds a new model (using X to predict estimated/actual tau),
and then calculates shapley values.
Parameters:
X (np.matrix or np.array or pd.Dataframe) – a feature matrix. Required if shap_dict is None.
tau (np.array) – a treatment effect vector (estimated/actual)
model_tau_feature (sklearn/lightgbm/xgboost model object) – an unfitted model object
features (optional, np.array) – list/array of feature names. If None, an enumerated list will be used.
shap_dict (optional, dict) – a dict of shapley value matrices. If None, shap_dict will be computed.
The organic conversion rate in the population without an intervention.
If None, the organic conversion rate is obtained from tne control group.
NB: The organic conversion in the control group is not always the same
as the organic conversion rate without treatment.
data (DataFrame) – A pandas DataFrame containing the features, treatment assignment
indicator and the outcome of interest.
treatment (string) – A string corresponding to the name of the treatment column. The
assumed coding in the column is 1 for treatment and 0 for control.
outcome (string) – A string corresponding to the name of the outcome column. The assumed
coding in the column is 1 for conversion and 0 for no conversion.
treatment (array, shape = (num_samples, )) – An array of treatment group indicator values.
control_name (string) – The name of the control condition as a string. Must be contained in the treatment array.
treatment_names (list, length = cate.shape[1]) – A list of treatment group names. NB: The order of the items in the
list must correspond to the order in which the conditional average
treatment effect estimates are in cate_array.
y_proba (array, shape = (num_samples, )) – The predicted probability of conversion using the Y ~ X model across
the total sample.
cate (array, shape = (num_samples, len(set(treatment)))) – Conditional average treatment effect estimations from any model.
value (array, shape = (num_samples, )) – Value of converting each unit.
conversion_cost (shape = (num_samples, len(set(treatment)))) – The cost of a treatment that is triggered if a unit converts after having been in the treatment, such as a
promotion code.
impression_cost (shape = (num_samples, len(set(treatment)))) – The cost of a treatment that is the same for each unit whether or not they convert, such as a cost associated
with a promotion channel.
Notes
Because we get the conditional average treatment effects from
cate-learners relative to the control condition, we subtract the
cate for the unit in their actual treatment group from y_proba for that
unit, in order to recover the control outcome. We then add the cates
to the control outcome to obtain y_proba under each condition. These
outcomes are counterfactual because just one of them is actually
observed.
To capture the counterfactual notation, we use 1 and 0 to indicate the actual and
counterfactual values of a variable, respectively, and we use do to indicate the effect
of an intervention.
The experimental and observational data are either assumed to come to the same population,
or from random samples of the population. If the data are from a sample, the bounds may
be incorrectly calculated because the relevant quantities in the Tian-Pearl equations are
defined e.g. as \(P(Y|do(T))\), not \(P(Y|do(T), S)\) where \(S\) corresponds to sample selection.
Bareinboim and Pearl (2016) discuss conditions
under which \(P(Y|do(T))\) can be recovered from \(P(Y|do(T), S)\).
Get auuc values for cumulative gains of model estimates in quantiles.
For details, reference get_cumgain() and plot_gain()
:param synthetic_preds: dictionary of predictions generated by get_synthetic_preds()
:type synthetic_preds: dict
:param or get_synthetic_preds_holdout():
:param outcome_col: the column name for the actual outcome
:type outcome_col: str, optional
:param treatment_col: the column name for the treatment indicator (0 or 1)
:type treatment_col: str, optional
:param treatment_effect_col: the column name for the true treatment effect
:type treatment_effect_col: str, optional
:param plot: plot the cumulative gain chart or not
:type plot: boolean,optional
Returns:
auuc values by learner for cumulative gains of model estimates
Generate a synthetic dataset for classification uplift modeling problem.
Parameters:
n_samples (int, optional (default=1000)) – The number of samples to be generated for each treatment group.
treatment_name (list, optional (default = ['control','treatment1','treatment2','treatment3'])) – The list of treatment names.
y_name (string, optional (default = 'conversion')) – The name of the outcome variable to be used as a column in the output dataframe.
n_classification_features (int, optional (default = 10)) – Total number of features for base classification
n_classification_informative (int, optional (default = 5)) – Total number of informative features for base classification
n_classification_redundant (int, optional (default = 0)) – Total number of redundant features for base classification
n_classification_repeated (int, optional (default = 0)) – Total number of repeated features for base classification
n_uplift_increase_dict (dictionary, optional (default: {'treatment1': 2, 'treatment2': 2, 'treatment3': 2})) – Number of features for generating positive treatment effects for corresponding treatment group.
Dictionary of {treatment_key: number_of_features_for_increase_uplift}.
n_uplift_decrease_dict (dictionary, optional (default: {'treatment1': 0, 'treatment2': 0, 'treatment3': 0})) – Number of features for generating negative treatment effects for corresponding treatment group.
Dictionary of {treatment_key: number_of_features_for_increase_uplift}.
delta_uplift_increase_dict (dictionary, optional (default: {'treatment1': .02, 'treatment2': .05, 'treatment3': .1})) – Positive treatment effect created by the positive uplift features on the base classification label.
Dictionary of {treatment_key: increase_delta}.
delta_uplift_decrease_dict (dictionary, optional (default: {'treatment1': 0., 'treatment2': 0., 'treatment3': 0.})) – Negative treatment effect created by the negative uplift features on the base classification label.
Dictionary of {treatment_key: increase_delta}.
n_uplift_increase_mix_informative_dict (dictionary, optional) – Number of positive mix features for each treatment. The positive mix feature is defined as a linear combination
of a randomly selected informative classification feature and a randomly selected positive uplift feature.
The linear combination is made by two coefficients sampled from a uniform distribution between -1 and 1.
default: {‘treatment1’: 1, ‘treatment2’: 1, ‘treatment3’: 1}
n_uplift_decrease_mix_informative_dict (dictionary, optional) – Number of negative mix features for each treatment. The negative mix feature is defined as a linear combination
of a randomly selected informative classification feature and a randomly selected negative uplift feature. The
linear combination is made by two coefficients sampled from a uniform distribution between -1 and 1.
default: {‘treatment1’: 0, ‘treatment2’: 0, ‘treatment3’: 0}
positive_class_proportion (float, optional (default = 0.5)) – The proportion of positive label (1) in the control group.
random_seed (int, optional (default = 20190101)) – The random seed to be used in the data generation process.
Returns:
df_res (DataFrame) – A data frame containing the treatment label, features, and outcome variable.
x_name (list) – The list of feature names generated.
Notes
The algorithm for generating the base classification dataset is adapted from the make_classification method in the
sklearn package, that uses the algorithm in Guyon [1] designed to generate the “Madelon” dataset.
Generate a synthetic dataset for classification uplift modeling problem.
Parameters:
n_samples (int, optional (default=1000)) – The number of samples to be generated for each treatment group.
treatment_name (list, optional (default = ['control','treatment1','treatment2','treatment3'])) – The list of treatment names. The first element must be ‘control’ as control group, and the rest are treated as
treatment groups.
y_name (string, optional (default = 'conversion')) – The name of the outcome variable to be used as a column in the output dataframe.
n_classification_features (int, optional (default = 10)) – Total number of features for base classification
n_classification_informative (int, optional (default = 5)) – Total number of informative features for base classification
n_classification_redundant (int, optional (default = 0)) – Total number of redundant features for base classification
n_classification_repeated (int, optional (default = 0)) – Total number of repeated features for base classification
n_uplift_dict (dictionary, optional (default: {'treatment1': 2, 'treatment2': 2, 'treatment3': 3})) – Number of features for generating heterogeneous treatment effects for corresponding treatment group.
Dictionary of {treatment_key: number_of_features_for_uplift}.
n_mix_informative_uplift_dict (dictionary, optional (default: {'treatment1': 1, 'treatment2': 1, 'treatment3': 1})) – Number of mix features for each treatment. The mix feature is defined as a linear combination
of a randomly selected informative classification feature and a randomly selected uplift feature.
The mixture is made by a weighted sum (p*feature1 + (1-p)*feature2), where the weight p is drawn from a uniform
distribution between 0 and 1.
delta_uplift_dict (dictionary, optional (default: {'treatment1': .02, 'treatment2': .05, 'treatment3': -.05})) – Treatment effect (delta), can be positive or negative.
Dictionary of {treatment_key: delta}.
positive_class_proportion (float, optional (default = 0.1)) – The proportion of positive label (1) in the control group, or the mean of outcome variable for control group.
random_seed (int, optional (default = 20200101)) – The random seed to be used in the data generation process.
feature_association_list (list, optional (default = ['linear','quadratic','cubic','relu','sin','cos'])) – List of uplift feature association patterns to the treatment effect. For example, if the feature pattern is
‘quadratic’, then the treatment effect will increase or decrease quadratically with the feature.
The values in the list must be one of (‘linear’,’quadratic’,’cubic’,’relu’,’sin’,’cos’). However, the same
value can appear multiple times in the list.
random_select_association (boolean, optional (default = True)) – How the feature patterns are selected from the feature_association_list to be applied in the data generation
process. If random_select_association = True, then for every uplift feature, a random feature association
pattern is selected from the list. If random_select_association = False, then the feature association pattern
is selected from the list in turns to be applied to each feature one by one.
error_std (float, optional (default = 0.05)) – Standard deviation to be used in the error term of the logistic regression. The error is drawn from a normal
distribution with mean 0 and standard deviation specified in this argument.
Returns:
df1 (DataFrame) – A data frame containing the treatment label, features, and outcome variable.
x_name (list) – The list of feature names generated.
Synthetic data in Nie X. and Wager S. (2018) ‘Quasi-Oracle Estimation of Heterogeneous Treatment Effects’
:param mode: mode of the simulation: 1 for difficult nuisance components and an easy treatment effect. 2 for a randomized trial. 3 for an easy propensity and a difficult baseline. 4 for unrelated treatment and control groups. 5 for a hidden confounder biasing treatment.
:type mode: int, optional
:param n: number of observations
:type n: int, optional
:param p: number of covariates (>=5)
:type p: int optional
:param sigma: standard deviation of the error term
:type sigma: float
:param adj: adjustment term for the distribution of propensity, e. Higher values shift the distribution to 0.
It does not apply to mode == 2 or 3.
Returns:
Synthetically generated samples with the following outputs:
y ((n,)-array): outcome variable.
X ((n,p)-ndarray): independent variables.
w ((n,)-array): treatment flag with value 0 or 1.
tau ((n,)-array): individual treatment effect.
b ((n,)-array): expected outcome.
e ((n,)-array): propensity of receiving treatment.
matched_indexes_ (pandas.DataFrame): two-column dataframe with the
(from,to) pairs of original data indices produced by the most
recent match() call. from corresponds to the matching
source group (treatment if treatment_to_control else control);
to is the matched counterpart from the opposite group. Each row
is one matched pair, so with ratio>1 a single from index
can appear multiple times against distinct to indices. Useful
for joining matched pairs back to upstream metadata or auditing the
matching outcome (see uber/causalml#621). match_by_group calls
match() once per group, so the attribute reflects the last
group processed.
X (numpy.ndarray, pd.DataFrame, or pl.DataFrame) – a feature matrix.
scikit-learn >= 1.6 accepts pandas and Polars DataFrames
natively, so no conversion is performed here.
y (numpy.ndarray, pd.Series, or pl.Series) – a binary target vector
Generate propensity score if user didn’t provide and optionally calibrate.
Parameters:
X (np.matrix, pd.DataFrame, or pl.DataFrame) – features for training
treatment (np.array, pd.Series, or pl.Series) – a treatment vector for training
p_model (model object, optional) – a binary classifier with either a predict_proba or predict method
X_pred (np.matrix, pd.DataFrame, or pl.DataFrame, optional) – features for prediction
treatment_pred (np.array, pd.Series, or pl.Series, optional) – a treatment vector for prediction
calibrate_p (bool, optional) – whether calibrate the propensity score
clip_bounds (tuple, optional) – lower and upper bounds for clipping propensity scores. Bounds should be implemented
such that: 0 < lower < upper < 1, to avoid division by zero in BaseRLearner.fit_predict() step.
Returns:
(tuple)
p (numpy.ndarray): propensity score
p_model (PropensityModel): either the original p_model or a trained ElasticNetPropensityModel
Cross-fitted outcome/treatment residuals for the R-loss (Nie & Wager, 2021).
Computes out-of-fold m_hat(X) = E[Y|X] and e_hat(X) = E[W|X] via
n_folds-fold cross-fitting, stratified on treatment so every fold retains
both arms, and returns:
y_residual = y - m_hat(X)
w_residual = w - e_hat(X)
A candidate CATE model tau_hat is scored against these via the R-loss:
This is also the quantity BaseRLearner.fit() implicitly minimizes: fitting
the per-arm effect model against target (y_residual / w_residual) with
sample_weight = w_residual ** 2 is the weighted-least-squares solution to
the same R-loss objective.
Parameters:
X (numpy.ndarray or pandas.DataFrame) – a feature matrix
treatment (numpy.ndarray or pandas.Series) – a binary treatment indicator (0 or 1)
y (numpy.ndarray or pandas.Series) – an outcome vector
outcome_learner (model) – a model to estimate E[Y|X]. Must implement
fit/predict (or predict_proba if method=”predict_proba”)
propensity_learner (PropensityModel, optional) – passed through to
compute_propensity_score(). Ignored if p is given.
Defaults to ElasticNetPropensityModel
p (numpy.ndarray or pandas.Series, optional) – pre-computed propensity
scores. If given, propensity is not re-estimated in-fold
method (str, optional) – “predict” or “predict_proba” (for classifier
outcome learners, e.g. BaseRClassifier). Only the positive-class
column is used for “predict_proba”. Default “predict”
n_folds (int, optional) – number of cross-fitting folds. Default 5
random_state (int or None, optional) – random seed for the fold splitter
n_jobs (int, optional) – parallel jobs forwarded to cross_val_predict
for the outcome model. Default -1
compute_w_residual (bool, optional) – whether to compute and return
w_residual. If False, skips propensity estimation entirely (no
in-fold propensity model is fit) and returns w_residual=None.
Set False when only the outcome residual is needed – e.g.
BaseRLearner.fit(), which already has propensity scores from
elsewhere and would otherwise pay for a redundant per-fold
propensity fit whose output is discarded. Default True.
Returns:
y_residual (numpy.ndarray): y - m_hat(X), out-of-fold
w_residual (numpy.ndarray or None): w - e_hat(X), out-of-fold
(or w - p directly if p was supplied), or None if
compute_w_residual=False
A Sensitivity Check class to support Placebo Treatment, Irrelevant Additional Confounder
and Subset validation refutation methods to verify causal inference.
Return separate potential-outcome predictions mu1_hat, mu0_hat.
Only supported for S/T/DR-learner-style objects, whose
fit_predict(…, return_components=True) returns the fitted
outcome regressions (mu0_hat, mu1_hat) directly. X-learner and
R-learner are explicitly unsupported: X-learner’s “components”
are two CATE estimates from its second-stage tau models, not
potential outcomes, and R-learner has no outcome-regression
decomposition to extract.
Parameters:
X – same as get_prediction()
p – same as get_prediction()
treatment – same as get_prediction()
y – same as get_prediction()
Returns:
(mu1_hat, mu0_hat)
Return type:
(tuple of np.array)
Raises:
NotImplementedError – if the learner does not expose
potential-outcome regressions via return_components.
method (list of str) – a list of sensitivity analysis method
sample_size (float, optional) – ratio for subset the original data
confound (string, optional) – the name of confouding function
alpha_range (np.array, optional) – a parameter to pass the confounding function
Returns:
a feature matrix
p (np.array): a propensity score vector between 0 and 1
treatment (np.array): a treatment vector (1 if treated, otherwise 0)
y (np.array): an outcome vector
Check partial rsqs values of feature corresponding confounding amonunt of ATE
:param sens_df: a data frame output from causalsens
:type sens_df: pandas.DataFrame
:param feature_name: feature name to check
:type feature_name: str
:param partial_rsqs_value: partial rsquare value of feature
:type partial_rsqs_value: float
:param range: range to search from sens_df
:type range: float
Plot the results of a sensitivity analysis against unmeasured
:param sens_df: a data frame output from causalsens
:type sens_df: pandas.DataFrame
:param partial_rsqs_d: a data frame output from causalsens including partial rsqure
:type partial_rsqs_d: pandas.DataFrame
:param type: the type of plot to draw, ‘raw’ or ‘r.squared’ are supported
:type type: str, optional
:param ci: whether plot confidence intervals
:type ci: bool, optional
:param partial_rsqs: whether plot partial rsquare results
:type partial_rsqs: bool, optional
Calculate the AUUC (Area Under the Uplift Curve) score.
Args:
df (pandas.DataFrame): a data frame with model estimates and actual data as columns.
Columns not matching outcome_col, treatment_col, or treatment_effect_col are
treated as model prediction columns whose AUUC will be computed.
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
return_ci (bool, optional): whether to return standard errors and bootstrap
confidence intervals. Default False, so existing callers are unaffected.
n_bootstrap (int, optional): number of half-sample bootstrap iterations.
Only used when return_ci=True. Default 200.
alpha (float, optional): significance level for confidence intervals.
Only used when return_ci=True. Default 0.05.
random_state (int or None, optional): random seed for the bootstrap sampler.
Pass an integer for reproducible results. Default None.
Returns:
(pandas.Series): the AUUC score for each model estimate column
If return_ci=True:
(pandas.DataFrame): AUUC score, standard error and confidence interval
bounds for each model estimate column.
Return type:
If return_ci=False
Note
No p-value is reported for AUUC. A ranking drawn at random scores about 0.5
here rather than 0, so testing H0: AUUC = 0 would reject for essentially
every model and say nothing about whether the model beats random. Use
qini_score(), which is already measured against the random curve, when
a test against random is what is wanted.
w (numpy.array, optional) – a treatment vector (1 or True: treatment, 0 or False: control). If given, log
metrics for the treatment and control group separately
metrics (dict, optional) – a dictionary of the metric names and functions
causalml.metrics.compute_dr_pseudo_outcomes(X, treatment, y, p=None, learner=None, control_outcome_learner=None, treatment_outcome_learner=None, n_folds=5, p_clip_bounds=(0.02,0.98), random_state=None)[source]
Construct cross-fitted doubly-robust (AIPW) pseudo-outcomes for CATE evaluation.
where e is the propensity score and mu_0/mu_1 are the control/treatment
outcome regressions. Under either correct propensity or correct outcome-model
specification, E[phi_i|X_i] is an unbiased estimate of the true CATE
tau(X_i) (Kennedy, 2023), which is why phi can stand in for the unobserved
ground-truth treatment effect when scoring fitted CATE models.
Nuisance models (propensity and outcome regressions) are cross-fitted with
n_folds-fold splitting so that phi_i is always constructed from models
that did not see unit i during training. This is the same doubly-robust
formula used internally by BaseDRLearner.fit().
This is a standalone helper so the pseudo-outcomes can be computed once and
reused across multiple scoring calls – e.g. passed to dr_score() directly,
or to rate_score(...,treatment_effect_col=...) for RATE on observational
data – without re-fitting nuisance models for each.
Parameters:
X (numpy.ndarray or pandas.DataFrame) – a feature matrix
treatment (numpy.ndarray or pandas.Series) – a binary treatment indicator (0 or 1)
y (numpy.ndarray or pandas.Series) – an outcome vector
p (numpy.ndarray or pandas.Series, optional) – propensity scores. If None,
they are estimated in-fold via causalml.propensity.compute_propensity_score
(ElasticNetPropensityModel by default)
learner (model, optional) – a model used for both control and treatment outcome
regressions if the group-specific learners below are not given
control_outcome_learner (model, optional) – a model to estimate outcomes
in the control group
treatment_outcome_learner (model, optional) – a model to estimate outcomes
in the treatment group
n_folds (int, optional) – number of cross-fitting folds. Default 5.
p_clip_bounds (tuple, optional) – lower and upper bounds for clipping
propensity scores before they’re used as AIPW weights. The default
ElasticNetPropensityModel clips to (1e-3,1-1e-3) internally
for numerical stability of the model itself, but that’s too permissive
once the score is inverted here: a handful of near-boundary,
cross-fitted propensities (e.g. 0.001, arising from isotonic
calibration on a single fold) can produce AIPW weights in the
hundreds and dominate the mean. Tighter trimming bounds the
variance at the cost of some bias for units with extreme propensity;
(0.02, 0.98) is a reasonable default for that trade-off. Default
(0.02, 0.98).
random_state (int or None, optional) – random seed for the fold splitter.
Default None.
Returns:
the cross-fitted DR pseudo-outcomes, one per row of X
Score fitted CATE models via the doubly-robust (DR) pseudo-outcome loss.
Following Kennedy (2023), this constructs cross-fitted AIPW pseudo-outcomes
phi (see compute_dr_pseudo_outcomes()) and scores each candidate CATE
model by its mean squared error against phi:
DR loss(tau_hat) = mean((tau_hat(X) - phi) ** 2)
Lower is better. Unlike held-out outcome MSE, this measures accuracy of the
treatment effect estimate rather than the outcome level, without requiring
access to counterfactual outcomes. Mahajan et al. (2024) found DR-based
metrics dominate across 78 benchmark datasets for CATE model selection.
Pseudo-outcomes can either be supplied directly (via pseudo_outcome_col,
e.g. computed once with compute_dr_pseudo_outcomes() and reused across
multiple scoring calls or shared with rate_score()) or computed internally
from X, treatment_col, and outcome_col.
Parameters:
df (pandas.DataFrame) – a data frame with fitted CATE model estimates as
columns, plus either pseudo_outcome_col or both outcome_col
and treatment_col
X (numpy.ndarray or pandas.DataFrame, optional) – feature matrix used to
fit the DR nuisance models. Required unless pseudo_outcome_col is
already present in df
treatment_col (str, optional) – the column name for the treatment
indicator (0 or 1). Ignored if pseudo_outcome_col is provided
outcome_col (str, optional) – the column name for the actual outcome.
Ignored if pseudo_outcome_col is provided
pseudo_outcome_col (str, optional) – the column name of pre-computed DR
pseudo-outcomes (e.g. from compute_dr_pseudo_outcomes()). If given
and present in df, nuisance models are not re-fit
p (numpy.ndarray or pandas.Series, optional) – propensity scores. Only
used when pseudo-outcomes are computed internally
learner (model, optional) – a model for both control and treatment outcome
regressions if the group-specific learners below are not given.
Required unless pseudo_outcome_col is provided
control_outcome_learner (model, optional) – a model to estimate outcomes
in the control group
treatment_outcome_learner (model, optional) – a model to estimate outcomes
in the treatment group
n_folds (int, optional) – number of cross-fitting folds for nuisance
estimation. Default 5
p_clip_bounds (tuple, optional) – bounds for clipping propensity scores
used as AIPW weights when pseudo-outcomes are computed internally.
See compute_dr_pseudo_outcomes() for why this is tighter than a
propensity model’s own internal clipping. Ignored if
pseudo_outcome_col is provided. Default (0.02, 0.98)
Get cumulative gains of model estimates in population.
If the true treatment effect is provided (e.g. in synthetic data), it’s calculated
as the cumulative gain of the true treatment effect in each population.
Otherwise, it’s calculated as the cumulative difference between the mean outcomes
of the treatment and control groups in each population.
For details, see Section 4.1 of Gutierrez and G{‘e}rardy (2016), Causal Inference
and Uplift Modeling: A review of the literature.
For the former, treatment_effect_col should be provided. For the latter, both
outcome_col and treatment_col should be provided.
Parameters:
df (pandas.DataFrame) – a data frame with model estimates and actual data as columns
outcome_col (str, optional) – the column name for the actual outcome
treatment_col (str, optional) – the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional) – the column name for the true treatment effect
normalize (bool, optional) – whether to normalize the y-axis to 1 or not
Get average uplifts of model estimates in cumulative population.
If the true treatment effect is provided (e.g. in synthetic data), it’s calculated
as the mean of the true treatment effect in each of cumulative population.
Otherwise, it’s calculated as the difference between the mean outcomes of the
treatment and control groups in each of cumulative population.
For details, see Section 4.1 of Gutierrez and G{‘e}rardy (2016), Causal Inference
and Uplift Modeling: A review of the literature.
For the former, treatment_effect_col should be provided. For the latter, both
outcome_col and treatment_col should be provided.
Parameters:
df (pandas.DataFrame) – a data frame with model estimates and actual data as columns
outcome_col (str, optional) – the column name for the actual outcome
treatment_col (str, optional) – the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional) – the column name for the true treatment effect
random_seed (int, optional) – deprecated
Returns:
average uplifts of model estimates in cumulative population
If the true treatment effect is provided (e.g. in synthetic data), it’s calculated
as the cumulative gain of the true treatment effect in each population.
Otherwise, it’s calculated as the cumulative difference between the mean outcomes
of the treatment and control groups in each population.
For details, see Radcliffe (2007), Using Control Group to Target on Predicted Lift:
Building and Assessing Uplift Models
For the former, treatment_effect_col should be provided. For the latter, both
outcome_col and treatment_col should be provided.
Parameters:
df (pandas.DataFrame) – a data frame with model estimates and actual data as columns
outcome_col (str, optional) – the column name for the actual outcome
treatment_col (str, optional) – the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional) – the column name for the true treatment effect
normalize (bool, optional) – whether to normalize the y-axis to 1 or not
Get the Targeting Operator Characteristic (TOC) of model estimates in population.
TOC(q) is the difference between the ATE among the top-q fraction of units ranked
by the prioritization score and the overall ATE. A positive TOC at low q indicates
the model successfully identifies units with above-average treatment benefit.
By definition, TOC(0) = 0 and TOC(1) = 0 (the subset ATE equals the overall ATE
when the entire population is selected).
If the true treatment effect is provided (e.g. in synthetic data), it’s used directly
to calculate TOC. Otherwise, it’s estimated as the difference between the mean outcomes
of the treatment and control groups in each quantile band.
Note: when using observed outcomes (i.e. without treatment_effect_col), the subset
ATE is estimated via a naive difference-in-means. This is valid for randomized
experiments (RCTs) but may be biased for observational data due to confounding within
quantile bands. For observational settings, compute doubly-robust (AIPW) pseudo-outcomes
externally and pass them as treatment_effect_col. See Yadlowsky et al. (2021),
Section 4 for details.
If a quantile band contains only treated or only control units, the code falls back to
TOC(q) = 0 for that band (i.e., subset ATE is set to the overall ATE). This is a
conservative approximation and is logged as a warning.
For details, see Yadlowsky et al. (2021), Evaluating Treatment Prioritization Rules
via Rank-Weighted Average Treatment Effects. https://arxiv.org/abs/2111.07966
For the former, treatment_effect_col should be provided. For the latter, both
outcome_col and treatment_col should be provided.
Parameters:
df (pandas.DataFrame) – a data frame with model estimates and actual data as columns
outcome_col (str, optional) – the column name for the actual outcome
treatment_col (str, optional) – the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional) – the column name for the true treatment effect
normalize (bool, optional) – whether to normalize the TOC curve by its maximum
absolute value. Uses max(|TOC|) as the reference to avoid division by zero
at q=1 where TOC is always zero by definition.
Returns:
TOC values of model estimates in population, indexed by quantile q
The mean absolute error is a non-negative floating point value, where best value
is 0.0. Read more in the User Guide.
Parameters:
y_true (array-like of shape (n_samples,) or (n_samples, n_outputs)) – Ground truth (correct) target values.
y_pred (array-like of shape (n_samples,) or (n_samples, n_outputs)) – Estimated target values.
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.
multioutput ({'raw_values', 'uniform_average'} or array-like of shape (n_outputs,), default='uniform_average') –
Defines aggregating of multiple output values.
Array-like value defines weights used to average errors.
’raw_values’ :
Returns a full set of errors in case of multioutput input.
’uniform_average’ :
Errors of all outputs are averaged with uniform weight.
Returns:
loss – If multioutput is ‘raw_values’, then mean absolute error is returned
for each output separately.
If multioutput is ‘uniform_average’ or an ndarray of weights, then the
weighted average of all output errors is returned.
MAE output is non-negative floating point. The best value is 0.0.
Plot the cumulative gain chart (or uplift curve) of model estimates.
If the true treatment effect is provided (e.g. in synthetic data), it’s calculated
as the cumulative gain of the true treatment effect in each population.
Otherwise, it’s calculated as the cumulative difference between the mean outcomes
of the treatment and control groups in each population.
For details, see Section 4.1 of Gutierrez and G{‘e}rardy (2016), Causal Inference
and Uplift Modeling: A review of the literature.
For the former, treatment_effect_col should be provided. For the latter, both
outcome_col and treatment_col should be provided.
Parameters:
df (pandas.DataFrame) – a data frame with model estimates and actual data as columns
outcome_col (str, optional) – the column name for the actual outcome
treatment_col (str, optional) – the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional) – the column name for the true treatment effect
normalize (bool, optional) – whether to normalize the y-axis to 1 or not
random_seed (int, optional) – random seed for numpy.random.rand()
n (int, optional) – the number of samples to be used for plotting
Plot the lift chart of model estimates in cumulative population.
If the true treatment effect is provided (e.g. in synthetic data), it’s calculated
as the mean of the true treatment effect in each of cumulative population.
Otherwise, it’s calculated as the difference between the mean outcomes of the
treatment and control groups in each of cumulative population.
For details, see Section 4.1 of Gutierrez and G{‘e}rardy (2016), Causal Inference
and Uplift Modeling: A review of the literature.
For the former, treatment_effect_col should be provided. For the latter, both
outcome_col and treatment_col should be provided.
Parameters:
df (pandas.DataFrame) – a data frame with model estimates and actual data as columns
outcome_col (str, optional) – the column name for the actual outcome
treatment_col (str, optional) – the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional) – the column name for the true treatment effect
random_seed (int, optional) – deprecated
n (int, optional) – the number of samples to be used for plotting
Plot the Qini chart (or uplift curve) of model estimates.
If the true treatment effect is provided (e.g. in synthetic data), it’s calculated
as the cumulative gain of the true treatment effect in each population.
Otherwise, it’s calculated as the cumulative difference between the mean outcomes
of the treatment and control groups in each population.
For details, see Radcliffe (2007), Using Control Group to Target on Predicted Lift:
Building and Assessing Uplift Models
For the former, treatment_effect_col should be provided. For the latter, both
outcome_col and treatment_col should be provided.
Parameters:
df (pandas.DataFrame) – a data frame with model estimates and actual data as columns
outcome_col (str, optional) – the column name for the actual outcome
treatment_col (str, optional) – the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional) – the column name for the true treatment effect
normalize (bool, optional) – whether to normalize the y-axis to 1 or not
random_seed (int, optional) – deprecated
n (int, optional) – the number of samples to be used for plotting
ci (bool, optional) – whether return confidence intervals for ATE or not
Plot the Targeting Operator Characteristic (TOC) curve of model estimates.
The TOC(q) shows the excess ATE when treating only the top-q fraction of units
prioritized by a model score, relative to the overall ATE. A positive and steeply
decreasing curve indicates the model effectively ranks high-benefit units first.
If the true treatment effect is provided (e.g. in synthetic data), it’s used directly.
Otherwise, it’s estimated from observed outcomes and treatment assignments.
For details, see Yadlowsky et al. (2021), Evaluating Treatment Prioritization Rules
via Rank-Weighted Average Treatment Effects. https://arxiv.org/abs/2111.07966
For the former, treatment_effect_col should be provided. For the latter, both
outcome_col and treatment_col should be provided.
Parameters:
df (pandas.DataFrame) – a data frame with model estimates and actual data as columns
outcome_col (str, optional) – the column name for the actual outcome
treatment_col (str, optional) – the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional) – the column name for the true treatment effect
normalize (bool, optional) – whether to normalize the TOC curve by its maximum
absolute value before plotting
n (int, optional) – the number of samples to be used for plotting
figsize (tuple, optional) – the size of the figure to plot
ax (plt.Axes, optional) – an existing axes object to draw on
Score fitted CATE models against a cross-fitted plug-in T-learner proxy.
Fits a simple T-learner – separate control/treatment outcome regressions –
with n_folds-fold cross-fitting, and uses mu_1(X)-mu_0(X) on each
held-out fold as a proxy for the true CATE. Candidate models are then scored
by mean squared error against this proxy:
Lower is better. This is a simpler baseline than dr_score() – it isn’t
doubly robust and is biased under a misspecified outcome model – but Mahajan
et al. (2024) found it is never dominated across their benchmark datasets
despite its simplicity, making it a useful complement to DR-based scoring
rather than a replacement.
Parameters:
df (pandas.DataFrame) – a data frame with fitted CATE model estimates as columns
X (numpy.ndarray or pandas.DataFrame) – feature matrix used to fit the
plug-in T-learner nuisance models
treatment_col (str, optional) – the column name for the treatment
indicator (0 or 1)
outcome_col (str, optional) – the column name for the actual outcome
learner (model, optional) – a model for both control and treatment outcome
regressions if the group-specific learners below are not given
control_outcome_learner (model, optional) – a model to estimate outcomes
in the control group
treatment_outcome_learner (model, optional) – a model to estimate outcomes
in the treatment group
n_folds (int, optional) – number of cross-fitting folds. Default 5
Calculate the Qini score: the area between the Qini curves of a model and random.
For details, see Radcliffe (2007), Using Control Group to Target on Predicted Lift:
Building and Assessing Uplift Models
Args:
df (pandas.DataFrame): a data frame with model estimates and actual data as columns
outcome_col (str, optional): the column name for the actual outcome
treatment_col (str, optional): the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional): the column name for the true treatment effect
normalize (bool, optional): whether to normalize the y-axis to 1 or not
return_ci (bool, optional): whether to return standard errors, bootstrap
confidence intervals and p-values. Default False, so existing callers
are unaffected.
n_bootstrap (int, optional): number of half-sample bootstrap iterations.
Only used when return_ci=True. Default 200.
alpha (float, optional): significance level for confidence intervals.
Only used when return_ci=True. Default 0.05.
random_state (int or None, optional): random seed for the bootstrap sampler.
Pass an integer for reproducible results. Default None.
Returns:
(pandas.Series): the Qini score for each model estimate column
If return_ci=True:
(pandas.DataFrame): Qini score, standard error, confidence interval bounds
and p-value for each model estimate column.
Return type:
If return_ci=False
Note
The p-value tests H0: Qini = 0, which here means the model’s ranking is no
better than random at finding units that benefit. That null is meaningful
because the score is already the area between the model curve and the
random curve — unlike AUUC, whose random baseline is about 0.5.
\(R^2\) (coefficient of determination) regression score function.
Best possible score is 1.0 and it can be negative (because the
model can be arbitrarily worse). In the general case when the true y is
non-constant, a constant model that always predicts the average y
disregarding the input features would get a \(R^2\) score of 0.0.
In the particular case when y_true is constant, the \(R^2\) score
is not finite: it is either NaN (perfect predictions) or -Inf
(imperfect predictions). To prevent such non-finite numbers to pollute
higher-level experiments such as a grid search cross-validation, by default
these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect
predictions) respectively. You can set force_finite to False to
prevent this fix from happening.
Note: when the prediction residuals have zero mean, the \(R^2\) score
is identical to the
ExplainedVariancescore.
Read more in the User Guide.
Parameters:
y_true (array-like of shape (n_samples,) or (n_samples, n_outputs)) – Ground truth (correct) target values.
y_pred (array-like of shape (n_samples,) or (n_samples, n_outputs)) – Estimated target values.
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.
multioutput ({'raw_values', 'uniform_average', 'variance_weighted'}, array-like of shape (n_outputs,) or None, default='uniform_average') –
Defines aggregating of multiple output scores.
Array-like value defines weights used to average scores.
Default is “uniform_average”.
’raw_values’ :
Returns a full set of scores in case of multioutput input.
’uniform_average’ :
Scores of all outputs are averaged with uniform weight.
’variance_weighted’ :
Scores of all outputs are averaged, weighted by the variances
of each individual output.
Changed in version 0.19: Default value of multioutput is ‘uniform_average’.
force_finite (bool, default=True) –
Flag indicating if NaN and -Inf scores resulting from constant
data should be replaced with real numbers (1.0 if prediction is
perfect, 0.0 otherwise). Default is True, a convenient setting
for hyperparameters’ search procedures (e.g. grid search
cross-validation).
Added in version 1.1.
Returns:
z – The \(R^2\) score or ndarray of scores if ‘multioutput’ is
‘raw_values’.
Return type:
float or ndarray of floats
Notes
This is not a symmetric function.
Unlike most other scores, \(R^2\) score may be negative (it need not
actually be the square of a quantity R).
This metric is not well-defined for single samples and will return a NaN
value if n_samples is less than two.
Calculate the Rank-weighted Average Treatment Effect (RATE) score.
RATE is the weighted area under the Targeting Operator Characteristic (TOC) curve:
RATE = integral_0^1 alpha(q) * TOC(q) dq
Two standard weighting schemes are supported (Yadlowsky et al., 2021):
"autoc": alpha(q) = 1/q. Places more weight on the highest-priority units.
Most powerful when treatment effects are concentrated in a small subgroup.
"qini": alpha(q) = q. Uniform weighting across units; reduces to the Qini
coefficient. More powerful when treatment effects are diffuse across the population.
A positive RATE indicates the prioritization rule effectively identifies units with
above-average treatment benefit. A RATE near zero suggests little heterogeneity or
a poor prioritization rule.
Note: the integral is approximated via a weighted mean over the discrete quantile grid
using midpoint values. Weights are normalized to sum to 1 (i.e. weights/weights.sum()),
so the absolute scale matches the TOC values but may differ slightly from the paper’s
continuous integral definition. Model rankings are preserved.
When return_ci=True, standard errors and confidence intervals are estimated via the
half-sample bootstrap (m = n // 2 draws without replacement), which gives valid
coverage for the RATE functional per the Yadlowsky et al. (2021) functional CLT.
The p-value tests H0: RATE = 0 (i.e. the model’s prioritization is no better than
random) using a two-sided z-test.
When using observed outcomes (without treatment_effect_col), the underlying TOC
estimates the subset ATE via naive difference-in-means, which is valid for RCTs but
biased for observational data. For observational settings, pass AIPW pseudo-outcomes
as treatment_effect_col. See the get_toc() docstring for details.
For details, see Yadlowsky et al. (2021), Evaluating Treatment Prioritization Rules
via Rank-Weighted Average Treatment Effects. https://arxiv.org/abs/2111.07966
For the former, treatment_effect_col should be provided. For the latter, both
outcome_col and treatment_col should be provided.
Parameters:
df (pandas.DataFrame) – a data frame with model estimates and actual data as columns
outcome_col (str, optional) – the column name for the actual outcome
treatment_col (str, optional) – the column name for the treatment indicator (0 or 1)
treatment_effect_col (str, optional) – the column name for the true treatment effect
weighting (str, optional) – the weighting scheme for the RATE integral.
One of "autoc" (default) or "qini".
normalize (bool, optional) – whether to normalize the TOC curve before scoring
return_ci (bool, optional) – whether to return bootstrap confidence intervals and
p-values. Default False.
n_bootstrap (int, optional) – number of half-sample bootstrap iterations.
Only used when return_ci=True. Default 200.
alpha (float, optional) – significance level for confidence intervals.
Only used when return_ci=True. Default 0.05.
random_state (int or None, optional) – random seed for the bootstrap sampler.
Pass an integer for reproducible results. Default None.
Returns:
(pandas.Series): RATE scores of model estimates
If return_ci=True:
(pandas.DataFrame): RATE score, standard error, CI lower bound, CI upper bound,
w (numpy.array, optional) – a treatment vector (1 or True: treatment, 0 or False: control). If given, log
metrics for the treatment and control group separately
metrics (dict, optional) – a dictionary of the metric names and functions
where m(X) = E[Y|X] and e(X) = E[W|X] are cross-fitted nuisance regressions
(see causalml.propensity.compute_r_residuals()). This is the loss
BaseRLearner.fit() already minimizes internally to train its own effect
model; exposing it standalone gives R-loss-based comparison across
arbitrary fitted CATE models – EconML RScorer parity. Lower is better.
R-score complements dr_score() and plug_in_t_score() on the CATE-accuracy
axis (as opposed to rate_score()’s targeting/ranking axis); Mahajan et al.
(2024) found DR-loss dominates and plug-in-T is never dominated, with
R-loss not the standout of the three – useful as a third opinion,
particularly for parity with EconML workflows already using RScorer.
Residuals can be supplied directly (e.g. precomputed once with
compute_r_residuals() and reused across scoring calls) via
y_residual_col / w_residual_col, or computed internally from X,
treatment_col, and outcome_col.
Parameters:
df (pandas.DataFrame) – a data frame with fitted CATE model estimates as
columns, plus either y_residual_col/w_residual_col or both
outcome_col and treatment_col
X (numpy.ndarray or pandas.DataFrame, optional) – feature matrix for the
R-loss nuisance models. Required unless residual columns are given
treatment_col (str, optional) – treatment indicator column (0 or 1).
Ignored if residual columns are provided
outcome_col (str, optional) – outcome column. Ignored if residual
columns are provided
y_residual_col (str, optional) – precomputed y - m_hat(X) column
w_residual_col (str, optional) – precomputed w - e_hat(X) column
outcome_learner (model, optional) – model for E[Y|X]. Required unless
residual columns are provided
propensity_learner (PropensityModel, optional) – passed to
compute_r_residuals(). Defaults to ElasticNetPropensityModel
Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) from prediction scores.
Note: this implementation can be used with binary, multiclass and
multilabel classification, but some restrictions apply (see Parameters).
Read more in the User Guide.
Parameters:
y_true (array-like of shape (n_samples,) or (n_samples, n_classes)) – True labels or label indicator matrix. The binary and multiclass cases
expect labels with shape (n_samples,) while the multilabel case expects
a multilabel indicator matrix with shape (n_samples, n_classes).
y_score (array-like of shape (n_samples,) or (n_samples, n_classes)) –
Target scores.
In the binary case, it corresponds to an array of shape
(n_samples,). Both probability estimates and non-thresholded
decision values can be provided. The probability estimates correspond
to the probability of the class with the greater label,
i.e. estimator.classes_[1] and thus
estimator.predict_proba(X, y)[:, 1]. The decision values
corresponds to the output of estimator.decision_function(X, y).
See more information in the User guide;
In the multiclass case, it corresponds to an array of shape
(n_samples, n_classes) of probability estimates provided by the
predict_proba method. The probability estimates must
sum to 1 across the possible classes. In addition, the order of the
class scores must correspond to the order of labels,
if provided, or else to the numerical or lexicographical order of
the labels in y_true. See more information in the
User guide;
In the multilabel case, it corresponds to an array of shape
(n_samples, n_classes). Probability estimates are provided by the
predict_proba method and the non-thresholded decision values by
the decision_function method. The probability estimates correspond
to the probability of the class with the greater label for each
output of the classifier. See more information in the
User guide.
average ({'micro', 'macro', 'samples', 'weighted'} or None, default='macro') –
If None, the scores for each class are returned.
Otherwise, this determines the type of averaging performed on the data.
Note: multiclass ROC AUC currently only handles the ‘macro’ and
‘weighted’ averages. For multiclass targets, average=None is only
implemented for multi_class=’ovr’ and average=’micro’ is only
implemented for multi_class=’ovr’.
'micro':
Calculate metrics globally by considering each element of the label
indicator matrix as a label.
'macro':
Calculate metrics for each label, and find their unweighted
mean. This does not take label imbalance into account.
'weighted':
Calculate metrics for each label, and find their average, weighted
by support (the number of true instances for each label).
'samples':
Calculate metrics for each instance, and find their average.
Will be ignored when y_true is binary.
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights.
max_fpr (float > 0 and <= 1, default=None) – If not None, the standardized partial AUC [2] over the range
[0, max_fpr] is returned. For the multiclass case, max_fpr,
should be either equal to None or 1.0 as AUC ROC partial
computation currently is not supported for multiclass.
Only used for multiclass targets. Determines the type of configuration
to use. The default value raises an error, so either
'ovr' or 'ovo' must be passed explicitly.
'ovr':
Stands for One-vs-rest. Computes the AUC of each class
against the rest [3][4]. This
treats the multiclass case in the same way as the multilabel case.
Sensitive to class imbalance even when average=='macro',
because class imbalance affects the composition of each of the
‘rest’ groupings.
'ovo':
Stands for One-vs-one. Computes the average AUC of all
possible pairwise combinations of classes [5].
Insensitive to class imbalance when
average=='macro'.
labels (array-like of shape (n_classes,), default=None) – Only used for multiclass targets. List of labels that index the
classes in y_score. If None, the numerical or lexicographical
order of the labels in y_true is used.
Plot Receiver Operating Characteristic (ROC) curve given an estimator and some data.
RocCurveDisplay.from_predictions
Plot Receiver Operating Characteristic (ROC) curve given the true and predicted values.
Notes
The Gini Coefficient is a summary measure of the ranking ability of binary
classifiers. It is expressed using the area under of the ROC as follows:
G = 2 * AUC - 1
Where G is the Gini coefficient and AUC is the ROC-AUC score. This normalisation
will ensure that random guessing will yield a score of 0 in expectation, and it is
upper bounded by 1.
>>> importnumpyasnp>>> fromsklearn.datasetsimportmake_multilabel_classification>>> fromsklearn.multioutputimportMultiOutputClassifier>>> X,y=make_multilabel_classification(random_state=0)>>> clf=MultiOutputClassifier(clf).fit(X,y)>>> # get a list of n_output containing probability arrays of shape>>> # (n_samples, n_classes)>>> y_score=clf.predict_proba(X)>>> # extract the positive columns for each output>>> y_score=np.transpose([score[:,1]forscoreiny_score])>>> roc_auc_score(y,y_score,average=None)array([0.828, 0.852, 0.94, 0.869, 0.95])>>> fromsklearn.linear_modelimportRidgeClassifierCV>>> clf=RidgeClassifierCV().fit(X,y)>>> roc_auc_score(y,clf.decision_function(X),average=None)array([0.82, 0.847, 0.93, 0.872, 0.944])
Rank features based on the chosen divergence measure.
Parameters:
data (pd.Dataframe) – DataFrame containing outcome, features, and experiment group
treatment_indicator (string) – the column name for binary indicator of treatment (1) or control (0)
features (list of string) – list of feature names, that are columns in the data DataFrame
y_name (string) – name of the outcome variable
method (string, optional, default = 'KL') – taking one of the following values {‘F’, ‘LR’, ‘KL’, ‘ED’, ‘Chi’}
The feature selection method to be used to rank the features.
‘F’ for F-test
‘LR’ for likelihood ratio test
‘KL’, ‘ED’, ‘Chi’ for bin-based uplift filter methods, KL divergence, Euclidean distance, Chi-Square
respectively
experiment_group_column (string, optional, default = 'treatment_group_key') – the experiment column name in
the DataFrame, which contains the treatment and control assignment label
control_group (string, optional, default = 'control') – name for control group, value in the experiment
group column
n_bins (int, optional, default = 10) – number of bins to be used for bin-based uplift filter methods
null_impute (str, optional, default=None) – impute np.nan present in the data taking on of the followin
strategy values {‘mean’, ‘median’, ‘most_frequent’, None}. If Value is None and null is present then
exception will be raised
Returns:
pd.DataFrame
a data frame containing the feature importance statistics
Rank features based on the F-statistics of the interaction.
Parameters:
data (pd.Dataframe) – DataFrame containing outcome, features, and experiment group
treatment_indicator (string) – the column name for binary indicator of treatment (1) or control (0)
features (list of string) – list of feature names, that are columns in the data DataFrame
y_name (string) – name of the outcome variable
order (int) – the order of feature to be evaluated with the treatment effect, order takes 3 values: 1,2,3.
order = 1 corresponds to linear importance of the feature, order=2 corresponds to quadratic and linear
importance of the feature,
forms. (order= 3 will calculate feature importance up to cubic)
Returns:
pd.DataFrame
a data frame containing the feature importance statistics
Rank features based on the LRT-statistics of the interaction.
Parameters:
data (pd.Dataframe) – DataFrame containing outcome, features, and experiment group
treatment_indicator (string) – the column name for binary indicator of treatment (1) or control (0)
feature_name (string) – feature name, as one column in the data DataFrame
y_name (string) – name of the outcome variable
order (int) – the order of feature to be evaluated with the treatment effect, order takes 3 values: 1,2,3.
order = 1 corresponds to linear importance of the feature, order=2 corresponds to quadratic and linear
importance of the feature,
forms. (order= 3 will calculate feature importance up to cubic)
Returns:
pd.DataFrame
a data frame containing the feature importance statistics
Rank features based on the chosen statistic of the interaction.
Parameters:
data (pd.Dataframe) – DataFrame containing outcome, features, and experiment group
features (list of string) – list of feature names, that are columns in the data DataFrame
y_name (string) – name of the outcome variable
method (string, optional, default = 'KL') – taking one of the following values {‘F’, ‘LR’, ‘KL’, ‘ED’, ‘Chi’}
The feature selection method to be used to rank the features.
‘F’ for F-test
‘LR’ for likelihood ratio test
‘KL’, ‘ED’, ‘Chi’ for bin-based uplift filter methods, KL divergence, Euclidean distance, Chi-Square
respectively
experiment_group_column (string) – the experiment column name in the DataFrame, which contains the treatment
and control assignment label
control_group (string) – name for control group, value in the experiment group column
treatment_group (string) – name for treatment group, value in the experiment group column
n_bins (int, optional) – number of bins to be used for bin-based uplift filter methods
null_impute (str, optional, default=None) – impute np.nan present in the data taking on of the following
strategy values {‘mean’, ‘median’, ‘most_frequent’, None}. If value is None and null is present then
exception will be raised
order (int) – the order of feature to be evaluated with the treatment effect for F filter and LR filter,
order takes 3 values: 1,2,3. order = 1 corresponds to linear importance of the feature, order=2
corresponds to quadratic and linear importance of the feature,
forms. (order= 3 will calculate feature importance up to cubic)
disp (bool) – Set to True to print convergence messages for Logistic regression convergence in LR method.
Returns:
pd.DataFrame
a data frame with following columns: [‘method’, ‘feature’, ‘rank’, ‘score’, ‘p_value’, ‘misc’]