P paper2skillsPlaybook
开始业务诊断
访客模式
13-广告分析

Identity Fragmentation Debiasing(身份碎片化纠偏)

Skill-Identity-Fragmentation-Debiasing

声明类型推断验证状态待复核

业务问题:女装独立站通过 Instagram(手机端)大量投放信息流广告

来源
paper2skills-vault/13-广告分析/Skill-Identity-Fragmentation-Debiasing.md
适用边界
论文方法到业务问题的项目侧映射,不自动证明客户根因。
声明类型示例验证状态待企业数据验证

每分广告预算有明确 ROI 追踪,砍掉低效渠道后同等预算 ROAS 提升 30-50%

来源
paper2skills-vault/13-广告分析/Skill-Identity-Fragmentation-Debiasing.md#business-value
适用边界
方法估算或场景示例,不等于客户结果或收益承诺。

待企业数据验证 · 缺失:样本、基线、时间窗、币种、计算方法、证据来源

业务视角
适用角色广告优化师 / 投放负责人 · CMO · 运营负责人
适用平台Amazon PPC(SP/SB/SD)· TikTok Ads · Meta 广告 · 多平台归因
什么情况下用广告账户几十个系列,不知道哪个在真正赚钱;ROAS 看起来好看但实际利润没有提升;预算有限想集中打高价值用户
示例目标(需企业数据验证)每分广告预算有明确 ROI 追踪,砍掉低效渠道后同等预算 ROAS 提升 30-50%
业务痛点
ROAS 好看但利润没有涨不知道哪个素材真的有效归因窗口期不同数据打架TikTok/Meta/Amazon 广告数据整合不了

1. 解决的问题

业务问题:女装独立站通过 Instagram(手机端)大量投放信息流广告

2. 核心算法逻辑

核心思想:用户在多设备间切换(手机看广告、电脑下单)导致底层 Cookie/IDFA 无法跨端串联,同一真实用户被拆分为多个"碎片化身份"。这使得广告平台看到的 ROAS 严重失真——有的记录"只有曝光没有购买",有的记录"只有购买没有广告"。算法通过 Stratified Aggregation(分层聚合) 在 Cohort 层面重建真实曝光与购买的对应关系,无需跨设备图谱,还原因果 ROI。

数学直觉:

碎片化用户在设备级别产生两条对立记录:

  • 手机端:$(exposed_i = 1, \; converted_i = 0)$ ← 曝光但未在手机购买
  • 桌面端:$(exposed_j = 0, \; converted_j = 1)$ ← 购买但系统不知曾曝光

朴素 ATE 估计 $\hat\tau_{naive} = \bar{Y}_{exposed} - \bar{Y}_{control}$ 在设备级计算时,碎片化用户的购买全部落入对照组,抬高 $\bar{Y}_{control}$,导致 $\hat\tau_{naive}$ 严重偏离真实值。

Stratified Aggregation 纠偏:在 Cohort $k$ 内,按 user\_id 将多条设备记录聚合为单条用户记录(取各字段的 OR/max),还原真实状态:

\tilde{exposed}_u = \max_{d \in D_u} exposed_{u,d}, \quad \tilde{converted}_u = \max_{d \in D_u} converted_{u,d}

然后在用户层面计算 Cohort-level ATE,全局加权平均:

\hat\tau_{SA} = \sum_k \frac{N_k}{N} \cdot \left(\bar{Y}^{(k)}_{exposed} - \bar{Y}^{(k)}_{control}\right)

关键假设:

  1. 碎片化用户的所有设备记录位于同一 Cohort(地区/时段/语言特征相同)
  2. Cohort 内用户的异质性 (confounding) 在曝光组与对照组之间均匀分布
  3. 每个 Cohort 至少有 20+ 用户(否则统计功效不足)

