causalml 包

子模块

causalml.inference.tree 模块

class causalml.inference.tree.CausalRandomForestRegressor(n_estimators: int = 100, *, control_name: int | str = 0, criterion: str = 'causal_mse', alpha: float = 0.05, max_depth: int | None = None, min_samples_split: int = 60, min_samples_leaf: int = 100, min_weight_fraction_leaf: float = 0.0, max_features: int | float | str = 1.0, max_leaf_nodes: int | None = None, min_impurity_decrease: float = -inf, bootstrap: bool = True, oob_score: bool = False, n_jobs: int | None = None, random_state: int | None = None, verbose: int = 0, warm_start: bool = False, ccp_alpha: float = 0.0, groups_penalty: float = 0.5, max_samples: int | None = None, groups_cnt: bool = True)[source]

基础:ForestRegressor

calculate_error(X_train: ndarray, X_test: ndarray, inbag: ndarray | None = None, calibrate: bool = True, memory_constrained: bool = False, memory_limit: int | None = None) ndarray[source]

从scikit-learn的RandomForest估计器计算误差条 来源: https://github.com/scikit-learn-contrib/forest-confidence-interval

Parameters:
  • X_train – (np.ndarray), 特征矩阵的训练子样本, (n_train_sample, n_features)

  • X_test – (np.ndarray), 特征矩阵的测试子样本, (n_train_sample, n_features)

  • inbag – (ndarray, 可选), 拟合数据的inbag矩阵。如果设置为None(默认),它将从森林中推断出来。然而,这仅适用于设置了True的树的引导。也就是说,如果采样是使用替换完成的。否则,用户需要提供自己的inbag矩阵。

  • calibrate – (boolean, optional) 是否应用校准以减少蒙特卡洛噪声。 如果森林中的树数量太少,由于蒙特卡洛效应,某些方差估计可能为负。要使用校准, 默认值:True

  • memory_constrained – (布尔值, 可选) 是否存在内存限制。如果为False,则假定形状为(n_train_sample,n_test_sample)的ndarray适合主内存。如果将memory_limit调整到最佳范围,设置为True实际上可以提高速度。

  • memory_limit – (int, optional) 中间矩阵将占用的内存上限,单位为兆字节。如果memory_constrained=True,则必须提供此参数。

Returns:

(np.ndarray), 一个包含RandomForest对象无偏采样方差的数组。

fit(X: ndarray, treatment: ndarray, y: ndarray, sample_weight: ndarray | None = None)[source]

拟合因果随机森林 :param X: (np.ndarray), 特征矩阵 :param treatment: (np.ndarray), 处理向量 :param y: (np.ndarray), 结果向量 :param sample_weight: (np.ndarray), 样本权重

Returns:

自身

predict(X: ndarray, with_outcomes: bool = False) ndarray[source]

预测个体治疗效果

Parameters:
  • X (np.matrix) – 特征矩阵

  • with_outcomes (bool) – 包含结果 Y_hat(X|T=0), Y_hat(X|T=1) 以及个体治疗效果

Returns:

个体处理效应 (ITE), 维度=nx1

或带有结果 [Y_hat(X|T=0), Y_hat(X|T=1), ITE] 的 ITE, 维度=nx3

Return type:

(np.matrix)

set_fit_request(*, sample_weight: bool | None | str = '$UNCHANGED$', treatment: bool | None | str = '$UNCHANGED$') CausalRandomForestRegressor

传递给fit方法的请求元数据。

请注意,此方法仅在 enable_metadata_routing=True(参见sklearn.set_config())时相关。 请参阅用户指南了解路由机制的工作原理。

每个参数的选项是:

  • True: 请求元数据,并在提供时传递给 fit。如果未提供元数据,则忽略该请求。

  • False: 不请求元数据,元估计器不会将其传递给 fit

  • None: 不请求元数据,如果用户提供了元数据,元估计器将引发错误。

  • str: 元数据应使用此给定的别名传递给元估计器,而不是原始名称。

默认值(sklearn.utils.metadata_routing.UNCHANGED)保留现有的请求。这允许您更改某些参数的请求,而不更改其他参数。

在版本1.3中添加。

注意

此方法仅在此估计器用作元估计器的子估计器时相关,例如在Pipeline内部使用。否则它没有效果。

Parameters:
  • sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – fit 方法中 sample_weight 参数的元数据路由。

  • treatment (str, True, False, 或 None, default=sklearn.utils.metadata_routing.UNCHANGED) – fit 方法中 treatment 参数的元数据路由。

Returns:

self – 更新后的对象。

Return type:

对象

set_predict_request(*, with_outcomes: bool | None | str = '$UNCHANGED$') CausalRandomForestRegressor

传递给predict方法的请求元数据。

请注意,此方法仅在 enable_metadata_routing=True(参见sklearn.set_config())时相关。 请参阅用户指南了解路由机制的工作原理。

每个参数的选项是:

  • True: 请求元数据,并在提供时传递给 predict。如果未提供元数据,则忽略该请求。

  • False: 不请求元数据,元估计器不会将其传递给 predict

  • None: 不请求元数据,如果用户提供了元数据,元估计器将引发错误。

  • str: 元数据应使用此给定的别名传递给元估计器,而不是原始名称。

默认值(sklearn.utils.metadata_routing.UNCHANGED)保留现有的请求。这允许您更改某些参数的请求,而不更改其他参数。

在版本1.3中添加。

注意

此方法仅在此估计器用作元估计器的子估计器时相关,例如在Pipeline内部使用。否则它没有效果。

Parameters:

with_outcomes (str, True, False, 或 None, default=sklearn.utils.metadata_routing.UNCHANGED) – predictwith_outcomes 参数的元数据路由。

Returns:

self – 更新后的对象。

Return type:

对象

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') CausalRandomForestRegressor

传递给score方法的请求元数据。

请注意,此方法仅在 enable_metadata_routing=True(参见sklearn.set_config())时相关。 请参阅用户指南了解路由机制的工作原理。

每个参数的选项是:

  • True: 请求元数据,并在提供时传递给 score。如果未提供元数据,则忽略该请求。

  • False: 不请求元数据,元估计器不会将其传递给 score

  • None: 不请求元数据,如果用户提供了元数据,元估计器将引发错误。

  • str: 元数据应使用此给定的别名传递给元估计器,而不是原始名称。

默认值(sklearn.utils.metadata_routing.UNCHANGED)保留现有的请求。这允许您更改某些参数的请求,而不更改其他参数。

在版本1.3中添加。

注意

此方法仅在此估计器用作元估计器的子估计器时相关,例如在Pipeline内部使用。否则它没有效果。

Parameters:

sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – scoresample_weight 参数的元数据路由。

Returns:

self – 更新后的对象。

Return type:

对象

class causalml.inference.tree.CausalTreeRegressor(*, criterion: str = 'causal_mse', splitter: str = 'best', alpha: float = 0.05, control_name: int | str = 0, max_depth: int | None = None, min_samples_split: int | float = 60, min_weight_fraction_leaf: float = 0.0, max_features: int | float | str | None = None, max_leaf_nodes: int | None = None, min_impurity_decrease: float = -inf, ccp_alpha: float = 0.0, groups_penalty: float = 0.5, min_samples_leaf: int = 100, random_state: int | None = None, groups_cnt: bool = False, groups_cnt_mode: str = 'nodes')[source]

基础类:RegressorMixin, BaseCausalDecisionTree

一个因果树回归器类。 因果树是一种决策树回归器,具有处理效果的分割标准。 详细信息可在Athey and Imbens (2015)中找到。

bootstrap(X: ndarray, treatment: ndarray, y: ndarray, sample_size: int, seed: int) ndarray[source]

运行单个引导程序。

在引导样本上拟合,然后在整个群体上进行预测。

Parameters:
  • X (np.ndarray) – 特征矩阵

  • treatment (np.ndarray) – 一个治疗向量

  • y (np.ndarray) – 结果向量

  • sample_size (int) – 自举样本大小

  • seed – (int): 引导种子

Returns:

引导预测

Return type:

(np.ndarray)

bootstrap_pool(**kw)
estimate_ate(X: ndarray, treatment: ndarray, y: ndarray) tuple[source]

估计平均处理效果(ATE)。 :param X: 特征矩阵 :type X: np.matrix :param treatment: 处理向量 :type treatment: np.array :param y: 结果向量 :type y: np.array

Returns:

元组,ATE估计的均值和置信区间(LB, UB)。

fit(X: ndarray, treatment: ndarray, y: ndarray, sample_weight: ndarray | None = None, check_input=False)[source]

拟合CausalTreeRegressor :param X: 特征矩阵 :type X: np.ndarray :param treatment: 处理向量 :type treatment: np.ndarray :param y: 结果向量 :type y: np.ndarray :param sample_weight: 样本权重 :type sample_weight: np.ndarray :param check_input: 默认=False :type check_input: bool, 可选

Returns:

自身

fit_predict(X: ndarray, treatment: ndarray, y: ndarray, return_ci: bool = False, n_bootstraps: int = 1000, bootstrap_size: int = 10000, n_jobs: int = 1, verbose: bool = False) tuple[source]

拟合因果树模型并预测处理效果。

Parameters:
  • X (np.matrix) – 特征矩阵

  • treatment (np.array) – 一个治疗向量

  • y (np.array) – 一个结果向量

  • return_ci (bool) – 是否返回置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

  • n_jobs (int) – 用于引导的作业数量

  • verbose (str) – 是否输出进度日志

Returns:

  • te (numpy.ndarray): 治疗效果的预测。

  • te_lower (numpy.ndarray, 可选): 治疗效果的下限

  • te_upper (numpy.ndarray, 可选): 治疗效果的上限

Return type:

(元组)

predict(X: ndarray, with_outcomes: bool = False, check_input=True) ndarray[source]

预测个体治疗效果

Parameters:
  • X (np.matrix) – 特征矩阵

  • with_outcomes (bool) – 包含结果 Y_hat(X|T=0), Y_hat(X|T=1) 以及个体治疗效果

  • check_input (bool) – 允许绕过多个输入检查。

Returns:

个体处理效应 (ITE), 维度=nx1

或带有结果 [Y_hat(X|T=0), Y_hat(X|T=1), ITE] 的 ITE, 维度=nx3

Return type:

(np.matrix)

set_fit_request(*, check_input: bool | None | str = '$UNCHANGED$', sample_weight: bool | None | str = '$UNCHANGED$', treatment: bool | None | str = '$UNCHANGED$') CausalTreeRegressor

传递给fit方法的请求元数据。

请注意,此方法仅在 enable_metadata_routing=True(参见sklearn.set_config())时相关。 请参阅用户指南了解路由机制的工作原理。

每个参数的选项是:

  • True: 请求元数据,并在提供时传递给 fit。如果未提供元数据,则忽略该请求。

  • False: 不请求元数据,元估计器不会将其传递给 fit

  • None: 不请求元数据,如果用户提供了元数据,元估计器将引发错误。

  • str: 元数据应使用此给定的别名传递给元估计器,而不是原始名称。

默认值(sklearn.utils.metadata_routing.UNCHANGED)保留现有的请求。这允许您更改某些参数的请求,而不更改其他参数。

在版本1.3中添加。

注意

此方法仅在此估计器用作元估计器的子估计器时相关,例如在Pipeline内部使用。否则它没有效果。

Parameters:
  • check_input (str, True, False, 或 None, default=sklearn.utils.metadata_routing.UNCHANGED) – fit 方法中 check_input 参数的元数据路由。

  • sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – fit 方法中 sample_weight 参数的元数据路由。

  • treatment (str, True, False, 或 None, default=sklearn.utils.metadata_routing.UNCHANGED) – fit 方法中 treatment 参数的元数据路由。

Returns:

self – 更新后的对象。

Return type:

对象

set_predict_request(*, check_input: bool | None | str = '$UNCHANGED$', with_outcomes: bool | None | str = '$UNCHANGED$') CausalTreeRegressor

传递给predict方法的请求元数据。

请注意,此方法仅在 enable_metadata_routing=True(参见sklearn.set_config())时相关。 请参阅用户指南了解路由机制的工作原理。

每个参数的选项是:

  • True: 请求元数据,并在提供时传递给 predict。如果未提供元数据,则忽略该请求。

  • False: 不请求元数据,元估计器不会将其传递给 predict

  • None: 不请求元数据,如果用户提供了元数据,元估计器将引发错误。

  • str: 元数据应使用此给定的别名传递给元估计器,而不是原始名称。

默认值(sklearn.utils.metadata_routing.UNCHANGED)保留现有的请求。这允许您更改某些参数的请求,而不更改其他参数。

在版本1.3中添加。

注意

此方法仅在此估计器用作元估计器的子估计器时相关,例如在Pipeline内部使用。否则它没有效果。

Parameters:
  • check_input (str, True, False, 或 None, default=sklearn.utils.metadata_routing.UNCHANGED) – check_input 参数在 predict 中的元数据路由。

  • with_outcomes (str, True, False, 或 None, default=sklearn.utils.metadata_routing.UNCHANGED) – predictwith_outcomes 参数的元数据路由。

Returns:

self – 更新后的对象。

Return type:

对象

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') CausalTreeRegressor

传递给score方法的请求元数据。

请注意,此方法仅在 enable_metadata_routing=True(参见sklearn.set_config())时相关。 请参阅用户指南了解路由机制的工作原理。

每个参数的选项是:

  • True: 请求元数据,并在提供时传递给 score。如果未提供元数据,则忽略该请求。

  • False: 不请求元数据,元估计器不会将其传递给 score

  • None: 不请求元数据,如果用户提供了元数据,元估计器将引发错误。

  • str: 元数据应使用此给定的别名传递给元估计器,而不是原始名称。

默认值(sklearn.utils.metadata_routing.UNCHANGED)保留现有的请求。这允许您更改某些参数的请求,而不更改其他参数。

在版本1.3中添加。

注意

此方法仅在此估计器用作元估计器的子估计器时相关,例如在Pipeline内部使用。否则它没有效果。

Parameters:

sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – scoresample_weight 参数的元数据路由。

Returns:

self – 更新后的对象。

Return type:

对象

class causalml.inference.tree.DecisionTree(classes_, col=-1, value=None, trueBranch=None, falseBranch=None, results=None, summary=None, maxDiffTreatment=None, maxDiffSign=1.0, nodeSummary=None, backupResults=None, bestTreatment=None, upliftScore=None, matchScore=None)

基础:object

树节点类

树节点类,用于包含树节点的所有统计信息。

Parameters:
  • classes (list of str) – 控制和治疗组名称的列表。

  • col (int, 可选 (默认值 = -1)) – 用于将树节点拆分为子节点的列索引。

  • value (float, optional (default = None)) – 用于将树节点分割为子节点的特征列的值。

  • trueBranch (object of DecisionTree) – 真分支树节点(特征 > 值)。

  • falseBranch (object of DecisionTree) – 假分支树节点(特征 > 值)。

  • results (list of float) – 树节点中每个对照组和治疗组的分类概率 P(Y=1|T)。

  • 摘要 (列表列表) – 树节点的摘要统计信息,包括不纯度、样本大小、提升分数等。

  • maxDiffTreatment (int) – 生成治疗组和对照组之间最大差异的治疗索引。

  • maxDiffSign (float) – 最大差异的符号(1. 或 -1.)。

  • nodeSummary (list of list) – 树节点的摘要统计信息 [P(Y=1|T), N(T)],其中 y_mean 代表目标指标的平均值,n 是样本大小。

  • backupResults (list of float) – 父节点中每个控制组和实验组的正概率。父节点信息作为子节点的备份,如果无法从子节点计算出有效的统计信息,在某些情况下将使用父节点信息。

  • bestTreatment (int) – 提供最佳提升(治疗效果)的处理索引。

  • upliftScore (list) – 该节点的提升分数:[max_Diff, p_value],其中 max_Diff 代表最大处理效果,p_value 代表处理效果的 p 值。

  • matchScore (float) – 通过使用验证数据集或测试数据集填充训练好的树得到的提升分数。

class causalml.inference.tree.UpliftRandomForestClassifier(control_name, n_estimators=10, max_features=10, random_state=None, max_depth=5, min_samples_leaf=100, min_samples_treatment=10, n_reg=10, early_stopping_eval_diff_scale=1, evaluationFunction='KL', normalization=True, honesty=False, estimation_sample_size=0.5, n_jobs=-1, joblib_prefer: unicode = 'threads')

基础:object

用于分类任务的提升随机森林。

Parameters:
  • n_estimators (整数, 可选 (默认=10)) – 提升随机森林中树的数量。

  • evaluationFunction (string) – 从以下模型中选择一个:'KL', 'ED', 'Chi', 'CTS', 'DDP', 'IT', 'CIT', 'IDDP'。

  • max_features (int, 可选 (默认=10)) – 在寻找最佳分割时考虑的特征数量。

  • random_state (int, RandomState 实例None (默认=None)) – 一个随机种子或 np.random.RandomState 用于控制构建树和森林时的随机性。

  • max_depth (int, optional (default=5)) – 树的最大深度。

  • min_samples_leaf (int, optional (default=100)) – 叶子节点分裂所需的最小样本数。

  • min_samples_treatment (int, optional (default=10)) – 实验组在叶节点上分裂所需的最小样本数。

  • n_reg (int, optional (default=10)) – Rzepakowski等人在2012年定义的正则化参数,表示父节点对子节点影响的权重(以样本大小为单位),仅对‘KL’、‘ED’、‘Chi’、‘CTS’方法有效。

  • early_stopping_eval_diff_scale (float, optional (default=1)) – 如果训练和验证的提升分数差异大于 min(train_uplift_score,valid_uplift_score)/early_stopping_eval_diff_scale,则停止。

  • control_name (string) – 控制组的名称(其他实验组将被视为处理组)

  • normalization (boolean, optional (default=True)) – Rzepakowski等人2012年定义的归一化因子,用于校正具有大量分割和不平衡处理和控制分割的测试

  • 诚实性 (布尔型 (默认=False)) – 如果为True,则使用基于“Athey, S., & Imbens, G. (2016). 异质因果效应的递归分区。”的诚实方法。

  • estimation_sample_size (float (default=0.5)) – 如果 honesty == True,用于估计叶子中CATE得分的样本大小。

  • n_jobs (int, optional (default=-1)) – 定义需要创建多少并行作业的并行化参数。 这被传递给joblib库,用于并行化提升树的创建和预测。

  • joblib_prefer (str, optional (default="threads")) – joblib的首选后端(作为prefer传递给joblib.Parallel)。有关有效值,请参阅joblib文档。

  • 输出

  • ----------

  • df_res (pandas dataframe) – 一个用户级别的结果数据框,包含估计的个体治疗效果。

static bootstrap(X, treatment, y, X_val, treatment_val, y_val, tree)
fit(X, treatment, y, X_val=None, treatment_val=None, y_val=None)

拟合UpliftRandomForestClassifier。

