60. 使用双比例 z 检验判断新 prompt 是否真的转化率更高
你向部分用户推送 prompt A,向另一部分用户推送 prompt B,并统计转化人数。B 看起来效果更好,但这只是噪声吗?双比例 z 检验可以回答这个问题。
编写 ab_test(conv_a, n_a, conv_b, n_b) 并返回 (z, p_value):
- pooled p = (conv_a + conv_b) / (n_a + n_b)
- se = sqrt(p (1 - p) (1 / n_a + 1 / n_b))
- z = (rate_b - rate_a) / se
- p_value 是双侧的:2 (1 - Phi(|z|)),其中 Phi 是标准正态分布的 CDF。
使用 math.erf 来计算 Phi: Phi(x) = 0.5 (1 + erf(x / sqrt(2)))。
def ab_test(conv_a, n_a, conv_b, n_b)示例 1
输入: conv_a = 100, n_a = 1000, conv_b = 150, n_b = 1000
输出: (3.380617, 0.000723)
示例 2
输入: conv_a = 50, n_a = 500, conv_b = 55, n_b = 500
输出: (0.515779, 0.606009)
示例 3
输入: conv_a = 80, n_a = 400, conv_b = 60, n_b = 400
输出: (-1.860968, 0.062749)
约束条件
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
Under the null hypothesis both prompts share one true rate, so the standard error uses the pooled rate, not the two separate rates.
提示 2
Compute each conversion rate, the pooled rate, the standard error from the formula, then z as the rate difference over the standard error, and finally the two-sided p-value.
提示 3
Order matters: z is rate_b - rate_a, keeping its sign, but the p-value uses abs(z) inside 0.5 * (1 + math.erf(x / math.sqrt(2))) and then 2 * (1 - phi).
常见错误
- 双侧意味着将尾部概率翻倍;有 bug 的版本返回的是单侧 p-value。
理解思路
双比例 z 检验用于询问两个转化率之间的差异是否大于随机噪声通常会产生的差异。首先假设 A 和 B 是相同的,并将它们合并(pool)来估计一个共同的转化率。然后以 standard error 为单位测量转化率之间的差距。
A 组在 1000 人中转化了 50 人 (5%),B 组在 1000 人中转化了 70 人 (7%)。Pooled p = 120 / 2000 = 0.06。se = sqrt(0.06 x 0.94 x (1/1000 + 1/1000)) = sqrt(0.0001128) = 0.01062。z = (0.07 - 0.05) / 0.01062 = 1.883。双侧 p-value = 2 x (1 - Phi(1.883)) = 0.0597,因此在 0.05 水平下不显著。
p = total conversions / total users; se = sqrt(p(1 - p)(1/n_a + 1/n_b)); z = (rate_b - rate_a) / se; p_value = 2(1 - Phi(|z|)),其中 Phi(x) = 0.5(1 + erf(x / sqrt 2))。产品团队使用此方法来评估 prompt 或 UI 实验。