实测锚点(③ 的 A1–A8 断言跑出来的值;夹具 3000 真实用户 / seed 2024 / 真值 ad_lift = 0.06)

  • 断链形态是结构性的:371 人被拆成 2 条记录(手机端 converted 恒 0,桌面端 exposed 恒 0),

设备级日志 3371 行 vs 真实用户 3000 人。注意 fragmentation_rate=0.40 只作用于高活跃人群, 总体碎片化率实测 12.4%,不能按参数名望文生义(③ 里有这条对账断言)。

  • 朴素口径低估 2.78 倍:设备级 ATE 0.0216 vs 真值 0.06;纠偏后 0.0548(误差 0.0052)。
  • 纠偏到底还原了什么,可以直接数出来:设备级"既曝光又转化"只有 320 行,

按 user_id 取 max 聚合后变成 379 人,多出的 59 人正是被断链的碎片化用户。

  • 偏差归因给碎片化而不是方法:同一套朴素算法只取未碎片化的单设备用户,ATE = 0.0555,

已经贴着真值 0.06 —— 断链才是偏差源,不是分层聚合本身。

  • ROI 提升不是纯赚:ROI 倍数 2.26 = ATE 倍数 2.54 ÷ 记录/用户比 1.12(③ A6 断言该恒等式)。
  • ① 假设 3 是可执行的下限:min_cohort_size 抬到无人满足时,corrected_roi() 抛

RuntimeError("拒绝给出 ATE")而不是静默返回 0 —— 静默 0 会被业务读成"广告无效"。

  • 8 个 Cohort 全部保留,每个 Cohort 的 ate 都落在自身 95% CI 内,CI 宽度中位数 0.1605

(单 Cohort 粒度远粗于全局,这也是 ① 只做加权汇总的原因)。

3. 业务应用场景

业务问题:女装独立站通过 Instagram(手机端)大量投放信息流广告。后台报表显示广告 CVR 极低(曝光了但转化接近 0),财务部门准备砍掉 Instagram 预算。真实情况是:高活跃用户在手机看到广告后,习惯切换到电脑上完成购买——这部分转化在设备级日志中被完全"断链",无法归因到 Instagram。

数据要求: - 字段:`user_id(或邮箱哈希/手机号哈希)| device_id | cohort(地区+时段) | exposed | converted` - 数据源:Instagram Ads API(曝光数据)+ Shopify 后台(订单数据,含 UTM 来源) - 如无 user\_id 关联能力,则退化为 Cohort 层面的聚合统计(不需要用户级关联)

预期产出(下面三个数由 ③ 在同一夹具上实跑得出:3000 真实用户、seed=2024、真值 ad_lift=6pp; 原先写的 0.016 / 0.28 出自那份跑不通的旧代码模板,已按实测更正): - 朴素设备级 ATE:0.0216(真值 0.060 的 1/2.78,严重低估) - Stratified Aggregation 纠偏后 ATE:0.0548(离真值只差 0.0052) - 纠偏后 ROI 从 0.363 提升至 0.821,揭示 Instagram 渠道被严重低估 - 口径提醒:ROI 只涨 2.26 倍而 ATE 涨 2.54 倍,差额来自样本口径从 3371 条设

4. 输入数据要求

  • 字段:user_id(或邮箱哈希/手机号哈希)| device_id | cohort(地区+时段) | exposed | converted
  • 数据源:Instagram Ads API(曝光数据)+ Shopify 后台(订单数据,含 UTM 来源)
  • 如无 user\_id 关联能力,则退化为 Cohort 层面的聚合统计(不需要用户级关联)
  • 无需用户级设备匹配,退化为 Cohort 聚合版本
  • 按用户地理位置 × 访问时段 × 浏览器语言分 Cohort(≥ 8 个 Cohort,每个 ≥ 20 用户)

5. 输出结果

  • 各 Cohort 的真实广告提升(ATE)及 95% 置信区间
  • 全局加权 ATE,剔除碎片化偏差后的真实 ROAS