Parameters:
  • X (ndarray, shape = [num_samples, num_features]) – 用于训练提升模型的协变量的ndarray。

  • treatment (array-like, shape = [num_samples]) – 一个包含每个单元的治疗组的数组。

  • y (数组形式, 形状 = [样本数量]) – 一个包含每个单位感兴趣结果的数组。

  • X_val (ndarray, shape = [num_samples, num_features]) – 用于验证提升模型的协变量的ndarray。

  • treatment_val (array-like, shape = [num_samples]) – 一个包含每个单位的验证治疗组的数组。

  • y_val (array-like, shape = [num_samples]) – 一个包含每个单元的验证结果的数组。

predict(X, full_output=False)

返回推荐的治疗组和在使用推荐治疗组条件下的预测最优概率。

Parameters:
  • X (ndarray, shape = [num_samples, num_features]) – 用于训练提升模型的协变量的ndarray。

  • full_output (bool, 可选 (默认=False)) – 是否让UpliftTree算法返回upliftScores, pred_nodes 以及推荐的治疗组和治疗组中的p_hat。

Returns:

  • y_pred_list (ndarray, shape = (num_samples, num_treatments])) – 一个包含每个样本的每个治疗组的预测治疗效果的ndarray

  • df_res (DataFrame, shape = [num_samples, (num_treatments * 2 + 3)]) – 如果full_outputTrue,则是一个包含每个治疗组和对照组的预测结果、每个治疗组的治疗效果、具有最高治疗效应的治疗组以及每个样本的最大治疗效应的DataFrame。

class causalml.inference.tree.UpliftTreeClassifier(control_name, max_features=None, max_depth=3, min_samples_leaf=100, min_samples_treatment=10, n_reg=100, early_stopping_eval_diff_scale=1, evaluationFunction='KL', normalization=True, honesty=False, estimation_sample_size=0.5, random_state=None)

基础:object

用于分类任务的提升树分类器。

提升树分类器通过修改分类树中的损失函数来估计个体处理效果。

提升树分类器用于提升随机森林中构建森林中的树。

Parameters:
  • evaluationFunction (string) – 从以下模型中选择一个:'KL', 'ED', 'Chi', 'CTS', 'DDP', 'IT', 'CIT', 'IDDP'。

  • max_features (int, optional (default=None)) – 在寻找最佳分割时考虑的特征数量。

  • max_depth (int, 可选 (默认=3)) – 树的最大深度。

  • min_samples_leaf (int, optional (default=100)) – 叶子节点分裂所需的最小样本数。

  • min_samples_treatment (int, optional (default=10)) – 实验组在叶节点上分裂所需的最小样本数。

  • n_reg (int, optional (default=100)) – Rzepakowski等人在2012年定义的正则化参数,表示父节点对子节点影响的权重(以样本大小为单位),仅对‘KL’、‘ED’、‘Chi’、‘CTS’方法有效。

  • early_stopping_eval_diff_scale (float, optional (default=1)) – 如果训练和验证的提升分数差异大于 min(train_uplift_score,valid_uplift_score)/early_stopping_eval_diff_scale,则停止。

  • control_name (string) – 控制组的名称(其他实验组将被视为处理组)。

  • 归一化 (布尔值, 可选 (默认=True)) – Rzepakowski等人2012年定义的归一化因子,用于校正具有大量分割和不平衡处理与控制分割的测试。

  • 诚实性 (bool (默认=False)) – 如果基于“Athey, S., & Imbens, G. (2016). 异质因果效应的递归划分”的诚实方法应被使用,则为True。如果使用‘IDDP’作为评估函数,此参数将自动设置为true。

  • estimation_sample_size (float (default=0.5)) – 如果 honesty == True,用于估计叶子中CATE得分的样本大小。

  • random_state (int, RandomState 实例None (默认=None)) – 一个随机种子或 np.random.RandomState 用于控制构建树时的随机性。

static arr_evaluate_CIT(cur_node_summary_p, cur_node_summary_n, left_node_summary_p, left_node_summary_n, right_node_summary_p, right_node_summary_n)

计算似然比检验统计量作为给定节点的分割评估标准

注意:n_class 应为 2。

Parameters:
  • cur_node_summary_p (array of shape [n_class]) – 类型为 numpy.double。 当前节点的控制和治疗组的每个正概率,即 [P(Y=1|T=i)…]

  • cur_node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 当前节点的每个控制和治疗组的计数,即 [N(T=i)…]

  • left_node_summary_p (array of shape [n_class]) – 类型为 numpy.double。 左节点的每个控制和治疗组的正概率,即 [P(Y=1|T=i)…]

  • left_node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 左节点中每个控制和治疗组的计数,即 [N(T=i)…]

  • right_node_summary_p (array of shape [n_class]) – 类型为 numpy.double。 右节点中每个控制和治疗组的正概率,即 [P(Y=1|T=i)…]

  • right_node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 右节点中每个控制和治疗组的计数,即 [N(T=i)…]

Returns:

lrt

Return type:

似然比检验统计量

static arr_evaluate_CTS(node_summary_p, node_summary_n)

计算CTS(条件治疗选择)作为给定节点的分割评估标准。

Parameters:
  • node_summary_p (array of shape [n_class]) – 类型为 numpy.double。 当前节点的控制和治疗组的正概率,即 [P(Y=1|T=i)…]

  • node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 当前节点的每个控制和治疗组的计数,即 [N(T=i)…]

Returns:

d_res

Return type:

CTS 分数

static arr_evaluate_Chi(node_summary_p, node_summary_n)

计算卡方统计量作为给定节点的分割评估标准。

Parameters:
  • node_summary_p (array of shape [n_class]) – 类型为 numpy.double。 当前节点的控制和治疗组的每个正概率,即 [P(Y=1|T=i)…]

  • node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 当前节点的每个控制和治疗组的计数,即 [N(T=i)…]

Returns:

d_res

Return type:

卡方

static arr_evaluate_DDP(node_summary_p, node_summary_n)

计算给定节点的分割评估标准的Delta P。

Parameters:
  • node_summary_p (array of shape [n_class]) – 类型为 numpy.double。 当前节点的控制和治疗组的每个正概率,即 [P(Y=1|T=i)…]

  • node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 当前节点的每个控制和治疗组的计数,即 [N(T=i)…]

Returns:

d_res

Return type:

Delta P

static arr_evaluate_ED(node_summary_p, node_summary_n)

计算欧几里得距离作为给定节点的分割评估标准。

Parameters:
  • node_summary_p (array of shape [n_class]) – 类型为 numpy.double。 当前节点的控制和治疗组的正概率,即 [P(Y=1|T=i)…]

  • node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 当前节点的每个控制和治疗组的计数,即 [N(T=i)…]

Returns:

d_res

Return type:

欧几里得距离

static arr_evaluate_IDDP(node_summary_p, node_summary_n)

计算给定节点的分割评估标准的Delta P。

Parameters:
  • node_summary_p (array of shape [n_class]) – 类型为 numpy.double。 当前节点的控制和治疗组的正概率,即 [P(Y=1|T=i)…]

  • node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 当前节点的每个控制和治疗组的计数,即 [N(T=i)…]

Returns:

d_res

Return type:

Delta P

static arr_evaluate_IT(left_node_summary_p, left_node_summary_n, right_node_summary_p, right_node_summary_n)

计算平方T统计量作为给定节点的分割评估标准

注意:n_class 应为 2。

Parameters:
  • left_node_summary_p (array of shape [n_class]) – 类型为 numpy.double。 左节点的每个控制和治疗组的正概率,即 [P(Y=1|T=i)…]

  • left_node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 左节点中每个控制和治疗组的计数,即 [N(T=i)…]

  • right_node_summary_p (array of shape [n_class]) – 类型为 numpy.double。 右节点中每个控制和治疗组的正概率,即 [P(Y=1|T=i)…]

  • right_node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 右节点中每个控制和治疗组的计数,即 [N(T=i)…]

Returns:

g_s

Return type:

平方T统计量

static arr_evaluate_KL(node_summary_p, node_summary_n)

计算KL散度作为给定节点的分割评估标准。 已修改以接受新的节点摘要格式。

Parameters:
  • node_summary_p (array of shape [n_class]) – 类型为 numpy.double。 当前节点的控制和治疗组的每个正概率,即 [P(Y=1|T=i)…]

  • node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 当前节点的每个控制和治疗组的计数,即 [N(T=i)…]

Returns:

d_res

Return type:

KL散度

arr_normI(cur_node_summary_n, left_node_summary_n, alpha: float = 0.9, currentDivergence: float = 0.0) float

归一化因子。

Parameters:
  • cur_node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 当前节点的每个控制和治疗组的计数,即 [N(T=i)…]

  • left_node_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 左节点中每个控制和治疗组的计数,即 [N(T=i)…]

  • alpha (float) – 用于平衡不同归一化部分的权重。

Returns:

norm_res – 归一化因子。

Return type:

浮点数

static classify(observations, tree, dataMissing=False)

根据树对观测值进行分类(预测)。

Parameters:
  • observations (list of list) – 训练数据的内部数据格式(结合了X、Y、treatment)。

  • dataMissing (boolean, optional (default = False)) – 一个指示数据是否缺失的标志。

Returns:

叶子节点中的结果。

Return type:

tree.results, tree.upliftScore

static divideSet(X, treatment_idx, y, column, value)

树节点分割。

Parameters:
  • X (ndarray, shape = [num_samples, num_features]) – 用于训练提升模型的协变量的ndarray。

  • treatment_idx (array-like, shape = [num_samples]) – 一个包含每个单元的治疗组索引的数组。

  • y (数组形式, 形状 = [样本数量]) – 一个包含每个单位感兴趣结果的数组。

  • (整数) – 用于分割数据的列。

  • value (floatint) – 列中用于分割数据的值。

Returns:

(X_l, X_r, treatment_l, treatment_r, y_l, y_r) – 左节点和右节点的协变量、处理和结果。

Return type:

ndarray列表

static divideSet_len(X, treatment_idx, y, column, value)

树节点分割。

修改自dividedSet(),但返回len(X_l)和len(X_r)而不是分割后的X_l和X_r,以避免一些开销,旨在用于寻找分割点。在找到最佳分割点后,可以分割以找到X_l和X_r。

Parameters:
  • X (ndarray, shape = [num_samples, num_features]) – 用于训练提升模型的协变量的ndarray。

  • treatment_idx (array-like, shape = [num_samples]) – 一个包含每个单元的治疗组索引的数组。

  • y (数组形式, 形状 = [样本数量]) – 一个包含每个单位感兴趣结果的数组。

  • (整数) – 用于分割数据的列。

  • value (floatint) – 列中用于分割数据的值。

Returns:

(len_X_l, len_X_r, treatment_l, treatment_r, y_l, y_r) – 左节点和右节点的协变量行数、处理和结果。

Return type:

ndarray列表

static evaluate_CIT(currentNodeSummary, leftNodeSummary, rightNodeSummary, y_l, y_r, w_l, w_r, y, w)

计算似然比检验统计量作为给定节点的分割评估标准 :param currentNodeSummary: 父节点的汇总统计 :type currentNodeSummary: 列表的列表 :param leftNodeSummary: 左节点的汇总统计 :type leftNodeSummary: 列表的列表 :param rightNodeSummary: 右节点的汇总统计 :type rightNodeSummary: 列表的列表 :param y_l: 包含左节点中每个单位感兴趣结果的数组 :type y_l: 类似数组, 形状 = [num_samples] :param y_r: 包含右节点中每个单位感兴趣结果的数组 :type y_r: 类似数组, 形状 = [num_samples] :param w_l: 包含左节点中每个单位处理的数组 :type w_l: 类似数组, 形状 = [num_samples] :param w_r: 包含右节点中每个单位处理的数组 :type w_r: 类似数组, 形状 = [num_samples] :param y: 包含每个单位感兴趣结果的数组 :type y: 类似数组, 形状 = [num_samples] :param w: 包含每个单位处理的数组 :type w: 类似数组, 形状 = [num_samples]

Returns:

lrt

Return type:

似然比检验统计量

static evaluate_CTS(nodeSummary)

计算CTS(条件治疗选择)作为给定节点的分割评估标准。

Parameters:

nodeSummary (list of list) – 树节点摘要统计信息,[P(Y=1|T), N(T)],由tree_node_summary()方法生成。

Returns:

d_res

Return type:

CTS 分数

static evaluate_Chi(nodeSummary)

计算卡方统计量作为给定节点的分割评估标准。

Parameters:

nodeSummary (dictionary) – 树节点摘要统计信息,由 tree_node_summary() 方法生成。

Returns:

d_res

Return type:

卡方

static evaluate_DDP(nodeSummary)

计算给定节点的分割评估标准的Delta P。

Parameters:

nodeSummary (list of list) – 树节点摘要统计信息,[P(Y=1|T), N(T)],由tree_node_summary()方法生成。

Returns:

d_res

Return type:

Delta P

static evaluate_ED(nodeSummary)

计算欧几里得距离作为给定节点的分割评估标准。

Parameters:

nodeSummary (dictionary) – 树节点摘要统计信息,由 tree_node_summary() 方法生成。

Returns:

d_res

Return type:

欧几里得距离

static evaluate_IDDP(nodeSummary)

计算给定节点的分割评估标准的Delta P。

Parameters:
  • nodeSummary (dictionary) – 树节点摘要统计信息,由 tree_node_summary() 方法生成。

  • control_name (string) – 控制组名称。

Returns:

d_res

Return type:

Delta P

static evaluate_IT(leftNodeSummary, rightNodeSummary, w_l, w_r)

计算平方T统计量作为给定节点的分割评估标准

Parameters:
  • leftNodeSummary (list of list) – 左侧节点的汇总统计信息。

  • rightNodeSummary (list of list) – 右侧节点的汇总统计信息。

  • w_l (array-like, shape = [num_samples]) – 一个包含左节点中每个单元处理的数组

  • w_r (array-like, shape = [num_samples]) – 一个数组,包含右节点中每个单元的处理

Returns:

g_s

Return type:

平方T统计量

static evaluate_KL(nodeSummary)

计算KL散度作为给定节点的分割评估标准。

Parameters:

nodeSummary (列表列表) – 树节点摘要统计信息,[P(Y=1|T), N(T)],由tree_node_summary()方法生成。

Returns:

d_res

Return type:

KL散度

fill(X, treatment, y)

将数据填充到现有的树中。 这是一个高级函数,用于将原始数据输入转换为较低级别的数据输入(列表的列表和树)。

Parameters:
  • X (ndarray, shape = [num_samples, num_features]) – 用于训练提升模型的协变量的ndarray。

  • treatment (array-like, shape = [num_samples]) – 一个包含每个单元的治疗组的数组。

  • y (数组形式, 形状 = [样本数量]) – 一个包含每个单位感兴趣结果的数组。

Returns:

self

Return type:

对象

fillTree(X, treatment_idx, y, tree)

将数据填充到现有的树中。 这是一个较低级别的函数,用于执行树填充任务。

Parameters:
  • X (ndarray, shape = [num_samples, num_features]) – 用于训练提升模型的协变量的ndarray。

  • treatment_idx (array-like, shape = [num_samples]) – 一个包含每个单元的治疗组索引的数组。

  • y (数组形式, 形状 = [样本数量]) – 一个包含每个单位感兴趣结果的数组。

  • tree (object) – DecisionTree类的对象

Returns:

self

Return type:

对象

fit(X, treatment, y, X_val=None, treatment_val=None, y_val=None)

拟合提升模型。

Parameters:
  • X (ndarray, shape = [num_samples, num_features]) – 用于训练提升模型的协变量的ndarray。

  • treatment (array-like, shape = [num_samples]) – 一个包含每个单元的治疗组的数组。

  • y (数组形式, 形状 = [样本数量]) – 一个包含每个单位感兴趣结果的数组。

Returns:

self

Return type:

对象

group_uniqueCounts(treatment_idx, y)

按实验组计算样本大小。

Parameters:
  • treatment_idx (array-like, shape = [num_samples]) – 一个包含每个单元的治疗组索引的数组。

  • y (数组形式, 形状 = [样本数量]) – 一个包含每个单位感兴趣结果的数组。

Returns:

results – 每个对照组和治疗组的负面和正面结果样本大小。

Return type:

列表的列表

growDecisionTreeFrom(X, treatment_idx, y, X_val, treatment_val_idx, y_val, early_stopping_eval_diff_scale=1, max_depth=10, min_samples_leaf=100, depth=1, min_samples_treatment=10, n_reg=100, parentNodeSummary_p=None)

训练提升决策树。

Parameters:
  • X (ndarray, shape = [num_samples, num_features]) – 用于训练提升模型的协变量的ndarray。

  • treatment_idx (array-like, shape = [num_samples]) – 一个包含每个单元的治疗组索引的数组。 数据类型应为 numpy.int8。

  • y (数组形式, 形状 = [样本数量]) – 一个包含每个单位感兴趣结果的数组。

  • X_val (ndarray, shape = [num_samples, num_features]) – 用于验证提升模型的协变量的ndarray。

  • treatment_val_idx (array-like, shape = [num_samples]) – 一个包含每个单位的验证治疗组索引的数组。

  • y_val (array-like, shape = [num_samples]) – 一个包含每个单元的验证结果的数组。

  • max_depth (int, optional (default=10)) – 树的最大深度。

  • min_samples_leaf (int, optional (default=100)) – 叶子节点分裂所需的最小样本数。

  • depth (int, optional (default = 1)) – 当前深度。

  • min_samples_treatment (int, optional (default=10)) – 实验组在叶节点上分裂所需的最小样本数。

  • n_reg (int, optional (default=10)) – Rzepakowski等人在2012年定义的正则化参数, 表示父节点对子节点影响的权重(以样本大小为单位),仅对‘KL’、‘ED’、‘Chi’、‘CTS’方法有效。

  • parentNodeSummary_p (array-like, shape [n_class]) – 父树节点的节点摘要概率统计。

Return type:

DecisionTree类的对象

honestApproach(X_est, T_est, Y_est)

应用基于“Athey, S., & Imbens, G. (2016). Recursive partitioning for heterogeneous causal effects.”的诚实方法。 :param X_est: 用于计算决策树叶节点中无偏估计的协变量的ndarray。 :type X_est: ndarray, shape = [num_samples, num_features] :param T_est: 包含每个单元治疗组的数组。 :type T_est: array-like, shape = [num_samples] :param Y_est: 包含每个单元感兴趣结果的数组。 :type Y_est: array-like, shape = [num_samples]

normI(n_c: int, n_c_left: int, n_t: list, n_t_left: list, alpha: float = 0.9, currentDivergence: float = 0.0) float

归一化因子。

Parameters:
  • currentNodeSummary (list of list) – 当前树节点的摘要统计信息,[P(Y=1|T), N(T)]。

  • leftNodeSummary (list of list) – 左树节点的摘要统计,[P(Y=1|T), N(T)]。

  • alpha (float) – 用于平衡不同归一化部分的权重。

Returns:

norm_res – 归一化因子。

Return type:

浮点数

predict(X)

返回推荐的治疗组和在使用推荐治疗组条件下的预测最优概率。

Parameters:

X (ndarray, shape = [num_samples, num_features]) – 用于训练提升模型的协变量的ndarray。

Returns:

pred – 一个跨治疗的预测治疗效果的ndarray。

Return type:

ndarray, 形状 = [样本数量, 处理数量]

prune(X, treatment, y, minGain=0.0001, rule='maxAbsDiff')

修剪提升模型。 :param X: 用于训练提升模型的协变量数组。 :type X: ndarray, 形状 = [num_samples, num_features] :param treatment: 包含每个单元治疗组的数组。 :type treatment: 类数组, 形状 = [num_samples] :param y: 包含每个单元感兴趣结果的数组。 :type y: 类数组, 形状 = [num_samples] :param minGain: 树节点分裂所需的最小增益。子节点

如果实际分割增益小于最小增益,则修剪树枝。

Parameters:

规则 (字符串, 可选 (默认值 = 'maxAbsDiff')) – 剪枝规则。支持的值为‘maxAbsDiff’用于优化最大绝对差异,以及‘bestUplift’用于优化节点大小加权的处理效果。

Returns:

self

Return type:

对象

pruneTree(X, treatment_idx, y, tree, rule='maxAbsDiff', minGain=0.0, n_reg=0, parentNodeSummary=None)

在提升模型中修剪单个树节点。 :param X: 用于训练提升模型的协变量数组。 :type X: ndarray, shape = [num_samples, num_features] :param treatment_idx: 包含每个单元处理组索引的数组。 :type treatment_idx: array-like, shape = [num_samples] :param y: 包含每个单元感兴趣结果的数组。 :type y: array-like, shape = [num_samples] :param rule: 修剪规则。支持的值为‘maxAbsDiff’用于优化最大绝对差异,和

‘bestUplift’ 用于优化节点大小加权的处理效果。

Parameters:
  • minGain (float, optional (default = 0.)) – 树节点分裂所需的最小增益。如果实际分裂增益小于最小增益,则修剪子树枝。

  • n_reg (int, optional (default=0)) – Rzepakowski等人2012年定义的正则化参数,表示父节点对子节点影响的权重(以样本大小为单位),仅对‘KL’、‘ED’、‘Chi’、‘CTS’方法有效。

  • parentNodeSummary (list of list, optional (default = None)) – 节点摘要统计信息,父树节点的[P(Y=1|T), N(T)]。

Returns:

self

Return type:

对象

tree_node_summary(treatment_idx, y, min_samples_treatment=10, n_reg=100, parentNodeSummary=None)

树节点汇总统计。

Parameters:
  • treatment_idx (array-like, shape = [num_samples]) – 一个包含每个单元的治疗组索引的数组。

  • y (数组形式, 形状 = [样本数量]) – 一个包含每个单位感兴趣结果的数组。

  • min_samples_treatment (int, optional (default=10)) – 实验组在叶节点处分裂所需的最小样本数。

  • n_reg (int, optional (default=10)) – Rzepakowski等人在2012年定义的正则化参数, 表示父节点对子节点影响的权重(以样本大小为单位),仅对‘KL’、‘ED’、‘Chi’、‘CTS’方法有效。

  • parentNodeSummary (list of list) – 父节点中每个对照组和治疗组的正概率和样本大小。

Returns:

nodeSummary – 当前节点中每个对照组和治疗组的正概率和样本大小。

Return type:

列表的列表

static tree_node_summary_from_counts(group_count_arr, out_summary_p, out_summary_n, parentNodeSummary_p, has_parent_summary, min_samples_treatment=10, n_reg=100)

树节点汇总统计。

从tree_node_summary_to_arr修改而来,使用不同的格式来总结,并基于已经计算的组数进行计算。不使用[[P(Y=1|T=0), N(T=0)], [P(Y=1|T=1), N(T=1)], …],而是使用两个数组[N(T=i)…]和[P(Y=1|T=i)…]。

Parameters:
  • group_count_arr (array of shape [2*n_class]) – 类型为 numpy.int32。 分组计数,其中条目 2*i 是 N(Y=0, T=i), 条目 2*i+1 是 N(Y=1, T=i)。

  • out_summary_p (array of shape [n_class]) – 类型为 numpy.double。 用于填充当前节点的控制和治疗组的每个正概率。

  • out_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 用于填充当前节点的控制和治疗组的计数。

  • parentNodeSummary_p (array of shape [n_class]) – 父节点中每个控制组和实验组的正概率。

  • has_parent_summary (bool as int) – 如果为True(非零),则parentNodeSummary_p是一个有效的父节点摘要概率。 如果为False(0),则假设没有父节点摘要,并且不修改parentNodeSummary_p。

  • min_samples_treatment (int, optional (default=10)) – 实验组在叶节点处分裂所需的最小样本数。

  • n_reg (int, optional (default=10)) – Rzepakowski等人在2012年定义的正则化参数, 表示父节点对子节点影响的权重(以样本大小为单位),仅对‘KL’、‘ED’、‘Chi’、‘CTS’方法有效。

Return type:

没有返回值,但会修改 out_summary_p 和 out_summary_n。

static tree_node_summary_to_arr(treatment_idx, y, out_summary_p, out_summary_n, buf_count_arr, parentNodeSummary_p, has_parent_summary, min_samples_treatment=10, n_reg=100)

树节点汇总统计。 从tree_node_summary修改而来,使用不同的汇总格式。 不使用[[P(Y=1|T=0), N(T=0)], [P(Y=1|T=1), N(T=1)], …], 而是使用两个数组[N(T=i)…]和[P(Y=1|T=i)…]。

Parameters:
  • treatment_idx (array-like, shape = [num_samples]) – 一个包含每个单元的治疗组索引的数组。 类型为 numpy.int8。

  • y (数组形式, 形状 = [样本数量]) – 一个包含每个单位感兴趣结果的数组。 类型为 numpy.int8。

  • out_summary_p (array of shape [n_class]) – 类型为 numpy.double。 用于填充当前节点的控制和治疗组的每个正概率。

  • out_summary_n (array of shape [n_class]) – 类型为 numpy.int32。 用于填充当前节点的每个控制和治疗组的计数。

  • buf_count_arr (array of shape [2*n_class]) – 类型为 numpy.int32。 用作 group_uniqueCounts_to_arr 的临时缓冲区。

  • parentNodeSummary_p (array of shape [n_class]) – 父节点中每个控制组和实验组的正概率。

  • has_parent_summary (bool as int) – 如果为True(非零),则parentNodeSummary_p是一个有效的父节点摘要概率。 如果为False(0),则假设没有父节点摘要,并且不修改parentNodeSummary_p。

  • min_samples_treatment (int, optional (default=10)) – 实验组在叶节点处分裂所需的最小样本数。

  • n_reg (int, optional (default=10)) – Rzepakowski等人在2012年定义的正则化参数, 表示父节点对子节点影响的权重(以样本大小为单位),仅对‘KL’、‘ED’、‘Chi’、‘CTS’方法有效。

Return type:

没有返回值,但会修改 out_summary_p 和 out_summary_n。

uplift_classification_results(treatment_idx, y)

树节点中每个处理的分类概率。

Parameters:
  • treatment_idx (array-like, shape = [num_samples]) – 一个包含每个单元的治疗组索引的数组。

  • y (数组形式, 形状 = [样本数量]) – 一个包含每个单位感兴趣结果的数组。

Returns:

res – 每个对照组和治疗组的正概率 P(Y = 1)

Return type:

列表的列表

causalml.inference.tree.cat_continuous(x, granularity='Medium')[source]

根据百分位数对连续变量进行分类(分箱)。

Parameters:
  • x (列表) – 特征值。

  • granularity (string, optional, (default = 'Medium')) – 控制分箱的粒度,可选值为:'High', 'Medium', 'Low'。

Returns:

res – 特征值的百分位数区间列表。

Return type:

列表

causalml.inference.tree.cat_group(dfx, kpix, n_group=10)[source]

分类变量的类别减少

Parameters:
  • dfx (dataframe) – 输入的数据数据框。

  • kpix (string) – 特征的列。

  • n_group (int, optional (default = 10)) – 要保留的顶级类别值的数量,其他类别值将被放入“其他”中。

Return type:

转换后的分类特征值列表。

causalml.inference.tree.cat_transform(dfx, kpix, kpi1)[source]

编码字符串特征。

Parameters:
  • dfx (dataframe) – 输入的dataframe数据。

  • kpix (string) – 特征的列。

  • kpi1 (list) – 特征名称的列表。

Returns:

  • dfx (DataFrame) – 包含编码数据的更新后的数据框。

  • kpi1 (list) – 包含新虚拟特征名称的更新后的特征名称列表。

causalml.inference.tree.cv_fold_index(n, i, k, random_seed=2018)[source]

编码字符串特征。

Parameters:
  • dfx (dataframe) – 输入的数据数据框。

  • kpix (string) – 特征的列。

  • kpi1 (list) – 特征名称的列表。

Returns:

  • dfx (DataFrame) – 包含编码数据的更新后的数据框。

  • kpi1 (list) – 包含新虚拟特征名称的更新后的特征名称列表。

causalml.inference.tree.get_tree_leaves_mask(tree) ndarray[source]

获取树叶子节点的掩码数组 :param tree: CausalTreeRegressor

树对象

Returns: np.ndarray

掩码数组

causalml.inference.tree.kpi_transform(dfx, kpi_combo, kpi_combo_new)[source]

将一系列连续特征转换为分箱特征的特征转换

Parameters:
  • dfx (DataFrame) – 包含特征的DataFrame。

  • kpi_combo (list of string) – 要转换的特征名称列表

  • kpi_combo_new (list of string) – 要分配给转换后特征的新特征名称列表。

Returns:

dfx – 包含新特征的更新后的DataFrame。

Return type:

数据框

causalml.inference.tree.plot_dist_tree_leaves_values(tree: CausalTreeRegressor, title: str = 'Leaves values distribution', figsize: tuple = (5, 5), fontsize: int = 12) None[source]

为树叶子值创建分布图 :param tree: (CausalTreeRegressor), 树对象 :param title: (str), 图表标题 :param figsize: (tuple), 图形大小 :param fontsize: (int), 标题字体大小

返回:无

causalml.inference.tree.uplift_tree_plot(decisionTree, x_names)[source]

将树转换为点图以便绘图。

Parameters:
  • decisionTree (object) – DecisionTree类的对象

  • x_names (列表) – 特征名称列表

Return type:

表示树形图的Dot类。

causalml.inference.tree.uplift_tree_string(decisionTree, x_names)[source]

将树转换为字符串以便打印。

Parameters:
  • decisionTree (object) – DecisionTree类的对象

  • x_names (列表) – 特征名称列表

Return type:

树的字符串表示。

causalml.inference.meta 模块

class causalml.inference.meta.BaseDRLearner(learner=None, control_outcome_learner=None, treatment_outcome_learner=None, treatment_effect_learner=None, ate_alpha=0.05, control_name=0)[source]

基础:BaseLearner

DR-learner回归器类的父类。

DR-learner 使用机器学习模型估计治疗效果。

DR-learner 的详细信息可在 Kennedy (2020) 获取。

estimate_ate(X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000, seed=None, pretrain=False)[source]

估计平均处理效应(ATE)。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()以生成倾向得分。

  • bootstrap_ci (bool) – 是否运行bootstrap以计算置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

  • seed (int) – 用于交叉拟合的随机种子

  • pretrain (bool) – 模型是否已经拟合,默认为 False。

Returns:

ATE估计的均值和置信区间(LB, UB)。

fit(X, treatment, y, p=None, seed=None)[source]

拟合推理模型。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

  • seed (int) – 用于交叉拟合的随机种子

fit_predict(X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True, seed=None)[source]

拟合R学习者的治疗效果和结果模型并预测治疗效果。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

  • return_ci (bool) – 是否返回置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

  • return_components (bool, optional) – 是否分别返回治疗组和对照组的结果

  • verbose (str) – 是否输出进度日志

  • seed (int) – 用于交叉拟合的随机种子

Returns:

治疗效果预测。输出维度:[n_samples, n_treatment]

如果return_ci,返回CATE [n_samples, n_treatment], LB [n_samples, n_treatment], UB [n_samples, n_treatment]

Return type:

(numpy.ndarray)

predict(X, treatment=None, y=None, p=None, return_components=False, verbose=True)[source]

预测治疗效果。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series, 可选) – 一个治疗向量

  • y (np.arraypd.Series, 可选) – 一个结果向量

  • verbose (bool, optional) – 是否输出进度日志

Returns:

治疗效果预测。

Return type:

(numpy.ndarray)

class causalml.inference.meta.BaseDRRegressor(learner=None, control_outcome_learner=None, treatment_outcome_learner=None, treatment_effect_learner=None, ate_alpha=0.05, control_name=0)[source]

基础类: BaseDRLearner

DR-learner回归器类的父类。

class causalml.inference.meta.BaseRClassifier(outcome_learner=None, effect_learner=None, propensity_learner=LogisticRegressionCV(Cs=array([1.00230524, 2.15608891, 4.63802765, 9.97700064]), cv=StratifiedKFold(n_splits=4, random_state=42, shuffle=True), l1_ratios=array([0.001, 0.33366667, 0.66633333, 0.999]), penalty='elasticnet', random_state=42, solver='saga'), ate_alpha=0.05, control_name=0, n_fold=5, random_state=None)[source]

基础:BaseRLearner

R-learner分类器类的父类。

fit(X, treatment, y, p=None, sample_weight=None, verbose=True)[source]

拟合R学习者的治疗效果和结果模型。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

  • sample_weight (np.arraypd.Series, 可选) – 一个样本权重数组,表示每个观测值在 effect_learner 中的权重。如果为 None,则假定权重相等。

  • verbose (bool, optional) – 是否输出进度日志

predict(X, p=None)[source]

预测治疗效果。

Parameters:

X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

Returns:

治疗效果预测。

Return type:

(numpy.ndarray)

class causalml.inference.meta.BaseRLearner(learner=None, outcome_learner=None, effect_learner=None, propensity_learner=LogisticRegressionCV(Cs=array([1.00230524, 2.15608891, 4.63802765, 9.97700064]), cv=StratifiedKFold(n_splits=4, random_state=42, shuffle=True), l1_ratios=array([0.001, 0.33366667, 0.66633333, 0.999]), penalty='elasticnet', random_state=42, solver='saga'), ate_alpha=0.05, control_name=0, n_fold=5, random_state=None, cv_n_jobs=-1)[source]

基础:BaseLearner

R-learner 类的父类。

R-learner 使用两个机器学习模型和倾向得分来估计处理效果。

R-learner 的详细信息可在 Nie and Wager (2019) 获取。

estimate_ate(X, treatment=None, y=None, p=None, sample_weight=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000, pretrain=False)[source]

估计平均处理效应(ATE)。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 仅在 pretrain=False 时需要,一个治疗向量

  • y (np.arraypd.Series) – 仅在 pretrain=False 时需要,一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

  • sample_weight (np.arraypd.Series, 可选) – 一个样本权重数组,表示每个观测值在 effect_learner 中的权重。如果为 None,则假定权重相等。

  • bootstrap_ci (bool) – 是否运行bootstrap以计算置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

  • pretrain (bool) – 模型是否已经拟合,默认为 False。

Returns:

ATE估计的均值和置信区间(LB, UB)。

fit(X, treatment, y, p=None, sample_weight=None, verbose=True)[source]

拟合R学习者的治疗效果和结果模型。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

  • sample_weight (np.arraypd.Series, 可选) – 一个样本权重数组,表示每个观测值在 effect_learner 中的权重。如果为 None,则假定权重相等。

  • verbose (bool, optional) – 是否输出进度日志

fit_predict(X, treatment, y, p=None, sample_weight=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, verbose=True)[source]

拟合R学习者的治疗效果和结果模型并预测治疗效果。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

  • sample_weight (np.arraypd.Series, 可选) – 一个样本权重数组,表示每个观测值在 effect_learner 中的权重。如果为 None,则假定权重相等。

  • return_ci (bool) – 是否返回置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

  • verbose (bool) – 是否输出进度日志

Returns:

治疗效果预测。输出维度:[n_samples, n_treatment]。

如果return_ci为真,返回CATE [n_samples, n_treatment], LB [n_samples, n_treatment], UB [n_samples, n_treatment]

Return type:

(numpy.ndarray)

predict(X, p=None)[source]

预测治疗效果。

Parameters:

X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

Returns:

治疗效果预测。

Return type:

(numpy.ndarray)

class causalml.inference.meta.BaseRRegressor(learner=None, outcome_learner=None, effect_learner=None, propensity_learner=LogisticRegressionCV(Cs=array([1.00230524, 2.15608891, 4.63802765, 9.97700064]), cv=StratifiedKFold(n_splits=4, random_state=42, shuffle=True), l1_ratios=array([0.001, 0.33366667, 0.66633333, 0.999]), penalty='elasticnet', random_state=42, solver='saga'), ate_alpha=0.05, control_name=0, n_fold=5, random_state=None)[source]

基础:BaseRLearner

R-learner回归器类的父类。

class causalml.inference.meta.BaseSClassifier(learner=None, ate_alpha=0.05, control_name=0)[source]

基础类: BaseSLearner

S-learner分类器类的父类。

predict(X, treatment=None, y=None, p=None, return_components=False, verbose=True)[source]

预测治疗效果。 :param X: 特征矩阵 :type X: np.matrix 或 np.array 或 pd.Dataframe :param treatment: 处理向量 :type treatment: np.array 或 pd.Series, 可选 :param y: 结果向量 :type y: np.array 或 pd.Series, 可选 :param return_components: 是否分别返回处理组和对照组的结果 :type return_components: bool, 可选 :param verbose: 是否输出进度日志 :type verbose: bool, 可选

Returns:

治疗效果预测。

Return type:

(numpy.ndarray)

class causalml.inference.meta.BaseSLearner(learner=None, ate_alpha=0.05, control_name=0)[source]

基础:BaseLearner

S-learner 类的父类。 S-learner 使用一个机器学习模型来估计治疗效果。 有关 S-learner 的详细信息可在 Kunzel et al. (2018) 中找到。

estimate_ate(X, treatment, y, p=None, return_ci=False, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000, pretrain=False)[source]

估计平均处理效应(ATE)。