6. 业务价值与 ROI

未自动抽取;请查看原始 Skill 卡片。

7. 代码模板

代码块数量:1

Python290 行 · 完整显示
"""Identity Fragmentation Debiasing —— 跨设备身份碎片化的分层聚合纠偏。

自包含实现(numpy + pandas,**不需要 scipy**),对应 arXiv:2008.12849:
  1) simulate_cross_device_logs      生成"手机曝光 / 桌面下单"断链的设备级日志
  2) naive_roi_estimate              设备级朴素 ATE(把断链当成两个独立用户)
  3) StratifiedAggregationDebiaser   按 user_id 取 max 聚合回用户级,再做 Cohort-level ATE
  4) bias_decomposition_report       朴素 vs 纠偏 vs 真值三行对照

业务痛点:高活跃用户手机看广告、电脑下单,平台把它当成两个人 —— 一个"只曝光不转化",
一个"只转化没曝光",于是广告渠道被系统性低估,预算被错砍。
"""
from statistics import NormalDist

import numpy as np
import pandas as pd

Z95 = NormalDist().inv_cdf(0.975)          # 1.95996…,代替 scipy.stats.norm.ppf(0.975)
pd.set_option("display.width", 200)
pd.set_option("display.max_columns", None)


def simulate_cross_device_logs(n_true_users=2000, fragmentation_rate=0.40,
                               ad_treatment_prob=0.55, base_conversion_prob=0.08,
                               ad_lift=0.06, activity_gradient=0.025, seed=42,
                               n_cohorts=8):
    """真实因果链:广告曝光只改变购买概率;碎片化只影响"日志长什么样"。

    `fragmentation_rate` 的作用对象是**高活跃(activity ≥ 6)人群**——依据来自 ② 场景 1 的
    「高活跃用户在手机看到广告后,习惯切换到电脑上完成购买」;低活跃用户只有 0.03 的跨设备率。
    因此总体碎片化率会明显低于 0.40(③ 会把它打印出来并对账),这一点不能靠参数名望文生义。
    曝光本身与活跃度**独立**随机分配,所以用户级估计是无偏的。
    """
    rng = np.random.default_rng(seed)
    activity = np.where(rng.random(n_true_users) < 0.30,
                        rng.beta(8, 2, n_true_users) * 10,
                        rng.beta(2, 8, n_true_users) * 10)
    exposed = rng.random(n_true_users) < ad_treatment_prob
    p_buy = np.clip(base_conversion_prob + ad_lift * exposed
                    + activity_gradient * activity, 0.0, 1.0)
    converted = rng.random(n_true_users) < p_buy
    cohorts = rng.choice(["C%02d" % c for c in range(n_cohorts)], size=n_true_users)
    frag_prob = np.where(activity >= 6.0, fragmentation_rate, 0.03)
    fragmented = rng.random(n_true_users) < frag_prob

    rows = []
    for uid in range(n_true_users):
        if fragmented[uid]:
            # 手机端:记得到曝光,但下单发生在别的设备 → 这条记录永远 converted=0
            rows.append({"user_id": uid, "device_id": "mobile_%d" % uid,
                         "cohort": cohorts[uid], "exposed": int(exposed[uid]),
                         "converted": 0, "is_fragmented": True})
            # 桌面端:Cookie 断链,系统不知道它曾被广告触达 → exposed 被记成 0
            rows.append({"user_id": uid, "device_id": "desktop_%d" % uid,
                         "cohort": cohorts[uid], "exposed": 0,
                         "converted": int(converted[uid]), "is_fragmented": True})
        else:
            rows.append({"user_id": uid, "device_id": "single_%d" % uid,
                         "cohort": cohorts[uid], "exposed": int(exposed[uid]),
                         "converted": int(converted[uid]), "is_fragmented": False})
    return pd.DataFrame(rows)


def naive_roi_estimate(df, ad_spend=10000.0, revenue_per_conversion=50.0):
    """设备级朴素估计:一行设备记录当成一个人。"""
    exp_df = df[df["exposed"] == 1]
    ctl_df = df[df["exposed"] == 0]
    cvr_exp = float(exp_df["converted"].mean())
    cvr_ctl = float(ctl_df["converted"].mean())
    lift = cvr_exp - cvr_ctl
    incremental = lift * len(df)             # 注意:这里的分母是**设备记录数**
    return {"n_device_rows": int(len(df)),
            "cvr_exposed": round(cvr_exp, 4), "cvr_control": round(cvr_ctl, 4),
            "naive_lift": round(lift, 4),
            "incremental_conversions": round(incremental, 2),
            "naive_roi": round(incremental * revenue_per_conversion / ad_spend, 3)}


class StratifiedAggregationDebiaser:
    """分层聚合纠偏:先在 user_id 上取 max 还原真实状态,再按 Cohort 算 ATE 并加权汇总。"""

    def __init__(self, cohort_col="cohort", min_cohort_size=20):
        self.cohort_col = cohort_col
        self.min_cohort_size = min_cohort_size
        self.cohort_estimates_ = None
        self.global_ate_ = None
        self.kept_cohorts_ = 0
        self.dropped_cohorts_ = 0

    def collapse_to_user_level(self, df):
        """① 的公式:exposed~u = max_d exposed(u,d),converted~u = max_d converted(u,d)。"""
        return (df.groupby(["user_id", self.cohort_col], sort=True)
                .agg(exposed=("exposed", "max"), converted=("converted", "max"))
                .reset_index())

    def fit(self, df):
        user_df = self.collapse_to_user_level(df)
        rows = []
        self.kept_cohorts_ = 0
        self.dropped_cohorts_ = 0
        for cohort, grp in user_df.groupby(self.cohort_col):
            exp_g, ctl_g = grp[grp["exposed"] == 1], grp[grp["exposed"] == 0]
            # ① 关键假设 3:Cohort 用户数不足就不可估,只能显式跳过并留痕
            if len(grp) < self.min_cohort_size or len(exp_g) == 0 or len(ctl_g) == 0:
                self.dropped_cohorts_ += 1
                continue
            self.kept_cohorts_ += 1
            cvr_exp = float(exp_g["converted"].mean())
            cvr_ctl = float(ctl_g["converted"].mean())
            ate_k = cvr_exp - cvr_ctl
            se = float(np.sqrt(cvr_exp * (1 - cvr_exp) / len(exp_g)
                               + cvr_ctl * (1 - cvr_ctl) / len(ctl_g)))
            rows.append({"cohort": cohort, "n_users": len(grp), "n_exposed": len(exp_g),
                         "n_control": len(ctl_g), "cvr_exposed": round(cvr_exp, 4),
                         "cvr_control": round(cvr_ctl, 4), "ate": round(ate_k, 4),
                         "se_ate": round(se, 4),
                         "ci_lower": round(ate_k - Z95 * se, 4),
                         "ci_upper": round(ate_k + Z95 * se, 4)})
        self.cohort_estimates_ = pd.DataFrame(rows)
        if rows:
            w = self.cohort_estimates_["n_users"] / self.cohort_estimates_["n_users"].sum()
            self.global_ate_ = float((w * self.cohort_estimates_["ate"]).sum())
            self.weights_ = w
            self.global_cvr_exposed_ = float((w * self.cohort_estimates_["cvr_exposed"]).sum())
            self.global_cvr_control_ = float((w * self.cohort_estimates_["cvr_control"]).sum())
        else:
            # ① 前提被破坏时必须**拒绝出数**,而不是静默返回 0(静默 0 会被读成"广告无效")
            self.global_ate_ = None
            self.weights_ = None
        return self

    def corrected_roi(self, ad_spend=10000.0, revenue_per_conversion=50.0):
        if self.cohort_estimates_ is None:
            raise RuntimeError("请先调用 fit()")
        if self.global_ate_ is None:
            raise RuntimeError("没有满足 min_cohort_size=%d 的 Cohort,拒绝给出 ATE"
                               % self.min_cohort_size)
        total_n = int(self.cohort_estimates_["n_users"].sum())
        incremental = self.global_ate_ * total_n
        return {"n_users": total_n,
                "cohorts_kept": self.kept_cohorts_, "cohorts_dropped": self.dropped_cohorts_,
                "corrected_cvr_exposed": round(self.global_cvr_exposed_, 4),
                "corrected_cvr_control": round(self.global_cvr_control_, 4),
                "corrected_ate": round(self.global_ate_, 4),
                "incremental_conversions": round(incremental, 2),
                "corrected_roi": round(incremental * revenue_per_conversion / ad_spend, 3)}

    def cohort_report(self):
        if self.cohort_estimates_ is None:
            raise RuntimeError("请先调用 fit()")
        return self.cohort_estimates_.sort_values("ate", ascending=False,
                                                  kind="mergesort").reset_index(drop=True)