Parameters:
  • X (np.matrix, np.array, 或 pd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • return_ci (bool, optional) – 是否返回置信区间

  • bootstrap_ci (bool) – 是否返回置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

  • pretrain (bool) – 模型是否已经拟合,默认为 False。

Returns:

ATE估计的均值和置信区间(LB, UB)。

fit(X, treatment, y, p=None)[source]

拟合推理模型 :param X: 特征矩阵 :type X: np.matrix, np.array, 或 pd.Dataframe :param treatment: 处理向量 :type treatment: np.array 或 pd.Series :param y: 结果向量 :type y: np.array 或 pd.Series

fit_predict(X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True)[source]

拟合S学习器的推理模型并预测处理效果。 :param X: 特征矩阵 :type X: np.matrix, np.array, 或 pd.Dataframe :param treatment: 处理向量 :type treatment: np.array 或 pd.Series :param y: 结果向量 :type y: np.array 或 pd.Series :param return_ci: 是否返回置信区间 :type return_ci: bool, 可选 :param n_bootstraps: 自举迭代次数 :type n_bootstraps: int, 可选 :param bootstrap_size: 每次自举的样本数量 :type bootstrap_size: int, 可选 :param return_components: 是否分别返回处理和对照的结果 :type return_components: bool, 可选 :param verbose: 是否输出进度日志 :type verbose: bool, 可选

Returns:

治疗效果预测。输出维度:[n_samples, n_treatment]。

如果return_ci,返回CATE [n_samples, n_treatment], LB [n_samples, n_treatment], UB [n_samples, n_treatment]

Return type:

(numpy.ndarray)

predict(X, treatment=None, y=None, p=None, return_components=False, verbose=True)[source]

预测治疗效果。 :param X: 特征矩阵 :type X: np.matrix 或 np.array 或 pd.Dataframe :param treatment: 处理向量 :type treatment: np.array 或 pd.Series, 可选 :param y: 结果向量 :type y: np.array 或 pd.Series, 可选 :param return_components: 是否分别返回处理组和对照组的结果 :type return_components: bool, 可选 :param verbose: 是否输出进度日志 :type verbose: bool, 可选

Returns:

治疗效果预测。

Return type:

(numpy.ndarray)

class causalml.inference.meta.BaseSRegressor(learner=None, ate_alpha=0.05, control_name=0)[source]

基础类: BaseSLearner

S-learner回归器类的父类。

class causalml.inference.meta.BaseTClassifier(learner=None, control_learner=None, treatment_learner=None, ate_alpha=0.05, control_name=0)[source]

基础类: BaseTLearner

T-learner分类器类的父类。

predict(X, treatment=None, y=None, p=None, return_components=False, verbose=True)[source]

预测治疗效果。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series, 可选) – 一个治疗向量

  • y (np.arraypd.Series, 可选) – 一个结果向量

  • verbose (bool, optional) – 是否输出进度日志

Returns:

治疗效果预测。

Return type:

(numpy.ndarray)

class causalml.inference.meta.BaseTLearner(learner=None, control_learner=None, treatment_learner=None, ate_alpha=0.05, control_name=0)[source]

基础:BaseLearner

T-learner回归器类的父类。

T-learner 使用两个机器学习模型来估计治疗效果。

T-learner的详细信息可在Kunzel et al. (2018)中找到。

estimate_ate(X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000, pretrain=False)[source]

估计平均处理效应(ATE)。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • bootstrap_ci (bool) – 是否返回置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

Returns:

ATE估计的均值和置信区间(LB,UB)。 pretrain(布尔值):模型是否已经拟合,默认为False。

fit(X, treatment, y, p=None)[source]

拟合推理模型

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

fit_predict(X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True)[source]

拟合T学习器的推理模型并预测治疗效果。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • return_ci (bool) – 是否返回置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

  • return_components (bool, optional) – 是否分别返回治疗组和对照组的结果

  • verbose (str) – 是否输出进度日志

Returns:

治疗效果预测。输出维度:[n_samples, n_treatment]。

如果return_ci为真,返回CATE [n_samples, n_treatment], LB [n_samples, n_treatment], UB [n_samples, n_treatment]

Return type:

(numpy.ndarray)

predict(X, treatment=None, y=None, p=None, return_components=False, verbose=True)[source]

预测治疗效果。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series, 可选) – 一个治疗向量

  • y (np.arraypd.Series, 可选) – 一个结果向量

  • return_components (bool, optional) – 是否分别返回治疗组和对照组的结果

  • verbose (bool, optional) – 是否输出进度日志

Returns:

治疗效果预测。

Return type:

(numpy.ndarray)

class causalml.inference.meta.BaseTRegressor(learner=None, control_learner=None, treatment_learner=None, ate_alpha=0.05, control_name=0)[source]

基础类: BaseTLearner

T-learner回归器类的父类。

class causalml.inference.meta.BaseXClassifier(outcome_learner=None, effect_learner=None, control_outcome_learner=None, treatment_outcome_learner=None, control_effect_learner=None, treatment_effect_learner=None, ate_alpha=0.05, control_name=0)[source]

基础类: BaseXLearner

X-learner分类器类的父类。

fit(X, treatment, y, p=None)[source]

拟合推理模型。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

predict(X, treatment=None, y=None, p=None, return_components=False, verbose=True)[source]

预测治疗效果。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series, 可选) – 一个治疗向量

  • y (np.arraypd.Series, 可选) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

  • return_components (bool, optional) – 是否分别返回治疗组和对照组的结果

  • return_p_score (bool, optional) – 是否返回倾向得分

  • verbose (bool, optional) – 是否输出进度日志

Returns:

治疗效果预测。

Return type:

(numpy.ndarray)

class causalml.inference.meta.BaseXLearner(learner=None, control_outcome_learner=None, treatment_outcome_learner=None, control_effect_learner=None, treatment_effect_learner=None, ate_alpha=0.05, control_name=0)[source]

基础:BaseLearner

X-learner回归器类的父类。

X-learner 使用四个机器学习模型来估计治疗效果。

X-learner 的详细信息可在 Kunzel et al. (2018) 中找到。

estimate_ate(X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000, pretrain=False)[source]

估计平均处理效应(ATE)。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

  • bootstrap_ci (bool) – 是否运行bootstrap以计算置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

  • pretrain (bool) – 模型是否已经拟合,默认为 False。

Returns:

ATE估计的均值和置信区间(LB, UB)。

fit(X, treatment, y, p=None)[source]

拟合推理模型。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

fit_predict(X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True)[source]

拟合R学习者的治疗效果和结果模型并预测治疗效果。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

  • return_ci (bool) – 是否返回置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

  • return_components (bool, optional) – 是否分别返回治疗组和对照组的结果

  • verbose (str) – 是否输出进度日志

Returns:

治疗效果预测。输出维度:[n_samples, n_treatment]

如果return_ci,返回CATE [n_samples, n_treatment], LB [n_samples, n_treatment], UB [n_samples, n_treatment]

Return type:

(numpy.ndarray)

predict(X, treatment=None, y=None, p=None, return_components=False, verbose=True)[source]

预测治疗效果。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series, 可选) – 一个治疗向量

  • y (np.arraypd.Series, 可选) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

  • return_components (bool, optional) – 是否分别返回治疗组和对照组的结果

  • verbose (bool, optional) – 是否输出进度日志

Returns:

治疗效果预测。

Return type:

(numpy.ndarray)

class causalml.inference.meta.BaseXRegressor(learner=None, control_outcome_learner=None, treatment_outcome_learner=None, control_effect_learner=None, treatment_effect_learner=None, ate_alpha=0.05, control_name=0)[source]

基础类: BaseXLearner

X-learner回归器类的父类。

class causalml.inference.meta.LRSRegressor(ate_alpha=0.05, control_name=0)[source]

基础类: BaseSRegressor

estimate_ate(X, treatment, y, p=None, pretrain=False)[source]

估计平均处理效果(ATE)。 :param X: 特征矩阵 :type X: np.matrix, np.array, 或 pd.Dataframe :param treatment: 处理向量 :type treatment: np.array 或 pd.Series :param y: 结果向量 :type y: np.array 或 pd.Series

Returns:

ATE估计的均值和置信区间(LB, UB)。

class causalml.inference.meta.MLPTRegressor(ate_alpha=0.05, control_name=0, *args, **kwargs)[source]

基础类: BaseTRegressor

class causalml.inference.meta.TMLELearner(learner, ate_alpha=0.05, control_name=0, cv=None, calibrate_propensity=True)[source]

基础:object

目标最大似然估计。

参考文献: Gruber, S., & Van Der Laan, M. J. (2009). 目标最大似然估计: 一个温和的介绍。

estimate_ate(X, treatment, y, p, segment=None, return_ci=False)[source]

估计平均处理效应(ATE)。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典

  • segment (np.array, optional) – 一个可选的整数段向量。如果提供,将为每个段估计ATE及其置信区间。

  • return_ci (bool, optional) – 是否返回置信区间

Returns:

每个治疗t和段s的ATE及其置信区间(LB,UB)

Return type:

(元组)

class causalml.inference.meta.XGBDRRegressor(ate_alpha=0.05, control_name=0, *args, **kwargs)[source]

基础类:BaseDRRegressor

class causalml.inference.meta.XGBRRegressor(early_stopping=True, test_size=0.3, early_stopping_rounds=30, effect_learner_objective='reg:squarederror', effect_learner_n_estimators=500, random_state=42, *args, **kwargs)[source]

基础类: BaseRRegressor

fit(X, treatment, y, p=None, sample_weight=None, verbose=True)[source]

拟合R学习者的治疗效果和结果模型。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • y (np.arraypd.Series) – 一个结果向量

  • p (np.ndarraypd.Seriesdict, 可选) – 在单处理情况下,为浮点数(0,1)的倾向得分数组;或者,为映射到浮点数(0,1)倾向向量的处理组字典;如果为None,将运行ElasticNetPropensityModel()生成倾向得分。

  • sample_weight (np.arraypd.Series, 可选) – 一个样本权重数组,表示每个观测值在 effect_learner 中的权重。如果为 None,则假定权重相等。

  • verbose (bool, optional) – 是否输出进度日志

class causalml.inference.meta.XGBTRegressor(ate_alpha=0.05, control_name=0, *args, **kwargs)[source]

基础类: BaseTRegressor

causalml.inference.iv 模块

class causalml.inference.iv.BaseDRIVLearner(learner=None, control_outcome_learner=None, treatment_outcome_learner=None, treatment_effect_learner=None, ate_alpha=0.05, control_name=0)[source]

基础:object

DRIV-learner回归器类的父类。

DRIV-learner 使用机器学习模型估计了遵守者的内生处理效应。

DR-learner 的详细信息可在 Kennedy (2020) 中找到。 LATE 的 DR 矩条件来自 Chernozhukov et al (2018)

bootstrap(X, assignment, treatment, y, p, pZ, size=10000, seed=None)[source]

运行单个引导程序。在引导样本上拟合,然后在整个群体上进行预测。

estimate_ate(X, assignment, treatment, y, p=None, pZ=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000, seed=None, calibrate=True)[source]

估计遵守者的平均处理效果(ATE)。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • assignment (np.arraypd.Series) – 一个分配向量。分配是不依赖于未知混杂因素的工具变量。分配状态以单调的方式影响治疗,即如果被分配,一个人只能更有可能接受治疗。

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (2元组np.ndarraypd.Seriesdict, 可选) – 第一个(第二个)元素对应于 未分配(已分配)的单位。在单处理情况下,每个元素是一个浮点数(0,1)的倾向得分数组;或者,一个映射到浮点数(0,1)倾向向量的处理组字典。如果为None,将运行ElasticNetPropensityModel()来生成倾向得分。

  • pZ (np.arraypd.Series, 可选) – 一个浮点数(0,1)的分配概率数组;如果为 None 将运行 ElasticNetPropensityModel() 来生成分配概率分数。

  • bootstrap_ci (bool) – 是否运行bootstrap以计算置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

  • seed (int) – 用于交叉拟合的随机种子

Returns:

ATE估计的均值和置信区间(LB, UB)。

fit(X, assignment, treatment, y, p=None, pZ=None, seed=None, calibrate=True)[source]

拟合推理模型。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • assignment (np.arraypd.Series) – 一个(0,1)值的分配向量。分配是不依赖于未知混杂因素的工具变量。分配状态以单调的方式影响治疗,即如果被分配,一个人只能更有可能接受治疗。

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (2元组np.ndarraypd.Seriesdict, 可选) – 第一个(第二个)元素对应于 未分配(已分配)的单位。在单处理情况下,每个元素是一个浮点数(0,1)的倾向得分数组;或者,一个映射到浮点数(0,1)倾向向量的处理组字典。如果为None,将运行ElasticNetPropensityModel()来生成倾向得分。

  • pZ (np.arraypd.Series, 可选) – 一个浮点数(0,1)的分配概率数组;如果为 None 将运行 ElasticNetPropensityModel() 来生成分配概率分数。

  • seed (int) – 用于交叉拟合的随机种子

fit_predict(X, assignment, treatment, y, p=None, pZ=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True, seed=None, calibrate=True)[source]

拟合R学习者的治疗效果和结果模型并预测治疗效果。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • assignment (np.arraypd.Series) – 一个(0,1)值的分配向量。分配是不依赖于未知混杂因素的工具变量。分配状态以单调的方式影响治疗,即如果被分配,一个人只能更有可能接受治疗。

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • p (2元组np.ndarraypd.Seriesdict, 可选) – 第一个(第二个)元素对应于 未分配(已分配)的单位。在单处理情况下,每个元素是一个浮点数(0,1)的倾向得分数组;或者,一个映射到浮点数(0,1)倾向向量的处理组字典。如果为None,将运行ElasticNetPropensityModel()来生成倾向得分。

  • pZ (np.arraypd.Series, 可选) – 一个浮点数(0,1)的分配概率数组;如果为 None 将运行 ElasticNetPropensityModel() 来生成分配概率分数。

  • return_ci (bool) – 是否返回置信区间

  • n_bootstraps (int) – 自举迭代的次数

  • bootstrap_size (int) – 每个引导的样本数量

  • return_components (bool, optional) – 是否分别返回治疗组和对照组的结果

  • verbose (str) – 是否输出进度日志

  • seed (int) – 用于交叉拟合的随机种子

Returns:

对遵守者的治疗效果预测,即那些个体

只有在被分配时才会接受治疗。输出维度:[n_samples, n_treatment] 如果return_ci,返回CATE [n_samples, n_treatment], LB [n_samples, n_treatment], UB [n_samples, n_treatment]

Return type:

(numpy.ndarray)

get_importance(X=None, tau=None, model_tau_feature=None, features=None, method='auto', normalize=True, test_size=0.3, random_state=None)[source]

构建一个模型(使用X来预测估计/实际的tau),然后根据指定的方法计算特征重要性。

Currently supported methods are:
  • auto (calculates importance based on estimator’s default implementation of feature importance;

    估计器必须基于树) 注意:如果没有提供,它将使用lightgbm的LGBMRegressor作为估计器,并使用“gain”作为重要性类型

  • permutation (calculates importance based on mean decrease in accuracy when a feature column is permuted;

    估计器可以是任何形式)

提示:对于排列,下采样数据以获得更好的性能,特别是当X.shape[1]很大时

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • tau (np.array) – 一个治疗效果向量(估计/实际)

  • model_tau_feature (sklearn/lightgbm/xgboost 模型对象) – 一个未拟合的模型对象

  • 特征 (np.array) – 特征名称的列表/数组。如果为None,将使用枚举列表

  • method (str) – 自动, 排列

  • normalize (bool) – 如果 method=auto,则通过重要性之和进行归一化(默认为 True)

  • test_size (float/int) – 如果是浮点数,表示测试集所占数据集的比例。 如果是整数,表示测试样本的绝对数量(用于估计 排列重要性)

  • random_state (int/RandomState instance/None) – 用于排列重要性估计的随机状态

get_shap_values(X=None, model_tau_feature=None, tau=None, features=None)[source]

构建一个模型(使用X来预测估计/实际的tau),然后计算shapley值。 :param X: 特征矩阵 :type X: np.matrix 或 np.array 或 pd.Dataframe :param tau: 处理效果向量(估计/实际) :type tau: np.array :param model_tau_feature: 未拟合的模型对象 :type model_tau_feature: sklearn/lightgbm/xgboost 模型对象 :param features: 特征名称的列表/数组。如果为None,将使用枚举列表。 :type features: 可选, np.array

plot_importance(X=None, tau=None, model_tau_feature=None, features=None, method='auto', normalize=True, test_size=0.3, random_state=None)[source]

构建一个模型(使用X来预测估计/实际的tau),然后根据指定的方法绘制特征重要性。

Currently supported methods are:
  • auto (calculates importance based on estimator’s default implementation of feature importance;

    估计器必须基于树) 注意:如果没有提供,它将使用lightgbm的LGBMRegressor作为估计器,并使用“gain”作为重要性类型

  • permutation (calculates importance based on mean decrease in accuracy when a feature column is permuted;

    估计器可以是任何形式)

提示:对于排列,下采样数据以获得更好的性能,特别是当X.shape[1]很大时

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • tau (np.array) – 一个治疗效果向量(估计/实际)

  • model_tau_feature (sklearn/lightgbm/xgboost 模型对象) – 一个未拟合的模型对象

  • 特征 (可选, np.array) – 特征名称的列表/数组。如果为None,将使用枚举列表

  • method (str) – 自动, 排列

  • normalize (bool) – 如果方法为auto,则通过重要性之和进行归一化(默认为True)

  • test_size (float/int) – 如果是浮点数,表示测试集所占数据集的比例。 如果是整数,表示测试样本的绝对数量(用于估计 排列重要性)

  • random_state (int/RandomState instance/None) – 用于排列重要性估计的随机状态

plot_shap_dependence(treatment_group, feature_idx, X, tau, model_tau_feature=None, features=None, shap_dict=None, interaction_idx='auto', **kwargs)[source]

绘制指定特征的Shapley值的依赖关系,通过交互特征进行着色。

如果已经预先计算了shapley值,可以通过shap_dict参数传递它。 如果没有提供shap_dict,这将构建一个新模型(使用X来预测估计/实际的tau), 然后计算shapley值。

此图在x轴上绘制特征的值,在y轴上绘制同一特征的SHAP值。这显示了模型如何依赖于给定的特征,并且类似于经典的部分依赖图的更丰富的扩展。数据点的垂直分散表示交互效应。

Parameters:
  • treatment_group (strint) – 创建依赖图的处理组名称

  • feature_idx (strint) – 用于创建依赖图的特征索引/名称

  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • tau (np.array) – 一个治疗效果向量(估计/实际)

  • model_tau_feature (sklearn/lightgbm/xgboost 模型对象) – 一个未拟合的模型对象

  • 特征 (可选, np.array) – 特征名称的列表/数组。如果为None,将使用枚举列表。

  • shap_dict (可选, 字典) – 一个包含shapley值矩阵的字典。如果为None,将计算shap_dict。

  • interaction_idx (可选, strint) – 用于着色方案中的特征索引/名称作为交互特征。 如果为“auto”,则使用shap.common.approximate_interactions来选择似乎是最强的交互(注意,要找到真正的强交互,您需要计算SHAP交互值)。

plot_shap_values(X=None, tau=None, model_tau_feature=None, features=None, shap_dict=None, **kwargs)[source]

绘制Shapley值的分布。

如果已经预先计算了shapley值,可以通过shap_dict参数传递它。 如果没有提供shap_dict,这将构建一个新模型(使用X来预测估计/实际的tau), 然后计算shapley值。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵。如果 shap_dict 为 None,则为必需。

  • tau (np.array) – 一个治疗效果向量(估计/实际)

  • model_tau_feature (sklearn/lightgbm/xgboost 模型对象) – 一个未拟合的模型对象

  • 特征 (可选, np.array) – 特征名称的列表/数组。如果为None,将使用枚举列表。

  • shap_dict (可选, 字典) – 一个包含shapley值矩阵的字典。如果为None,将计算shap_dict。