def bias_decomposition_report(naive, corrected, true_lift):
    """三行对照表:把"低估了多少"和"低估来自哪一轨"摊开。"""
    return pd.DataFrame([
        {"估计方法": "朴素设备级(有偏)", "ATE": naive["naive_lift"], "ROI": naive["naive_roi"],
         "样本口径": "%d 条设备记录" % naive["n_device_rows"],
         "偏差 vs 真值": round(naive["naive_lift"] - true_lift, 4),
         "偏差方向": "高估" if naive["naive_lift"] > true_lift else "低估"},
        {"估计方法": "Stratified Aggregation 纠偏", "ATE": corrected["corrected_ate"],
         "ROI": corrected["corrected_roi"],
         "样本口径": "%d 个真实用户" % corrected["n_users"],
         "偏差 vs 真值": round(corrected["corrected_ate"] - true_lift, 4),
         "偏差方向": "高估" if corrected["corrected_ate"] > true_lift else "低估"},
        {"估计方法": "真实值(数据生成器给的 ad_lift)", "ATE": true_lift, "ROI": "—",
         "样本口径": "—", "偏差 vs 真值": 0.0, "偏差方向": "基准"}])


# ── 1. 夹具:3000 个真实用户,40% 高活跃用户跨设备碎片化,真实 ad_lift=6pp ──
TRUE_LIFT = 0.06
df = simulate_cross_device_logs(n_true_users=3000, fragmentation_rate=0.40,
                                ad_lift=TRUE_LIFT, seed=2024)
n_users = int(df["user_id"].nunique())
n_frag_users = int(df.loc[df["is_fragmented"], "user_id"].nunique())
print("设备记录 %d 行 / 真实用户 %d 人 / 被拆成两半的用户 %d 人(%.1f%%)"
      % (len(df), n_users, n_frag_users, 100.0 * n_frag_users / n_users))

# ── 2. 朴素估计(设备级) ──
naive = naive_roi_estimate(df, ad_spend=10000.0)
print("朴素 ATE %.4f  CVR曝光 %.4f  CVR对照 %.4f  朴素 ROI %.3f"
      % (naive["naive_lift"], naive["cvr_exposed"], naive["cvr_control"], naive["naive_roi"]))

# ── 3. 分层聚合纠偏 ──
debiaser = StratifiedAggregationDebiaser(cohort_col="cohort", min_cohort_size=20)
debiaser.fit(df)
corrected = debiaser.corrected_roi(ad_spend=10000.0, revenue_per_conversion=50.0)
print("纠偏 ATE %.4f  纠偏 ROI %.3f(保留 Cohort %d 个)"
      % (corrected["corrected_ate"], corrected["corrected_roi"], corrected["cohorts_kept"]))