predict(X, treatment=None, y=None, return_components=False, verbose=True)[source]

预测治疗效果。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series, 可选) – 一个治疗向量

  • y (np.arraypd.Series, 可选) – 一个结果向量

  • verbose (bool, optional) – 是否输出进度日志

Returns:

对遵守者的治疗效果预测,即那些个体

只有在被分配时才会接受治疗。

Return type:

(numpy.ndarray)

class causalml.inference.iv.BaseDRIVRegressor(learner=None, control_outcome_learner=None, treatment_outcome_learner=None, treatment_effect_learner=None, ate_alpha=0.05, control_name=0)[source]

基础类: BaseDRIVLearner

DRIV-learner回归器类的父类。

class causalml.inference.iv.IVRegressor[source]

基础:object

一个使用statsmodel中的IV2SLS的包装类

一个线性2SLS模型,用于估计具有内生处理变量的平均处理效应。

fit(X, treatment, y, w)[source]

拟合2SLS模型。

Parameters:
  • X (np.matrixnp.arraypd.Dataframe) – 特征矩阵

  • treatment (np.arraypd.Series) – 一个治疗向量

  • y (np.arraypd.Series) – 一个结果向量

  • w (np.arraypd.Series) – 一个工具向量

predict()[source]

返回平均处理效果及其估计的标准误差

Returns:

平均处理效果 (float): 估计的标准误差

Return type:

(浮点数)

class causalml.inference.iv.XGBDRIVRegressor(ate_alpha=0.05, control_name=0, *args, **kwargs)[source]

基础类: BaseDRIVRegressor

causalml.inference.nn 模块

causalml.inference.tf 模块

causalml.optimize 模块

class causalml.optimize.CounterfactualUnitSelector(learner, nevertaker_payoff, alwaystaker_payoff, complier_payoff, defier_payoff, organic_conversion=None)[source]

基础:object

一个高度实验性的反事实单位选择模型的实现,由Li和Pearl(2019)提出。

Parameters:
  • learner (object) – 用于估计分段概率的基础学习器。

  • nevertaker_payoff (float) – 针对从不接受者的收益

  • alwaystaker_payoff (float) – 针对总是接受者的收益

  • complier_payoff (float) – 针对一个遵守者的收益

  • defier_payoff (float) – 针对反抗者的收益

  • organic_conversion (float, optional (default=None)) –

    在没有干预的情况下,人群中的自然转化率。 如果为None,则从对照组中获取自然转化率。

    注意:对照组中的自然转化率并不总是与未治疗的自然转化率相同。

  • data (DataFrame) – 一个包含特征、处理分配指示符和感兴趣结果的pandas DataFrame。

  • treatment (string) – 一个字符串,对应于处理列的名称。假设列中的编码为1表示处理,0表示控制。

  • 结果 (字符串) – 一个字符串,对应于结果列的名称。假设列中的编码为1表示转化,0表示未转化。

参考文献

李、昂和朱迪亚·珀尔。2019年。“基于反事实逻辑的单位选择。” https://ftp.cs.ucla.edu/pub/stat_ser/r488.pdf.

fit(data, treatment, outcome)[source]

适合该类。

predict(data, treatment, outcome)[source]

预测个体级别的收益。如果满足增益平等条件,则使用精确函数;如果不满足,则使用界限之间的中点。

class causalml.optimize.CounterfactualValueEstimator(treatment, control_name, treatment_names, y_proba, cate, value, conversion_cost, impression_cost, *args, **kwargs)[source]

基础:object

Parameters:
  • treatment (array, shape = (num_samples, )) – 一个包含治疗组指示值的数组。

  • control_name (string) – 控制条件的名称,以字符串形式表示。必须包含在治疗数组中。

  • treatment_names (list, length = cate.shape[1]) – 处理组名称的列表。注意:列表中项目的顺序必须与cate_array中条件平均处理效应估计的顺序相对应。

  • y_proba (array, shape = (num_samples, )) – 使用 Y ~ X 模型在整个样本中预测的转换概率。

  • cate (array, shape = (num_samples, len(set(treatment)))) – 来自任何模型的条件平均治疗效果估计。

  • value (array, shape = (num_samples, )) – 每个单位的转换值。

  • conversion_cost (shape = (num_samples, len(set(treatment)))) – 如果单位在接受治疗后转化,例如促销代码,触发的治疗成本。

  • impression_cost (shape = (num_samples, len(set(treatment)))) – 每个单位无论是否转化的处理成本,例如与促销渠道相关的成本。

注释

因为我们从cate-learners中获得了相对于控制条件的条件平均处理效果,我们从该单元的y_proba中减去其实际治疗组中的单元的cate,以恢复控制结果。然后我们将cates添加到控制结果中,以获得每个条件下的y_proba。这些结果是反事实的,因为实际上只观察到了其中一个。

predict_best()[source]

根据治疗的最高反事实值预测最佳治疗组。

predict_counterfactuals()[source]

预测每个治疗组的反事实值。

class causalml.optimize.PolicyLearner(outcome_learner=GradientBoostingRegressor(), treatment_learner=GradientBoostingClassifier(), policy_learner=DecisionTreeClassifier(), clip_bounds=(0.001, 0.999), n_fold=5, random_state=None, calibration=False)[source]

基础:object

一个学习者,使用双重稳健估计器从观察数据中学习二元处理的因果效应,以学习处理分配策略。

策略学习器的详细信息可在Athey and Wager (2018)找到。

fit(X, treatment, y, p=None, dhat=None)[source]

拟合治疗分配策略学习器。

Parameters:
  • X (np.matrix) – 特征矩阵

  • treatment (np.array) – 处理向量(1 表示处理,否则为 0)

  • y (np.array) – 一个结果向量

  • p (可选, np.array) – 用户提供的介于0和1之间的倾向得分向量

  • dhat (可选, np.array) – 用户提供的预测治疗效果向量

Returns:

返回自身的实例。

Return type:

自身

predict(X)[source]

预测优化结果的治疗分配。

Parameters:

X (np.matrix) – 特征矩阵

Returns:

治疗分配的预测。

Return type:

(numpy.ndarray)

predict_proba(X)[source]

预测优化结果的治疗分配分数。

Parameters:

X (np.matrix) – 特征矩阵

Returns:

治疗分配得分的预测。

Return type:

(numpy.ndarray)

causalml.optimize.get_actual_value(treatment, observed_outcome, conversion_value, conditions, conversion_cost, impression_cost)[source]

根据参数字典设置转化和展示成本。

使用上述参数计算针对实际治疗组用户的实际值。

参数

treatmentarray, shape = (num_samples, )

处理数组。

observed_outcomearray, shape = (num_samples, )

观察结果数组,也称为 y。

conversion_valuearray, shape = (num_samples, )

转换给定用户的值。

conditionslist, len = len(set(treatment))

治疗条件列表。

conversion_costarray, shape = (num_samples, num_treatment)

每个处理中每个单位的转换成本数组。

impression_costarray, shape = (num_samples, num_treatment)

每个处理中每个单位的印象成本数组。

returns:
  • actual_value (数组, 形状 = (num_samples, )) – 用户在其实际治疗组中的实际值数组。

  • conversion_value (array, shape = (num_samples, )) – 用户转换后的收益数组。

causalml.optimize.get_pns_bounds(data_exp, data_obs, T, Y, type='PNS')[source]
Parameters:
  • data_exp (DataFrame) – 实验数据。

  • data_obs (DataFrame) – 来自观察研究的数据

  • T (str) – 二元治疗指标的名称

  • y (str) – 二元结果指标的名称

  • type (str) –

    所需的因果关系概率类型。可接受的参数有:
    • PNS: 必要且充分的因果关系概率

    • PS: 充分的因果关系概率

    • PN: 必要的因果关系概率

注释

基于Tian and Pearl (2000)中的公式(24)。

为了捕捉反事实符号,我们使用10分别表示变量的实际值和反事实值,并使用do来表示干预的效果。

实验和观测数据通常假设来自同一群体,或来自群体的随机样本。如果数据来自样本,边界可能会被错误计算,因为Tian-Pearl方程中的相关量被定义为例如\(P(Y|do(T))\),而不是\(P(Y|do(T), S)\),其中\(S\)对应于样本选择。Bareinboim and Pearl (2016)讨论了在什么条件下可以从\(P(Y|do(T), S)\)中恢复\(P(Y|do(T))\)

causalml.optimize.get_treatment_costs(treatment, control_name, cc_dict, ic_dict)[source]

根据参数字典设置转化和展示成本。

使用上述参数计算实际治疗组中针对用户的实际成本。

参数

treatmentarray, shape = (num_samples, )

处理数组。

control_name, str

控制组名称作为字符串。

cc_dictdict

包含每种治疗转换成本的字典。

ic_dict

包含每个处理的印象成本的字典。

returns:
  • conversion_cost (ndarray, shape = (num_samples, num_treatments)) – 每个处理的转换成本数组。

  • impression_cost (ndarray, shape = (num_samples, num_treatments)) – 每个处理的展示成本数组。

  • conditions (list, len = len(set(treatment))) – 实验条件的列表。

causalml.optimize.get_uplift_best(cate, conditions)[source]

从学习者那里获取CATE预测,添加控制结果数组并找到argmax条件的名称。

参数

catearray, shape = (num_samples, )

条件平均处理效应预测。

条件 : 列表, 长度 = 长度(集合(处理))

returns:

uplift_recomm_name – 学习者推荐的实验组。

rtype:

数组, 形状 = (num_samples, )

causalml.dataset 模块

causalml.dataset.bar_plot_summary(synthetic_summary, k, drop_learners=[], drop_cols=[], sort_cols=['MSE', 'Abs % Error of ATE'])[source]

生成一个比较学习者表现的条形图。

Parameters:
  • synthetic_summary (pd.DataFrame) – 由 get_synthetic_summary() 生成的摘要

  • k (int) – 模拟次数(仅用于图表标题文本)

  • drop_learners (list, optional) – 绘制图表时要省略的学习者列表(str)

  • drop_cols (list, optional) – 绘制图表时要省略的指标列表(str)

  • sort_cols (list, optional) – 绘制图表时用于排序的指标列表(str)

causalml.dataset.bar_plot_summary_holdout(train_summary, validation_summary, k, drop_learners=[], drop_cols=[])[source]

生成一个条形图,比较训练和验证的学习者表现

Parameters:
  • train_summary (pd.DataFrame) – 由 get_synthetic_summary_holdout() 生成的训练合成数据的摘要

  • validation_summary (pd.DataFrame) – 由get_synthetic_summary_holdout()生成的验证合成数据的摘要

  • k (int) – 模拟次数(仅用于图表标题文本)

  • drop_learners (list, optional) – 绘制图表时要省略的学习者列表(str)

  • drop_cols (list, optional) – 绘制图表时要省略的指标列表(str)

causalml.dataset.distr_plot_single_sim(synthetic_preds, kind='kde', drop_learners=[], bins=50, histtype='step', alpha=1, linewidth=1, bw_method=1)[source]

绘制每个学习者的预测分布(针对单个模拟)。 支持核密度估计(kde)和实际直方图绘制。

Parameters:
  • synthetic_preds (dict) – 由 get_synthetic_preds() 生成的预测字典

  • kind (str, optional) – ‘kde’ 或 ‘hist’

  • drop_learners (list, optional) – 绘制时省略的学习者列表(str)

  • bins (int, optional) – 如果类型设置为‘hist’,则绘制的柱状图的数量

  • histtype (str, optional) – 如果kind设置为'hist',则为直方图类型

  • alpha (float, optional) – 用于绘图的alpha(透明度)

  • linewidth (int, optional) – 绘图的线宽

  • bw_method (float, optional) – kde的参数

causalml.dataset.get_synthetic_auuc(synthetic_preds, drop_learners=[], outcome_col='y', treatment_col='w', treatment_effect_col='tau', plot=True)[source]

获取模型估计在分位数中的累积增益的auuc值。

详情请参考 get_cumgain() 和 plot_gain() :param synthetic_preds: 由 get_synthetic_preds() 生成的预测字典 :type synthetic_preds: dict :param 或 get_synthetic_preds_holdout(): :param outcome_col: 实际结果的列名 :type outcome_col: str, 可选 :param treatment_col: 处理指示符的列名(0 或 1) :type treatment_col: str, 可选 :param treatment_effect_col: 真实处理效果的列名 :type treatment_effect_col: str, 可选 :param plot: 是否绘制累积增益图 :type plot: boolean, 可选

Returns:

按学习者划分的auuc值,用于模型估计的累积增益

Return type:

(pandas.DataFrame)

causalml.dataset.get_synthetic_preds(synthetic_data_func, n=1000, estimators={})[source]

使用指定函数生成合成数据的预测(单次模拟)

Parameters:
  • synthetic_data_func (function) – 合成数据生成函数

  • n (int, optional) – 样本数量

  • estimators (dict of object) – 处理效果估计器的名称和对象的字典

Returns:

实际和估计治疗效果的数据字典

Return type:

(字典)

causalml.dataset.get_synthetic_preds_holdout(synthetic_data_func, n=1000, valid_size=0.2, estimators={})[source]

使用指定函数为训练集和保留集生成合成数据的预测(单次模拟)

Parameters:
  • synthetic_data_func (function) – 合成数据生成函数

  • n (int, optional) – 样本数量

  • valid_size (float,optional) – 验证/保留数据大小

  • estimators (dict of object) – 处理效果估计器的名称和对象的字典

Returns:

合成训练和验证数据字典:

  • preds_dict_train (dict): 合成训练数据字典

  • preds_dict_valid (dict): 合成验证数据字典

Return type:

(元组)

causalml.dataset.get_synthetic_summary(synthetic_data_func, n=1000, k=1, estimators={})[source]

使用指定函数生成对合成数据预测的摘要

Parameters:
  • synthetic_data_func (function) – 合成数据生成函数

  • n (int, optional) – 每次模拟的样本数量

  • k (int, optional) – 模拟次数

causalml.dataset.get_synthetic_summary_holdout(synthetic_data_func, n=1000, valid_size=0.2, k=1)[source]

使用指定函数为训练集和保留集的合成数据预测生成摘要

Parameters:
  • synthetic_data_func (function) – 合成数据生成函数

  • n (int, optional) – 每次模拟的样本数量

  • valid_size (float,optional) – 验证/保留数据大小

  • k (int, optional) – 模拟次数

Returns:

训练和验证预测的评估指标总结:

  • summary_train (pandas.DataFrame): 训练数据评估总结

  • summary_train (pandas.DataFrame): 验证数据评估总结

Return type:

(元组)

causalml.dataset.make_uplift_classification(n_samples=1000, treatment_name=['control', 'treatment1', 'treatment2', 'treatment3'], y_name='conversion', n_classification_features=10, n_classification_informative=5, n_classification_redundant=0, n_classification_repeated=0, n_uplift_increase_dict={'treatment1': 2, 'treatment2': 2, 'treatment3': 2}, n_uplift_decrease_dict={'treatment1': 0, 'treatment2': 0, 'treatment3': 0}, delta_uplift_increase_dict={'treatment1': 0.02, 'treatment2': 0.05, 'treatment3': 0.1}, delta_uplift_decrease_dict={'treatment1': 0.0, 'treatment2': 0.0, 'treatment3': 0.0}, n_uplift_increase_mix_informative_dict={'treatment1': 1, 'treatment2': 1, 'treatment3': 1}, n_uplift_decrease_mix_informative_dict={'treatment1': 0, 'treatment2': 0, 'treatment3': 0}, positive_class_proportion=0.5, random_seed=20190101)[source]

生成一个用于分类提升建模问题的合成数据集。

Parameters:
  • n_samples (int, optional (default=1000)) – 为每个处理组生成的样本数量。

  • treatment_name (list, optional (default = ['control','treatment1','treatment2','treatment3'])) – 处理名称的列表。

  • y_name (string, optional (default = 'conversion')) – 用作输出数据框中列的结果变量的名称。

  • n_classification_features (int, optional (default = 10)) – 基础分类的总特征数

  • n_classification_informative (int, optional (default = 5)) – 用于基础分类的信息特征总数

  • n_classification_redundant (int, 可选 (默认值 = 0)) – 基础分类的冗余特征总数

  • n_classification_repeated (int, 可选 (默认值 = 0)) – 基础分类的重复特征总数

  • n_uplift_increase_dict (dictionary, optional (default: {'treatment1': 2, 'treatment2': 2, 'treatment3': 2})) – 为相应治疗组生成正向治疗效果的特征数量。 {treatment_key: number_of_features_for_increase_uplift}的字典。

  • n_uplift_decrease_dict (dictionary, optional (default: {'treatment1': 0, 'treatment2': 0, 'treatment3': 0})) – 为相应治疗组生成负面治疗效果的特征数量。 {treatment_key: number_of_features_for_increase_uplift}的字典。

  • delta_uplift_increase_dict (dictionary, optional (default: {'treatment1': .02, 'treatment2': .05, 'treatment3': .1})) – 由正向提升特征在基础分类标签上产生的正向治疗效果。 {treatment_key: increase_delta}的字典。

  • delta_uplift_decrease_dict (dictionary, optional (default: {'treatment1': 0., 'treatment2': 0., 'treatment3': 0.})) – 由负提升特征对基础分类标签产生的负处理效果。 {treatment_key: increase_delta}的字典。

  • n_uplift_increase_mix_informative_dict (dictionary, optional) – 每种处理的正面混合特征数量。正面混合特征定义为随机选择的信息分类特征和随机选择的正面提升特征的线性组合。 线性组合由从-1到1之间的均匀分布中采样的两个系数组成。 默认值:{‘treatment1’: 1, ‘treatment2’: 1, ‘treatment3’: 1}

  • n_uplift_decrease_mix_informative_dict (dictionary, optional) – 每个处理的负混合特征数量。负混合特征定义为随机选择的信息分类特征和随机选择的负提升特征的线性组合。线性组合由从-1到1之间的均匀分布中采样的两个系数组成。默认值:{‘treatment1’: 0, ‘treatment2’: 0, ‘treatment3’: 0}

  • positive_class_proportion (float, optional (default = 0.5)) – 对照组中正标签(1)的比例。

  • random_seed (int, optional (default = 20190101)) – 数据生成过程中使用的随机种子。

Returns:

  • df_res (DataFrame) – 包含处理标签、特征和结果变量的数据框。

  • x_name (list) – 生成的特征名称列表。

注释

生成基础分类数据集的算法改编自sklearn包中的make_classification方法,该方法使用了Guyon [1]中设计的算法来生成“Madelon”数据集。

参考文献

causalml.dataset.make_uplift_classification_logistic(n_samples=10000, treatment_name=['control', 'treatment1', 'treatment2', 'treatment3'], y_name='conversion', n_classification_features=10, n_classification_informative=5, n_classification_redundant=0, n_classification_repeated=0, n_uplift_dict={'treatment1': 2, 'treatment2': 2, 'treatment3': 3}, n_mix_informative_uplift_dict={'treatment1': 1, 'treatment2': 1, 'treatment3': 0}, delta_uplift_dict={'treatment1': 0.02, 'treatment2': 0.05, 'treatment3': -0.05}, positive_class_proportion=0.1, random_seed=20200101, feature_association_list=['linear', 'quadratic', 'cubic', 'relu', 'sin', 'cos'], random_select_association=True, error_std=0.05)[source]

生成一个用于分类提升建模问题的合成数据集。

Parameters:
  • n_samples (int, optional (default=1000)) – 为每个处理组生成的样本数量。

  • treatment_name (列表, 可选 (默认值 = ['control','treatment1','treatment2','treatment3'])) – 处理名称的列表。第一个元素必须是‘control’作为对照组,其余的元素被视为处理组。

  • y_name (string, optional (default = 'conversion')) – 用作输出数据框中列的结果变量的名称。

  • n_classification_features (int, optional (default = 10)) – 基础分类的总特征数

  • n_classification_informative (int, optional (default = 5)) – 用于基础分类的信息特征总数

  • n_classification_redundant (int, 可选 (默认值 = 0)) – 基础分类的冗余特征总数

  • n_classification_repeated (int, 可选 (默认值 = 0)) – 基础分类的重复特征总数

  • n_uplift_dict (dictionary, optional (default: {'treatment1': 2, 'treatment2': 2, 'treatment3': 3})) – 用于生成对应治疗组异质治疗效果的特征数量。 {treatment_key: number_of_features_for_uplift}的字典。

  • n_mix_informative_uplift_dict (字典, 可选 (默认: {'treatment1': 1, 'treatment2': 1, 'treatment3': 1})) – 每个处理的混合特征数量。混合特征定义为随机选择的信息分类特征和随机选择的提升特征的线性组合。 混合是通过加权和(p*feature1 + (1-p)*feature2)进行的,其中权重p是从0到1之间的均匀分布中抽取的。

  • delta_uplift_dict (dictionary, optional (default: {'treatment1': .02, 'treatment2': .05, 'treatment3': -.05})) – 处理效果(delta),可以是正数或负数。 {treatment_key: delta} 的字典。

  • positive_class_proportion (float, optional (default = 0.1)) – 对照组中正标签(1)的比例,或对照组结果变量的平均值。

  • random_seed (int, optional (default = 20200101)) – 数据生成过程中使用的随机种子。

  • feature_association_list (list, optional (default = ['linear','quadratic','cubic','relu','sin','cos'])) – 提升特征关联模式的列表,用于处理效果。例如,如果特征模式是‘quadratic’,那么处理效果将随着特征呈二次方增加或减少。列表中的值必须是(‘linear’,‘quadratic’,‘cubic’,‘relu’,‘sin’,‘cos’)之一。然而,相同的值可以在列表中多次出现。

  • random_select_association (boolean, optional (default = True)) – 如何从feature_association_list中选择特征模式以应用于数据生成过程。如果random_select_association = True,则对于每个提升特征,从列表中随机选择一个特征关联模式。如果random_select_association = False,则按顺序从列表中选择特征关联模式,逐个应用于每个特征。

  • error_std (float, optional (default = 0.05)) – 用于逻辑回归误差项的标准差。误差是从均值为0且标准差在此参数中指定的正态分布中抽取的。

Returns:

  • df1 (DataFrame) – 包含处理标签、特征和结果变量的数据框。

  • x_name (list) – 生成的特征名称列表。

causalml.dataset.scatter_plot_single_sim(synthetic_preds)[source]

创建一个散点图网格,比较每个学习者的预测与真实值(针对单个模拟)。

Parameters:

synthetic_preds (dict) – 由 get_synthetic_preds() 或 get_synthetic_preds_holdout() 生成的预测字典

causalml.dataset.scatter_plot_summary(synthetic_summary, k, drop_learners=[], drop_cols=[])[source]

生成一个比较学习者表现的散点图。每个学习者的表现被绘制为(ATE的绝对百分比误差,MSE)空间中的一个点。

Parameters:
  • synthetic_summary (pd.DataFrame) – 由 get_synthetic_summary() 生成的摘要

  • k (int) – 模拟次数(仅用于图表标题文本)

  • drop_learners (list, optional) – 绘制时省略的学习者列表(str)

  • drop_cols (list, optional) – 绘制图表时要省略的指标列表(str)

causalml.dataset.scatter_plot_summary_holdout(train_summary, validation_summary, k, label=['Train', 'Validation'], drop_learners=[], drop_cols=[])[source]

生成一个散点图,比较学习者在训练和验证中的表现。

Parameters:
  • train_summary (pd.DataFrame) – 由 get_synthetic_summary_holdout() 生成的训练合成数据的摘要

  • validation_summary (pd.DataFrame) – 由get_synthetic_summary_holdout()生成的验证合成数据的摘要

  • 标签 (字符串, 可选) – 图例标签

  • k (int) – 模拟次数(仅用于图表标题文本)

  • drop_learners (list, optional) – 绘制时省略的学习者列表(str)

  • drop_cols (list, optional) – 绘制图表时要省略的指标列表(str)

causalml.dataset.simulate_easy_propensity_difficult_baseline(n=1000, p=5, sigma=1.0, adj=0.0)[source]
Synthetic data with easy propensity and a difficult baseline

来自Nie X.和Wager S. (2018)的“Setup C”中的“异质治疗效应的准Oracle估计”

Parameters:
  • n (int, optional) – 观测值的数量

  • p (int 可选) – 协变量的数量 (>=3)

  • sigma (float) – 误差项的标准差

  • adj (float) – 无效果。为了保持一致性而添加

Returns:

使用以下输出生成的合成样本:
  • y ((n,)-数组): 结果变量。

  • X ((n,p)-ndarray): 自变量。

  • w ((n,)-数组): 处理标志,值为0或1。

  • tau ((n,)-数组): 个体处理效应。

  • b ((n,)-数组): 预期结果。

  • e ((n,)-数组): 接受处理的倾向。

Return type:

(元组)

causalml.dataset.simulate_hidden_confounder(n=10000, p=5, sigma=1.0, adj=0.0)[source]
Synthetic dataset with a hidden confounder biasing treatment.

来自Louizos等人(2018年)的“使用深度潜变量模型进行因果效应推断”

Parameters:
  • n (int, optional) – 观测值的数量

  • p (int 可选) – 协变量的数量 (>=3)

  • sigma (float) – 误差项的标准差

  • adj (float) – 无效果。为了保持一致性而添加

Returns:

使用以下输出生成的合成样本:
  • y ((n,)-数组): 结果变量。

  • X ((n,p)-ndarray): 自变量。

  • w ((n,)-数组): 处理标志,值为0或1。

  • tau ((n,)-数组): 个体处理效应。

  • b ((n,)-数组): 预期结果。

  • e ((n,)-数组): 接受处理的倾向。

Return type:

(元组)

causalml.dataset.simulate_nuisance_and_easy_treatment(n=1000, p=5, sigma=1.0, adj=0.0)[source]
Synthetic data with a difficult nuisance components and an easy treatment effect

来自Nie X.和Wager S. (2018)的“异质处理效应的准Oracle估计”中的设置A

Parameters:
  • n (int, optional) – 观测值的数量

  • p (int 可选) – 协变量的数量 (>=5)

  • sigma (float) – 误差项的标准差

  • adj (float) – 倾向分布的调整项,e。较高的值将分布向0移动。

Returns:

使用以下输出生成的合成样本:
  • y ((n,)-数组): 结果变量。

  • X ((n,p)-ndarray): 自变量。

  • w ((n,)-数组): 处理标志,值为0或1。

  • tau ((n,)-数组): 个体处理效应。

  • b ((n,)-数组): 预期结果。

  • e ((n,)-数组): 接受处理的倾向。

Return type:

(元组)

causalml.dataset.simulate_randomized_trial(n=1000, p=5, sigma=1.0, adj=0.0)[source]
Synthetic data of a randomized trial

来自Nie X.和Wager S.(2018)的“异质治疗效应的准Oracle估计”中的设置B

Parameters:
  • n (int, optional) – 观测值的数量

  • p (int 可选) – 协变量的数量 (>=5)

  • sigma (float) – 误差项的标准差

  • adj (float) – 无效果。为了保持一致性而添加

Returns:

使用以下输出生成的合成样本:
  • y ((n,)-数组): 结果变量。

  • X ((n,p)-ndarray): 自变量。

  • w ((n,)-数组): 处理标志,值为0或1。

  • tau ((n,)-数组): 个体处理效应。

  • b ((n,)-数组): 预期结果。

  • e ((n,)-数组): 接受处理的倾向。

Return type:

(元组)

causalml.dataset.simulate_unrelated_treatment_control(n=1000, p=5, sigma=1.0, adj=0.0)[source]
Synthetic data with unrelated treatment and control groups.

来自Nie X.和Wager S.(2018)的“异质治疗效应的准Oracle估计”中的设置D

Parameters:
  • n (int, optional) – 观测值的数量

  • p (int 可选) – 协变量的数量 (>=3)

  • sigma (float) – 误差项的标准差

  • adj (float) – 倾向分布的调整项,e。较高的值将分布向0移动。

Returns:

合成生成的样本具有以下输出:
  • y ((n,)-数组): 结果变量。

  • X ((n,p)-ndarray): 自变量。

  • w ((n,)-数组): 处理标志,值为0或1。

  • tau ((n,)-数组): 个体处理效应。

  • b ((n,)-数组): 预期结果。

  • e ((n,)-数组): 接受处理的倾向。

Return type:

(元组)

causalml.dataset.synthetic_data(mode=1, n=1000, p=5, sigma=1.0, adj=0.0)[source]

Nie X. 和 Wager S. (2018) 的合成数据《异质处理效应的准Oracle估计》 :param mode: 模拟的模式: 1 表示困难的干扰成分和简单的处理效应。 2 表示随机试验。 3 表示简单的倾向性和困难的基线。 4 表示无关的处理组和对照组。 5 表示隐藏的混淆因素导致处理偏差。 :type mode: int, 可选 :param n: 观测值的数量 :type n: int, 可选 :param p: 协变量的数量(>=5) :type p: int 可选 :param sigma: 误差项的标准差 :type sigma: float :param adj: 倾向性分布的调整项,e。较高的值将分布向0移动。

这不适用于 mode == 2 或 3。

Returns:

使用以下输出生成的合成样本:
  • y ((n,)-数组): 结果变量。

  • X ((n,p)-ndarray): 自变量。

  • w ((n,)-数组): 处理标志,值为0或1。

  • tau ((n,)-数组): 个体处理效应。

  • b ((n,)-数组): 预期结果。

  • e ((n,)-数组): 接受处理的倾向。

Return type:

(元组)

causalml.match 模块

class causalml.match.MatchOptimizer(treatment_col='is_treatment', ps_col='pihat', user_col=None, matching_covariates=['pihat'], max_smd=0.1, max_deviation=0.1, caliper_range=(0.01, 0.5), max_pihat_range=(0.95, 0.999), max_iter_per_param=5, min_users_per_group=1000, smd_cols=['pihat'], dev_cols_transformations={'pihat': <function mean>}, dev_factor=1.0, verbose=True)[source]

基础:object

check_table_one(tableone, matched, score_cols, pihat_threshold, caliper)[source]
match_and_check(score_cols, pihat_threshold, caliper)[source]
search_best_match(df)[source]
single_match(score_cols, pihat_threshold, caliper)[source]
class causalml.match.NearestNeighborMatch(caliper=0.2, replace=False, ratio=1, shuffle=True, treatment_to_control=True, random_state=None, n_jobs=-1)[source]

基础:object

基于最近邻算法的倾向得分匹配。

caliper

被视为匹配的阈值。

Type:

浮点数

replace

是否与替换匹配

Type:

布尔

ratio

控制/治疗组的匹配比例。

Type:

整数

shuffle

是否在匹配前打乱处理组数据

Type:

布尔

treatment_to_control

是否将治疗与对照匹配 或对照与治疗匹配

Type:

布尔

random_state

RandomState 或一个整数 种子

Type:

numpy.random.RandomState 或 int

n_jobs

用于邻居搜索的并行作业数量。 None 表示 1,除非在 joblib.parallel_backend 上下文中。-1 表示使用所有处理器

Type:

整数

match(data, treatment_col, score_cols)[source]

通过匹配指定列(倾向性优先)从对照组中找到匹配项。

Parameters:
  • data (pandas.DataFrame) – 总输入数据

  • treatment_col (str) – 处理组的列名

  • score_cols (list) – 用于匹配的列名列表(应包括倾向性列)

Returns:

由匹配数据组成的子集

处理组和对照组数据。

Return type:

(pandas.DataFrame)

match_by_group(data, treatment_col, score_cols, groupby_col)[source]

从按groupby_col分层的对照组中通过匹配指定列(倾向性优先)找到匹配项。

Parameters:
  • data (pandas.DataFrame) – 总样本数据

  • treatment_col (str) – 处理组的列名

  • score_cols (列表) – 用于匹配的列名列表(应包括倾向性列)

  • groupby_col (str) – 用于分层的列名

Returns:

由匹配数据组成的子集

处理组和对照组数据。

Return type:

(pandas.DataFrame)

causalml.match.create_table_one(data, treatment_col, features, with_std=True, with_counts=True)[source]

报告处理组和对照组之间输入特征的平衡情况。

参考文献

R的tableone在CRAN:https://github.com/kaz-yos/tableone Python的tableone在PyPi:https://github.com/tompollard/tableone

Parameters:
  • data (pandas.DataFrame) – 总体或匹配的样本数据

  • treatment_col (str) – 处理组的列名

  • 特征 (列表字符串) – 特征的列名

  • with_std (bool) – 是否以 ()格式输出标准差和均值

  • with_counts (bool) – 是否包含一行用于统计样本总数的计数

Returns:

一个包含均值和标准差的表格

治疗组和对照组,以及两组之间特征的SMD。

Return type:

(pandas.DataFrame)

causalml.match.smd(feature, treatment)[source]

计算特征在治疗组和对照组之间的标准均值差(SMD)。

定义可在 https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3144483/#s11title

Parameters:
  • 特征 (pandas.Series) – 用于计算SMD的特征列

  • treatment (pandas.Series) – 一个指示某行是否在治疗组中的列

Returns:

特征的SMD

Return type:

(浮点数)

causalml.propensity 模块

class causalml.propensity.ElasticNetPropensityModel(clip_bounds=(0.001, 0.999), **model_kwargs)[source]

基础:LogisticRegressionPropensityModel

class causalml.propensity.GradientBoostedPropensityModel(early_stop=False, clip_bounds=(0.001, 0.999), **model_kwargs)[source]

基础类: PropensityModel

带有可选早停的梯度提升倾向评分模型。

注释

请参阅xgboost文档以获取有关梯度提升调优参数的更多信息: https://xgboost.readthedocs.io/en/latest/python/python_api.html

fit(X, y, stop_val_size=0.2)[source]

拟合一个倾向模型。

Parameters:
  • X (numpy.ndarray) – 特征矩阵

  • y (numpy.ndarray) – 一个二元目标向量

predict(X)[source]

预测倾向得分。

Parameters:

X (numpy.ndarray) – 特征矩阵

Returns:

倾向得分在0到1之间。

Return type:

(numpy.ndarray)

class causalml.propensity.LogisticRegressionPropensityModel(clip_bounds=(0.001, 0.999), **model_kwargs)[source]

基础类: PropensityModel

基于LogisticRegression算法的倾向回归模型。

class causalml.propensity.PropensityModel(clip_bounds=(0.001, 0.999), **model_kwargs)[source]

基础:object

fit(X, y)[source]

拟合一个倾向模型。

Parameters:
  • X (numpy.ndarray) – 特征矩阵

  • y (numpy.ndarray) – 一个二元目标向量

fit_predict(X, y)[source]

拟合倾向模型并预测倾向得分。

Parameters:
  • X (numpy.ndarray) – 特征矩阵

  • y (numpy.ndarray) – 一个二分类目标向量

Returns:

倾向得分在0到1之间。

Return type:

(numpy.ndarray)

predict(X)[source]

预测倾向得分。

Parameters:

X (numpy.ndarray) – 特征矩阵

Returns:

倾向得分在0到1之间。

Return type:

(numpy.ndarray)

causalml.propensity.calibrate(ps, treatment)[source]

使用逻辑GAM校准倾向得分。

参考:https://pygam.readthedocs.io/en/latest/api/logisticgam.html

Parameters:
  • ps (numpy.array) – 一个倾向得分向量

  • treatment (numpy.array) – 一个二值处理向量(0:对照组,1:处理组)

Returns:

一个校准的倾向得分向量

Return type:

(numpy.array)

causalml.propensity.compute_propensity_score(X, treatment, p_model=None, X_pred=None, treatment_pred=None, calibrate_p=True)[source]

如果用户没有提供,生成倾向得分

Parameters:
  • X (np.matrix) – 用于训练的特征

  • treatment (np.arraypd.Series) – 用于训练的处理向量

  • p_model (倾向模型对象, 可选) – ElasticNetPropensityModel (默认) / GradientBoostedPropensityModel

  • X_pred (np.matrix, optional) – 用于预测的特征

  • treatment_pred (np.arraypd.Series, 可选) – 用于预测的处理向量

  • calibrate_p (bool, optional) – 是否校准倾向得分

Returns:

(元组)
  • p (numpy.ndarray): 倾向得分

  • p_model (PropensityModel): 一个训练好的PropensityModel对象

causalml.metrics 模块

class causalml.metrics.Sensitivity(df, inference_features, p_col, treatment_col, outcome_col, learner, *args, **kwargs)[source]

基础:object

一个敏感性检查类,用于支持安慰剂处理、无关额外混杂因素和子集验证反驳方法,以验证因果推断。

参考: https://github.com/microsoft/dowhy/blob/master/dowhy/causal_refuters/

get_ate_ci(X, p, treatment, y)[source]

返回治疗效果预测的置信区间。

Parameters:
  • X (np.matrix) – 特征矩阵

  • p (np.array) – 一个介于0和1之间的倾向得分向量

  • treatment (np.array) – 处理向量(1 表示处理,否则为 0)

  • y (np.array) – 一个结果向量

Returns:

ATE估计的均值和置信区间(LB, UB)。

Return type:

(numpy.ndarray)

static get_class_object(method_name, *args, **kwargs)[source]

根据输入方法返回类对象 :param method_name: 敏感性分析方法列表 :type method_name: 字符串列表

Returns:

敏感性类别

Return type:

(类)

get_prediction(X, p, treatment, y)[source]

返回治疗效果预测。

Parameters:
  • X (np.matrix) – 特征矩阵

  • p (np.array) – 一个介于0和1之间的倾向得分向量

  • treatment (np.array) – 处理向量(1 表示处理,否则为 0)

  • y (np.array) – 一个结果向量