# ── 4. Cohort 明细 + 对照 ──
cohort_df = debiaser.cohort_report()
print("\nCohort 级估计")
print(cohort_df)
print("\n偏差分解")
print(bias_decomposition_report(naive, corrected, TRUE_LIFT))

# ── 5. 同一份数据,用"只有单设备用户"的干净子集作对照 ──
naive_clean = naive_roi_estimate(df[~df["is_fragmented"]], ad_spend=10000.0)
print("\n对照:只取未碎片化的单设备用户,朴素 ATE = %.4f" % naive_clean["naive_lift"])

print("\n【断言】")
# A1 碎片化确实是"同一人被记成两行",且两行呈对立形态
frag = df[df["is_fragmented"]]
mob = frag[frag["device_id"].str.startswith("mobile")]
des = frag[frag["device_id"].str.startswith("desktop")]
assert len(mob) == len(des) == n_frag_users, "碎片化用户必须正好两条记录"
assert int(mob["converted"].sum()) == 0, "手机端碎片记录一律记为未转化"
assert int(des["exposed"].sum()) == 0, "桌面端碎片记录一律记为未曝光"
assert int(mob["exposed"].sum()) > 0 and int(des["converted"].sum()) > 0, "断链两头都有货"
print("  A1 断链形态:%d 人 × 2 行(总体 %.1f%%,不是名义的 40%%),手机行转化 %d、桌面行曝光 %d"
      % (n_frag_users, 100.0 * n_frag_users / n_users,
         int(mob["converted"].sum()), int(des["exposed"].sum())))
assert n_frag_users / n_users < 0.40, "参数 0.40 只作用于高活跃人群,总体率必须低于它"

# A2 朴素估计确实低估,而且低估倍数可量化
assert naive["naive_lift"] < TRUE_LIFT * 0.6, \
    "朴素 ATE %.4f 未显著低估真值 %.3f" % (naive["naive_lift"], TRUE_LIFT)
underestimate_x = TRUE_LIFT / naive["naive_lift"]
print("  A2 朴素 ATE %.4f,低估 **%.2f 倍**" % (naive["naive_lift"], underestimate_x))

# A3 用户级 max 聚合把"曝光过且买过"的人重新还原出来 —— 设备级永远数不到这类人
user_df = debiaser.collapse_to_user_level(df)
assert len(user_df) == n_users, "聚合后应正好回到 %d 个用户,实际 %d" % (n_users, len(user_df))
assert len(df[(df["exposed"] == 1) & (df["converted"] == 1)]) \
    < len(user_df[(user_df["exposed"] == 1) & (user_df["converted"] == 1)]), \
    "聚合后既曝光又转化的人数必须严格增加,否则纠偏没有还原任何东西"
back = int(user_df[(user_df["exposed"] == 1) & (user_df["converted"] == 1)]
           .merge(df[(df["is_fragmented"]) & (df["device_id"].str.startswith("desktop"))]
                  [["user_id"]], on="user_id").shape[0])
assert back > 0, "还原的转化里必须包含碎片化用户"
print("  A3 设备级「曝光∧转化」%d 行 → 用户级 %d 人,其中 %d 人是被断链的碎片化用户"
      % (len(df[(df['exposed'] == 1) & (df['converted'] == 1)]),
         len(user_df[(user_df['exposed'] == 1) & (user_df['converted'] == 1)]), back))

# A4 纠偏后 ATE 回到真值附近,且 8 个 Cohort 全保留、加权口径可复算
assert abs(corrected["corrected_ate"] - TRUE_LIFT) < 0.02, \
    "纠偏 ATE %.4f 偏离真值 %.3f 超过 0.02" % (corrected["corrected_ate"], TRUE_LIFT)
assert corrected["cohorts_kept"] == 8 and corrected["cohorts_dropped"] == 0
assert abs(corrected["corrected_ate"] - TRUE_LIFT) < abs(naive["naive_lift"] - TRUE_LIFT), \
    "纠偏后反而更远,方法不成立"