Returns:

治疗效果预测

Return type:

(numpy.ndarray)

sensitivity_analysis(methods, sample_size=None, confound='one_sided', alpha_range=None)[source]

通过不同的方法返回敏感性数据

Parameters:
  • method (list of str) – 敏感性分析方法的列表

  • sample_size (float, optional) – 用于子集原始数据的比例

  • 混淆 (字符串, 可选) – 混淆函数的名称

  • alpha_range (np.array, optional) – 一个用于传递混淆函数的参数

Returns:

一个特征矩阵 p (np.array): 一个介于0和1之间的倾向得分向量 treatment (np.array): 一个处理向量(如果处理过则为1,否则为0) y (np.array): 一个结果向量

Return type:

X (np.matrix)

sensitivity_estimate()[source]
summary(method)[source]

总结报告 :param method_name: 敏感性分析方法 :type method_name: str

Returns:

一个摘要数据框

Return type:

(pd.DataFrame)

class causalml.metrics.SensitivityPlaceboTreatment(*args, **kwargs)[source]

基础:Sensitivity

用随机生成的新变量替换处理变量。

sensitivity_estimate()[source]

总结报告 :param return_ci: 敏感性分析方法 :type return_ci: str

Returns:

一个摘要数据框

Return type:

(pd.DataFrame)

class causalml.metrics.SensitivityRandomCause(*args, **kwargs)[source]

基础:Sensitivity

向数据框添加一个不相关的随机协变量。

sensitivity_estimate()[source]
class causalml.metrics.SensitivityRandomReplace(*args, **kwargs)[source]

基础类: Sensitivity

用一个不相关的变量替换一个随机协变量。

sensitivity_estimate()[source]

用一个不相关的变量替换一个随机协变量。

class causalml.metrics.SensitivitySelectionBias(*args, confound='one_sided', alpha_range=None, sensitivity_features=None, **kwargs)[source]

基础:Sensitivity

参考:

[1] 布莱克威尔, 马修. “因果效应敏感性分析的选择偏差方法.” 政治分析 22.2 (2014): 169-182. https://www.mattblackwell.org/files/papers/causalsens.pdf

[2] 混淆参数 alpha_range 使用与以下相同的范围: https://github.com/mattblackwell/causalsens/blob/master/R/causalsens.R

causalsens()[source]
static partial_rsqs_confounding(sens_df, feature_name, partial_rsqs_value, range=0.01)[source]

检查特征对应的混淆量的部分rsqs值 :param sens_df: 来自causalsens的数据框输出 :type sens_df: pandas.DataFrame :param feature_name: 要检查的特征名称 :type feature_name: str :param partial_rsqs_value: 特征的部分rsquare值 :type partial_rsqs_value: float :param range: 从sens_df中搜索的范围 :type range: float

返回:混杂量的最小值和最大值

static plot(sens_df, partial_rsqs_df=None, type='raw', ci=False, partial_rsqs=False)[source]

绘制敏感性分析的结果,针对未测量的变量 :param sens_df: 来自causalsens的数据框输出 :type sens_df: pandas.DataFrame :param partial_rsqs_d: 来自causalsens的数据框输出,包括部分rsqure :type partial_rsqs_d: pandas.DataFrame :param type: 绘图的类型,支持‘raw’或‘r.squared’ :type type: str, optional :param ci: 是否绘制置信区间 :type ci: bool, optional :param partial_rsqs: 是否绘制部分rsquare结果 :type partial_rsqs: bool, optional

summary(method='Selection Bias')[source]

选择偏差方法的总结报告 :param method_name: 敏感性分析方法 :type method_name: str

Returns:

一个摘要数据框

Return type:

(pd.DataFrame)

class causalml.metrics.SensitivitySubsetData(*args, **kwargs)[source]

基础:Sensitivity

从数据中随机抽取大小为 sample_size 的子集。

sensitivity_estimate()[source]
causalml.metrics.ape(y, p)[source]

绝对百分比误差 (APE)。 :param y: 目标 :type y: float :param p: 预测 :type p: float

Returns:

APE

Return type:

e (浮点数)