recomputed = float((cohort_df["n_users"] / cohort_df["n_users"].sum()
                    * cohort_df["ate"]).sum())
assert abs(recomputed - corrected["corrected_ate"]) < 5e-4, \
    "① 的加权平均式复算 %.4f vs 实现 %.4f" % (recomputed, corrected["corrected_ate"])
print("  A4 纠偏 ATE %.4f(真值 %.3f,误差 %.4f),加权式复算 %.4f 一致"
      % (corrected["corrected_ate"], TRUE_LIFT,
         abs(corrected["corrected_ate"] - TRUE_LIFT), recomputed))

# A5 归因给"碎片化"而不是"方法本身":同一套朴素算法只去掉断链,误差就消失
assert abs(naive_clean["naive_lift"] - TRUE_LIFT) < 0.025, \
    "单设备干净子集上朴素估计应接近真值,实测 %.4f" % naive_clean["naive_lift"]
print("  A5 只用未碎片化用户时,朴素 ATE %.4f 已经贴近真值 %.3f —— 偏差确实来自断链"
      % (naive_clean["naive_lift"], TRUE_LIFT))

# A6 ROI 口径差异必须摊开:朴素按**设备记录数**放大增量、纠偏按**用户数**,
#    所以 ROI 的提升倍数 = ATE 倍数 ÷ (记录数/用户数),口径切换会吃掉一部分表观收益
row_ratio = naive["n_device_rows"] / corrected["n_users"]
lift_ratio = corrected["corrected_ate"] / naive["naive_lift"]
roi_ratio = corrected["corrected_roi"] / naive["naive_roi"]
assert abs(roi_ratio - lift_ratio / row_ratio) < 0.05, \
    "ROI 倍数 %.3f 应约等于 ATE 倍数 %.3f ÷ 记录/用户比 %.3f" % (
        roi_ratio, lift_ratio, row_ratio)
assert abs(naive["cvr_exposed"] - naive_clean["cvr_exposed"]) > 0.01, \
    "碎片化的主要杀伤在曝光组转化率被稀释"
print("  A6 ROI 从 %.3f 到 %.3f(%.2f 倍)= ATE %.2f 倍 ÷ 记录/用户 %.2f 倍"
      % (naive["naive_roi"], corrected["corrected_roi"], roi_ratio, lift_ratio, row_ratio))

# A7 Cohort 门槛(① 关键假设 3):门槛高到无人满足时必须拒判,而不是静默给 0
tight = StratifiedAggregationDebiaser(min_cohort_size=10 ** 6).fit(df)
try:
    tight.corrected_roi()
    raise AssertionError("门槛不满足时却给出了 ROI")
except RuntimeError as exc:
    assert "拒绝给出 ATE" in str(exc), str(exc)
assert tight.kept_cohorts_ == 0 and tight.global_ate_ is None
print("  A7 min_cohort_size 过大时 %s" % "RuntimeError(拒绝出数)")

# A8 未 fit 就取数、每个 Cohort 的 CI 必须包住自己的点估计
try:
    StratifiedAggregationDebiaser().cohort_report()
    raise AssertionError("未 fit 却返回了 Cohort 报告")
except RuntimeError:
    pass
assert bool(((cohort_df["ci_lower"] <= cohort_df["ate"])
             & (cohort_df["ate"] <= cohort_df["ci_upper"])).all())
assert bool((cohort_df["n_exposed"] > 0).all() and (cohort_df["n_control"] > 0).all())
print("  A8 每个 Cohort 的 ate 都落在自身 95%% CI 内,CI 宽度中位数 %.4f"
      % float((cohort_df["ci_upper"] - cohort_df["ci_lower"]).median()))
print("[✓] Identity Fragmentation Debiasing 测试通过")

8. 论文来源

论文链接用于核验方法来源,不自动证明本页商业结果。