causalml.metrics.auuc_score(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', normalize=True, tmle=False, *args, **kwarg)[source]

计算AUUC(提升曲线下面积)得分。

Args:

df (pandas.DataFrame): 一个包含模型估计值和实际数据列的数据框 outcome_col (str, 可选): 实际结果的列名 treatment_col (str, 可选): 处理指示符的列名(0 或 1) treatment_effect_col (str, 可选): 真实处理效果的列名 normalize (bool, 可选): 是否将 y 轴归一化为 1

Returns:

AUUC 分数

Return type:

(浮点数)

causalml.metrics.classification_metrics(y, p, w=None, metrics={'AUC': <function roc_auc_score>, 'Log Loss': <function logloss>})[source]

记录分类器的指标。

Parameters:
  • y (numpy.array) – 目标

  • p (numpy.array) – 预测

  • w (numpy.array, 可选) – 一个处理向量(1 或 True:处理组,0 或 False:对照组)。如果提供,则分别记录处理组和对照组的指标

  • metrics (dict, optional) – 一个包含指标名称和函数的字典

causalml.metrics.get_cumgain(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', normalize=False, random_seed=42)[source]

获取模型估计在人口中的累积增益。

如果提供了真实的治疗效果(例如在合成数据中),则计算为每个群体中真实治疗效果的累积增益。否则,计算为每个群体中治疗组和对照组平均结果之间的累积差异。

详情请参见Gutierrez和G{‘e}rardy(2016)的第4.1节,因果推断和提升建模:文献综述

对于前者,应提供treatment_effect_col。对于后者,应同时提供outcome_coltreatment_col

Parameters:
  • df (pandas.DataFrame) – 一个包含模型估计值和实际数据作为列的数据框

  • outcome_col (str, optional) – 实际结果的列名

  • treatment_col (str, optional) – 治疗指示器的列名(0 或 1)

  • treatment_effect_col (str, optional) – 真实治疗效果的列名

  • normalize (bool, optional) – 是否将y轴归一化为1

  • random_seed (int, optional) – 已弃用

Returns:

模型估计在人口中的累积增益

Return type:

(pandas.DataFrame)

causalml.metrics.get_cumlift(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', random_seed=42)[source]

获取模型估计在累积人口中的平均提升。

如果提供了真实的治疗效果(例如在合成数据中),则计算为每个累积人口中真实治疗效果的均值。否则,计算为每个累积人口中治疗组和对照组结果均值的差异。

详情请参见Gutierrez和G{‘e}rardy(2016)的第4.1节,因果推断和提升建模:文献综述

对于前者,应提供treatment_effect_col。对于后者,应同时提供outcome_coltreatment_col

Parameters:
  • df (pandas.DataFrame) – 一个包含模型估计值和实际数据作为列的数据框

  • outcome_col (str, optional) – 实际结果的列名

  • treatment_col (str, optional) – 治疗指示器的列名(0 或 1)

  • treatment_effect_col (str, optional) – 真实治疗效果的列名

  • random_seed (int, optional) – 已弃用

Returns:

模型估计在累积人口中的平均提升

Return type:

(pandas.DataFrame)

causalml.metrics.get_qini(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', normalize=False, random_seed=42)[source]

获取模型中人口估计的Qini值。

如果提供了真实的治疗效果(例如在合成数据中),则计算为每个群体中真实治疗效果的累积增益。否则,计算为每个群体中治疗组和对照组平均结果之间的累积差异。

详情请参见Radcliffe (2007),使用控制组针对预测提升:构建和评估提升模型

对于前者,应提供treatment_effect_col。对于后者,应同时提供outcome_coltreatment_col

Parameters:
  • df (pandas.DataFrame) – 一个包含模型估计值和实际数据作为列的数据框

  • outcome_col (str, optional) – 实际结果的列名

  • treatment_col (str, optional) – 治疗指示器的列名(0 或 1)

  • treatment_effect_col (str, optional) – 真实治疗效果的列名

  • normalize (bool, optional) – 是否将y轴归一化为1

  • random_seed (int, optional) – 已弃用

Returns:

模型估计在人口中的累积增益

Return type:

(pandas.DataFrame)

causalml.metrics.get_tmlegain(df, inference_col, learner=LGBMRegressor(learning_rate=0.05, n_estimators=300, num_leaves=64), outcome_col='y', treatment_col='w', p_col='p', n_segment=5, cv=None, calibrate_propensity=True, ci=False)[source]

获取基于TMLE的模型估计分段的平均提升。

Parameters:
  • df (pandas.DataFrame) – 一个包含模型估计值和实际数据作为列的数据框

  • inferenece_col (list of str) – 用于推理的学习器中的列列表

  • learner (可选) – TMLE 用于估计结果的模型

  • outcome_col (str, optional) – 实际结果的列名

  • treatment_col (str, optional) – 治疗指示器的列名(0 或 1)

  • p_col (str, optional) – 倾向得分的列名

  • n_segment (int, optional) – TMLE 将为每个部分估计的段数

  • cv (sklearn.model_selection._BaseKFold, 可选) – sklearn 交叉验证对象

  • calibrate_propensity (bool, optional) – 是否校准倾向得分

  • ci (bool, optional) – 是否返回ATE的置信区间

Returns:

基于TMLE的模型估计的累积增益

Return type:

(pandas.DataFrame)

causalml.metrics.get_tmleqini(df, inference_col, learner=LGBMRegressor(learning_rate=0.05, n_estimators=300, num_leaves=64), outcome_col='y', treatment_col='w', p_col='p', n_segment=5, cv=None, calibrate_propensity=True, ci=False, normalize=False)[source]

获取基于TMLE的模型估计的Qini分段。

Parameters:
  • df (pandas.DataFrame) – 一个包含模型估计值和实际数据作为列的数据框

  • inferenece_col (list of str) – 用于推理的学习器中的列列表

  • learner (可选) – TMLE 用于估计结果的模型

  • outcome_col (str, optional) – 实际结果的列名

  • treatment_col (str, optional) – 治疗指示器的列名(0 或 1)

  • p_col (str, optional) – 倾向得分的列名

  • n_segment (int, optional) – TMLE将为每个部分估计的段数

  • cv (sklearn.model_selection._BaseKFold, 可选) – sklearn 交叉验证对象

  • calibrate_propensity (bool, optional) – 是否校准倾向得分

  • ci (bool, 可选) – 是否返回ATE的置信区间

Returns:

基于TMLE的模型估计的累积增益

Return type:

(pandas.DataFrame)

causalml.metrics.gini(y, p)[source]

归一化基尼系数。

Parameters:
  • y (numpy.array) – 目标

  • p (numpy.array) – 预测

Returns:

归一化基尼系数

Return type:

e (numpy.float64)

causalml.metrics.logloss(y, p)[source]

有界对数损失误差。 :param y: 目标 :type y: numpy.array :param p: 预测 :type p: numpy.array

Returns:

有界对数损失误差

causalml.metrics.mae(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average')

平均绝对误差回归损失。

了解更多信息,请参阅用户指南

Parameters:
  • y_true (array-like of shape (n_samples,) or (n_samples, n_outputs)) – 真实(正确)的目标值。

  • y_pred (数组形式,形状为 (n_samples,) 或 (n_samples, n_outputs)) – 估计的目标值。

  • sample_weight (array-like of shape (n_samples,), default=None) – 样本权重。

  • multioutput ({'raw_values', 'uniform_average'}array-likeshape (n_outputs,), default='uniform_average') –

    定义多个输出值的聚合方式。 类似数组的值定义了用于平均误差的权重。

    ’raw_values’ :

    在多输出输入的情况下返回完整的误差集。

    ’uniform_average’ :

    所有输出的误差以均匀权重平均。

Returns:

loss – 如果 multioutput 是 'raw_values',则分别返回每个输出的平均绝对误差。 如果 multioutput 是 'uniform_average' 或权重的 ndarray,则返回所有输出误差的加权平均值。

MAE 输出是非负浮点数。最佳值为 0.0。

Return type:

浮点数或浮点数数组

示例

>>> from sklearn.metrics import mean_absolute_error
>>> y_true = [3, -0.5, 2, 7]
>>> y_pred = [2.5, 0.0, 2, 8]
>>> mean_absolute_error(y_true, y_pred)
np.float64(0.5)
>>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
>>> y_pred = [[0, 2], [-1, 2], [8, -5]]
>>> mean_absolute_error(y_true, y_pred)
np.float64(0.75)
>>> mean_absolute_error(y_true, y_pred, multioutput='raw_values')
array([0.5, 1. ])
>>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7])
np.float64(0.85...)
causalml.metrics.mape(y, p)[source]

平均绝对百分比误差 (MAPE)。 :param y: 目标 :type y: numpy.array :param p: 预测 :type p: numpy.array

Returns:

平均绝对百分比误差

Return type:

e (numpy.float64)

causalml.metrics.plot(df, kind='gain', tmle=False, n=100, figsize=(8, 8), ci=False, plot_chance_level=True, chance_level_kw=None, *args, **kwarg)[source]

绘制模型估计的提升/增益/Qini图表之一。

一个用于plot_lift()plot_gain()plot_qini()plot_tmlegain()plot_tmleqini()的工厂方法。 详情请参阅每个函数的文档字符串。

Parameters:
  • df (pandas.DataFrame) – 一个包含模型估计值和实际数据作为列的数据框。

  • kind (str, optional) – 绘制的图表类型。支持 'lift'、'gain' 和 'qini'。

  • n (int, optional) – 用于绘图的样本数量。

  • figsize (set of float, optional) – 要绘制的图形的大小。

  • ci (bool, optional) – 是否绘制置信区间。仅在tmle=True时可用。 默认值为False。

  • plot_chance_level (bool, optional) – 是否绘制机会水平(即随机)线。 默认值为 True。

  • chance_level_line_kw (dict, optional) – 用于机会水平线的关键字参数。默认值为 None。

  • *args – 可变长度参数列表。

  • **kwargs – 任意关键字参数。

causalml.metrics.plot_gain(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', normalize=False, random_seed=42, n=100, figsize=(8, 8))[source]

绘制模型估计的累积增益图(或提升曲线)。

如果提供了真实的治疗效果(例如在合成数据中),则计算为每个群体中真实治疗效果的累积增益。否则,计算为每个群体中治疗组和对照组平均结果之间的累积差异。

详情请参见Gutierrez和G{‘e}rardy(2016)的第4.1节,因果推断和提升建模:文献综述

对于前者,应提供treatment_effect_col。对于后者,应同时提供outcome_coltreatment_col

Parameters:
  • df (pandas.DataFrame) – 一个包含模型估计值和实际数据作为列的数据框

  • outcome_col (str, optional) – 实际结果的列名

  • treatment_col (str, optional) – 治疗指示器的列名(0 或 1)

  • treatment_effect_col (str, optional) – 真实治疗效果的列名

  • normalize (bool, optional) – 是否将y轴归一化为1

  • random_seed (int, optional) – numpy.random.rand() 的随机种子

  • n (int, optional) – 用于绘图的样本数量

causalml.metrics.plot_lift(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', random_seed=42, n=100, figsize=(8, 8))[source]

绘制模型估计在累积人口中的提升图。

如果提供了真实的治疗效果(例如在合成数据中),则计算为每个累积人口中真实治疗效果的均值。否则,计算为每个累积人口中治疗组和对照组结果均值的差异。

详情请参见Gutierrez和G{‘e}rardy(2016)的第4.1节,因果推断和提升建模:文献综述

对于前者,应提供treatment_effect_col。对于后者,应同时提供outcome_coltreatment_col

Parameters:
  • df (pandas.DataFrame) – 一个包含模型估计值和实际数据作为列的数据框

  • outcome_col (str, optional) – 实际结果的列名

  • treatment_col (str, optional) – 治疗指示器的列名(0 或 1)

  • treatment_effect_col (str, optional) – 真实治疗效果的列名

  • random_seed (int, optional) – 已弃用

  • n (int, optional) – 用于绘图的样本数量

causalml.metrics.plot_qini(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', normalize=False, random_seed=42, n=100, figsize=(8, 8))[source]

绘制模型估计的Qini图(或提升曲线)。

如果提供了真实的治疗效果(例如在合成数据中),则计算为每个群体中真实治疗效果的累积增益。否则,计算为每个群体中治疗组和对照组平均结果之间的累积差异。

详情请参见Radcliffe (2007),使用控制组针对预测提升:构建和评估提升模型

对于前者,应提供treatment_effect_col。对于后者,应同时提供outcome_coltreatment_col

Parameters:
  • df (pandas.DataFrame) – 一个包含模型估计值和实际数据作为列的数据框

  • outcome_col (str, optional) – 实际结果的列名

  • treatment_col (str, optional) – 治疗指示器的列名(0 或 1)

  • treatment_effect_col (str, optional) – 真实治疗效果的列名

  • normalize (bool, optional) – 是否将y轴归一化为1

  • random_seed (int, optional) – 已弃用

  • n (int, optional) – 用于绘图的样本数量

  • ci (bool, 可选) – 是否返回ATE的置信区间

causalml.metrics.plot_tmlegain(df, inference_col, learner=LGBMRegressor(learning_rate=0.05, n_estimators=300, num_leaves=64, verbose=-1), outcome_col='y', treatment_col='w', p_col='tau', n_segment=5, cv=None, calibrate_propensity=True, ci=False, figsize=(8, 8))[source]

基于TMLE估计绘制提升图

Parameters:
  • df (pandas.DataFrame) – 一个包含模型估计值和实际数据作为列的数据框

  • inferenece_col (list of str) – 用于推理的学习器中的列列表

  • learner (可选) – TMLE 用于估计结果的模型

  • outcome_col (str, optional) – 实际结果的列名

  • treatment_col (str, optional) – 治疗指示器的列名(0 或 1)

  • p_col (str, optional) – 倾向得分的列名

  • n_segment (int, optional) – TMLE将为每个部分估计的段数

  • cv (sklearn.model_selection._BaseKFold, 可选) – sklearn 交叉验证对象

  • calibrate_propensity (bool, optional) – 是否校准倾向得分

  • ci (bool, 可选) – 是否返回ATE的置信区间

causalml.metrics.plot_tmleqini(df, inference_col, learner=LGBMRegressor(learning_rate=0.05, n_estimators=300, num_leaves=64), outcome_col='y', treatment_col='w', p_col='tau', n_segment=5, cv=None, calibrate_propensity=True, ci=False, figsize=(8, 8))[source]

基于TMLE估计绘制qini图表

Parameters:
  • df (pandas.DataFrame) – 一个包含模型估计值和实际数据作为列的数据框

  • inferenece_col (list of str) – 用于推理的学习器中的列列表

  • learner (可选) – TMLE 用于估计结果的模型

  • outcome_col (str, optional) – 实际结果的列名

  • treatment_col (str, optional) – 治疗指示器的列名(0 或 1)

  • p_col (str, optional) – 倾向得分的列名

  • n_segment (int, optional) – TMLE将为每个部分估计的段数

  • cv (sklearn.model_selection._BaseKFold, 可选) – sklearn 交叉验证对象

  • calibrate_propensity (bool, optional) – 是否校准倾向得分

  • ci (bool, 可选) – 是否返回ATE的置信区间

causalml.metrics.qini_score(df, outcome_col='y', treatment_col='w', treatment_effect_col='tau', normalize=True, tmle=False, *args, **kwarg)[source]

计算Qini分数:模型和随机的Qini曲线之间的面积。

详情请参见Radcliffe (2007),使用控制组针对预测提升:构建和评估提升模型

Args:

df (pandas.DataFrame): 一个包含模型估计值和实际数据列的数据框 outcome_col (str, 可选): 实际结果的列名 treatment_col (str, 可选): 处理指示符的列名(0 或 1) treatment_effect_col (str, 可选): 真实处理效果的列名 normalize (bool, 可选): 是否将 y 轴归一化为 1

Returns:

七牛分数

Return type:

(浮点数)

causalml.metrics.r2_score(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average', force_finite=True)[source]

\(R^2\)(决定系数)回归评分函数。

最佳可能的分数是1.0,它也可能是负数(因为模型可能任意更差)。在一般情况下,当真实的y不是常数时,一个总是预测平均y而不考虑输入特征的常数模型将获得\(R^2\)分数为0.0。

在特定情况下,当y_true是常数时,\(R^2\)分数 不是有限的:它要么是NaN(完美预测)要么是-Inf (不完美预测)。为了防止这些非有限数字污染 更高级别的实验,如网格搜索交叉验证,默认情况下 这些情况分别被替换为1.0(完美预测)或0.0(不完美 预测)。你可以将force_finite设置为False来 防止这种修复发生。

注意:当预测残差的均值为零时,\(R^2\) 分数与 Explained Variance score 相同。

了解更多信息,请参阅用户指南

Parameters:
  • y_true (array-like of shape (n_samples,) or (n_samples, n_outputs)) – 真实(正确)的目标值。

  • y_pred (数组形式,形状为 (n_samples,) 或 (n_samples, n_outputs)) – 估计的目标值。

  • sample_weight (array-like of shape (n_samples,), default=None) – 样本权重。

  • multioutput ({'raw_values', 'uniform_average', 'variance_weighted'}, array-like of shape (n_outputs,) or None, default='uniform_average') –

    定义多个输出分数的聚合方式。 类数组值定义了用于平均分数的权重。 默认值为“uniform_average”。

    ’raw_values’ :

    在多输出输入的情况下返回完整的分数集。

    ’uniform_average’ :

    所有输出的分数以均匀权重平均。

    ’variance_weighted’ :

    所有输出的分数以每个单独输出的方差加权平均。

    在版本0.19中更改:multioutput的默认值为‘uniform_average’。

  • force_finite (bool, default=True) –

    标志,指示是否应将由常数数据导致的NaN-Inf分数替换为实数(如果预测完美则为1.0,否则为0.0)。默认值为True,这是超参数搜索过程(例如网格搜索交叉验证)的便捷设置。

    在版本1.1中添加。

Returns:

z – 如果 'multioutput' 是 'raw_values',则为 \(R^2\) 分数或分数数组。

Return type:

浮点数或浮点数数组

注释

这不是一个对称函数。

与大多数其他分数不同,\(R^2\) 分数可能为负数(它实际上不必是量 R 的平方)。

该指标对于单个样本没有明确定义,如果n_samples小于2,将返回NaN值。

参考文献

示例

>>> from sklearn.metrics import r2_score
>>> y_true = [3, -0.5, 2, 7]
>>> y_pred = [2.5, 0.0, 2, 8]
>>> r2_score(y_true, y_pred)
0.948...
>>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
>>> y_pred = [[0, 2], [-1, 2], [8, -5]]
>>> r2_score(y_true, y_pred,
...          multioutput='variance_weighted')
0.938...
>>> y_true = [1, 2, 3]
>>> y_pred = [1, 2, 3]
>>> r2_score(y_true, y_pred)
1.0
>>> y_true = [1, 2, 3]
>>> y_pred = [2, 2, 2]
>>> r2_score(y_true, y_pred)
0.0
>>> y_true = [1, 2, 3]
>>> y_pred = [3, 2, 1]
>>> r2_score(y_true, y_pred)
-3.0
>>> y_true = [-2, -2, -2]
>>> y_pred = [-2, -2, -2]
>>> r2_score(y_true, y_pred)
1.0
>>> r2_score(y_true, y_pred, force_finite=False)
nan
>>> y_true = [-2, -2, -2]
>>> y_pred = [-2, -2, -2 + 1e-8]
>>> r2_score(y_true, y_pred)
0.0
>>> r2_score(y_true, y_pred, force_finite=False)
-inf
causalml.metrics.regression_metrics(y, p, w=None, metrics={'Gini': <function gini>, 'RMSE': <function rmse>, 'sMAPE': <function smape>})[source]

记录回归器的指标。

Parameters:
  • y (numpy.array) – 目标

  • p (numpy.array) – 预测

  • w (numpy.array, 可选) – 一个处理向量(1 或 True:处理组,0 或 False:对照组)。如果提供,则分别记录处理组和对照组的指标

  • metrics (dict, optional) – 一个包含指标名称和函数的字典

causalml.metrics.rmse(y, p)[source]

均方根误差 (RMSE)。 :param y: 目标 :type y: numpy.array :param p: 预测 :type p: numpy.array

Returns:

均方根误差

Return type:

e (numpy.float64)

causalml.metrics.roc_auc_score(y_true, y_score, *, average='macro', sample_weight=None, max_fpr=None, multi_class='raise', labels=None)[source]

从预测分数计算接收者操作特征曲线下的面积(ROC AUC)。

注意:此实现可用于二元、多类和多标签分类,但有一些限制适用(参见参数)。

了解更多信息,请参阅用户指南

Parameters:
  • y_true (数组形式,形状为 (n_samples,) 或 (n_samples, n_classes)) – 真实标签或二进制标签指示器。二分类和多分类情况期望标签的形状为 (n_samples,),而多标签情况期望二进制标签指示器的形状为 (n_samples, n_classes)。

  • y_score (数组形式,形状为 (n_samples,) 或 (n_samples, n_classes)) –

    目标分数。

    • 在二分类情况下,它对应于形状为 (n_samples,)的数组。可以提供概率估计和非阈值决策值。概率估计对应于 具有较大标签的类别的概率, 即 estimator.classes_[1]estimator.predict_proba(X, y)[:, 1]。决策值对应于 estimator.decision_function(X, y)的输出。 更多信息请参见用户指南;

    • 在多分类情况下,它对应于形状为 (n_samples, n_classes)的数组,由 predict_proba方法提供的概率估计。概率估计必须 在所有可能的类别上总和为1。此外,类别分数的顺序必须对应于 labels的顺序, 如果提供了,否则对应于y_true中标签的数值或字典顺序。 更多信息请参见用户指南;

    • 在多标签情况下,它对应于形状为 (n_samples, n_classes)的数组。概率估计由 predict_proba方法提供,非阈值决策值由 decision_function方法提供。概率估计对应于 分类器每个输出的具有较大标签的类别的概率。 更多信息请参见用户指南.

  • average ({'micro', 'macro', 'samples', 'weighted'}None, default='macro') –

    如果 None,则返回每个类的分数。 否则,这将确定对数据执行的平均类型。 注意:多类 ROC AUC 目前仅处理 'macro' 和 'weighted' 平均值。对于多类目标,average=None 仅 在 multi_class=’ovr’ 时实现,而 average=’micro’ 仅 在 multi_class=’ovr’ 时实现。

    'micro':

    通过将标签指示矩阵的每个元素视为标签来全局计算指标。

    'macro':

    计算每个标签的指标,并找到它们的未加权 平均值。这不考虑标签不平衡。

    'weighted':

    计算每个标签的指标,并找到它们的加权平均值, 权重由支持度(每个标签的真实实例数)决定。

    'samples':

    计算每个实例的指标,并找到它们的平均值。

    y_true 是二分类时将被忽略。

  • sample_weight (array-like of shape (n_samples,), default=None) – 样本权重。

  • max_fpr (float > 0 and <= 1, default=None) – 如果不是 None,则返回在 [0, max_fpr] 范围内的标准化部分 AUC [2]。对于多分类情况,max_fpr 应等于 None1.0,因为目前不支持多分类的 AUC ROC 部分计算。

  • multi_class ({'raise', 'ovr', 'ovo'}, default='raise') –

    仅用于多类目标。确定要使用的配置类型。默认值会引发错误,因此必须显式传递'ovr''ovo'

    'ovr':

    代表一对多(One-vs-rest)。计算每个类与其余类的AUC [3] [4]。这将多类情况与多标签情况处理方式相同。即使average == 'macro',对类别不平衡也很敏感,因为类别不平衡会影响每个“其余”分组的组成。

    'ovo':

    代表一对一(One-vs-one)。计算所有可能的类别两两组合的平均AUC [5]。当average == 'macro'时,对类别不平衡不敏感。

  • labels (array-like of shape (n_classes,), default=None) – 仅用于多类目标。用于索引y_score中类别的标签列表。如果None,则使用y_true中标签的数值或字典顺序。

Returns:

auc – 曲线下面积得分。

Return type:

浮点数

另请参阅

average_precision_score

精确率-召回率曲线下的面积。

roc_curve

计算接收者操作特征(ROC)曲线。

RocCurveDisplay.from_estimator

绘制接收者操作特征(ROC)曲线,给定一个估计器和一些数据。

RocCurveDisplay.from_predictions

根据真实值和预测值绘制接收者操作特征(ROC)曲线。

注释

基尼系数是二元分类器排序能力的总结度量。它使用ROC曲线下的面积表示如下:

G = 2 * AUC - 1

其中 G 是基尼系数,AUC 是 ROC-AUC 分数。这种归一化将确保随机猜测在期望中得分为 0,并且它的上限为 1。

参考文献

示例

二元情况:

>>> from sklearn.datasets import load_breast_cancer
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.metrics import roc_auc_score
>>> X, y = load_breast_cancer(return_X_y=True)
>>> clf = LogisticRegression(solver="liblinear", random_state=0).fit(X, y)
>>> roc_auc_score(y, clf.predict_proba(X)[:, 1])
np.float64(0.99...)
>>> roc_auc_score(y, clf.decision_function(X))
np.float64(0.99...)

多类别情况:

>>> from sklearn.datasets import load_iris
>>> X, y = load_iris(return_X_y=True)
>>> clf = LogisticRegression(solver="liblinear").fit(X, y)
>>> roc_auc_score(y, clf.predict_proba(X), multi_class='ovr')
np.float64(0.99...)

多标签情况:

>>> import numpy as np
>>> from sklearn.datasets import make_multilabel_classification
>>> from sklearn.multioutput import MultiOutputClassifier
>>> 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_pred = clf.predict_proba(X)
>>> # extract the positive columns for each output
>>> y_pred = np.transpose([pred[:, 1] for pred in y_pred])
>>> roc_auc_score(y, y_pred, average=None)
array([0.82..., 0.86..., 0.94..., 0.85... , 0.94...])
>>> from sklearn.linear_model import RidgeClassifierCV
>>> clf = RidgeClassifierCV().fit(X, y)
>>> roc_auc_score(y, clf.decision_function(X), average=None)
array([0.81..., 0.84... , 0.93..., 0.87..., 0.94...])
causalml.metrics.smape(y, p)[source]

对称平均绝对百分比误差 (sMAPE)。 :param y: 目标 :type y: numpy.array :param p: 预测 :type p: numpy.array

Returns:

对称平均绝对百分比误差

Return type:

e (numpy.float64)

causalml.feature_selection 模块

class causalml.feature_selection.FilterSelect[source]

基础:object

用于特征重要性方法的类。

filter_D(data, features, y_name, n_bins=10, method='KL', control_group='control', experiment_group_column='treatment_group_key', null_impute=None)[source]

根据选定的散度度量对特征进行排序。

Parameters:
  • data (pd.Dataframe) – 包含结果、特征和实验组的DataFrame

  • treatment_indicator (string) – 用于表示处理(1)或控制(0)的二进制指示器的列名

  • 特征 (列表 of 字符串) – 特征名称的列表,这些特征是数据DataFrame中的列

  • y_name (string) – 结果变量的名称

  • method (string, optional, default = 'KL') – 取以下值之一 {‘F’, ‘LR’, ‘KL’, ‘ED’, ‘Chi’} 用于对特征进行排序的特征选择方法。 ‘F’ 表示 F 检验 ‘LR’ 表示似然比检验 ‘KL’, ‘ED’, ‘Chi’ 分别表示基于分箱的提升过滤方法,KL 散度,欧几里得距离,卡方检验

  • experiment_group_column (string, optional, default = 'treatment_group_key') – DataFrame中的实验列名,包含处理和对照分配的标签

  • control_group (string, optional, default = 'control') – 控制组的名称,实验组列中的值

  • n_bins (int, optional, default = 10) – 用于基于分箱的提升过滤方法的箱数

  • null_impute (str, optional, default=None) – 对数据中存在的 np.nan 进行填补,采用以下策略值之一 {'mean', 'median', 'most_frequent', None}。如果值为 None 且存在空值,则会引发异常。

Returns:

pd.DataFrame

包含特征重要性统计的数据框

Return type:

所有结果

filter_F(data, treatment_indicator, features, y_name, order=1)[source]

基于交互作用的F统计量对特征进行排序。

Parameters:
  • data (pd.Dataframe) – 包含结果、特征和实验组的DataFrame

  • treatment_indicator (string) – 用于表示处理(1)或控制(0)的二进制指示器的列名

  • 特征 (列表 of 字符串) – 特征名称的列表,这些特征是数据DataFrame中的列

  • y_name (string) – 结果变量的名称

  • order (int) – 用于评估处理效果的特征的顺序,order 取 3 个值:1,2,3。 order = 1 对应于特征的线性重要性,order=2 对应于特征的二次和线性重要性,

  • forms. (order= 3 将计算特征重要性直到立方)

Returns:

pd.DataFrame

包含特征重要性统计的数据框

Return type:

所有结果

filter_LR(data, treatment_indicator, features, y_name, order=1, disp=True)[source]

基于交互的LRT统计量对特征进行排序。

Parameters:
  • data (pd.Dataframe) – 包含结果、特征和实验组的DataFrame

  • treatment_indicator (string) – 用于表示处理(1)或控制(0)的二进制指示器的列名

  • feature_name (string) – 特征名称,作为数据DataFrame中的一列

  • y_name (string) – 结果变量的名称

  • order (int) – 用于评估处理效果的特征的顺序,order 可以取 3 个值:1,2,3。 order = 1 对应于特征的线性重要性,order=2 对应于特征的二次和线性重要性,

  • forms. (order= 3 将计算特征重要性直到立方)

Returns:

pd.DataFrame

包含特征重要性统计的数据框

Return type:

所有结果

get_importance(data, features, y_name, method, experiment_group_column='treatment_group_key', control_group='control', treatment_group='treatment', n_bins=5, null_impute=None, order=1, disp=False)[source]

根据所选交互统计量对特征进行排序。

Parameters:
  • data (pd.Dataframe) – 包含结果、特征和实验组的DataFrame

  • 特征 (列表 of 字符串) – 特征名称的列表,这些特征是数据DataFrame中的列

  • y_name (string) – 结果变量的名称

  • method (string, optional, default = 'KL') – 取以下值之一 {‘F’, ‘LR’, ‘KL’, ‘ED’, ‘Chi’} 用于对特征进行排序的特征选择方法。 ‘F’ 表示 F 检验 ‘LR’ 表示似然比检验 ‘KL’, ‘ED’, ‘Chi’ 分别表示基于分箱的提升过滤方法,KL 散度,欧几里得距离,卡方检验

  • experiment_group_column (string) – DataFrame中的实验列名称,包含处理和对照分配的标签

  • control_group (string) – 控制组的名称,实验组列中的值

  • treatment_group (string) – 实验组的名称,实验组列中的值

  • n_bins (int, optional) – 用于基于分箱的提升过滤方法的箱数

  • null_impute (str, optional, default=None) – 对数据中存在的 np.nan 进行填补,采用以下策略之一 {'mean', 'median', 'most_frequent', None}。如果值为 None 且存在空值,则会引发异常

  • order (int) – 用于评估F过滤器和LR过滤器处理效果的特征的顺序, order 取3个值:1,2,3。order = 1 对应于特征的线性重要性,order=2 对应于特征的二次和线性重要性,

  • forms. (order= 3 将计算特征重要性直到立方)

  • disp (bool) – 设置为True以打印LR方法中逻辑回归收敛的收敛消息。

Returns:

pd.DataFrame

一个包含以下列的数据框:[‘method’, ‘feature’, ‘rank’, ‘score’, ‘p_value’, ‘misc’]

Return type:

所有结果

causalml.features 模块

class causalml.features.LabelEncoder(min_obs=10)[source]

基础:BaseEstimator

将不常见值分组为一个标签的标签编码器。

代码来自 https://github.com/jeongyoonlee/Kaggler/blob/master/kaggler/preprocessing/data.py

min_obs

分配标签所需的最小观察数。

Type:

整数

label_encoders

列的标签编码器

Type:

字典列表

label_maxes

列标签的最大值

Type:

整数列表

fit(X, y=None)[source]
fit_transform(X, y=None)[source]

将分类列编码为标签编码列

Parameters:

X (pandas.DataFrame) – 要编码的分类列

Returns:

标签编码列

Return type:

X (pandas.DataFrame)

transform(X)[source]

将分类列编码为标签编码列

Parameters:

X (pandas.DataFrame) – 要编码的分类列

Returns:

标签编码列

Return type:

X (pandas.DataFrame)

class causalml.features.OneHotEncoder(min_obs=10)[source]

基础:BaseEstimator

将不常见值分组到一个虚拟变量中的One-Hot-Encoder。

代码来自 https://github.com/jeongyoonlee/Kaggler/blob/master/kaggler/preprocessing/data.py

min_obs

创建虚拟变量的最小观测数

Type:

整数

label_encoders

标签编码器及其最大值 对于列

Type:

(字典,整数)列表

fit(X, y=None)[source]
fit_transform(X, y=None)[source]

将分类列编码为使用独热编码的稀疏矩阵。

Parameters:

X (pandas.DataFrame) – 要编码的分类列

Returns:

稀疏矩阵将分类变量编码为虚拟变量

transform(X)[source]

将分类列编码为使用独热编码的稀疏矩阵。

Parameters:

X (pandas.DataFrame) – 要编码的分类列

Returns:

稀疏矩阵编码分类

变量转换为虚拟变量

Return type:

X_new (scipy.sparse.coo_matrix)

causalml.features.load_data(data, features, transformations={})[source]

加载数据并设置特征矩阵和标签向量。

Parameters:
  • data (pandas.DataFrame) – 总输入数据

  • 特征 (列表字符串) – 用于推理模型的列名

  • 转换 (字典(字符串, 函数)) – 应用于特征的转换

Returns:

一个特征矩阵

Return type:

X (numpy.matrix)

模块内容