O1Easy★ BA/DA 转 DS/MLE · 必练桥梁Part O · BA→Python 数据科学化与统计算子

向量化 Cohort 累计 ARPU 三角阵(SQL GroupBy → NumPy)

⚡闪卡盲测➔

不用 Python 双重循环,用 np.bincount 与 np.add.at + np.cumsum 在毫秒级构建百万级留存 LTV / Cumulative ARPU 矩阵。

⏱️ 时间复杂度: O(U + E + C*W)
💾 空间复杂度: O(C*W)
🎯 免登录实战自测闭环(先做再看答案)
按「机制回忆 → 关键行填空 → 边界反例 → 追问与错题记录」顺序自测,进度自动保存在本地。
Step 1 · 机制口述与数值稳定性自检
Step 2 · 核心代码关键行补全
import numpy as np
def compute_cohort_arpu_matrix(signup_cohorts: np.ndarray, event_offsets: np.ndarray, revenues: np.ndarray, num_cohorts: int, max_window: int) -> np.ndarray:
# signup_cohorts: (N_users,), event_offsets & revenues: (N_events,) paired with user_ids via event_user_idx
raise NotImplementedError('Use explicit signature below')
def cohort_arpu_matrix(user_cohort: np.ndarray, event_user_idx: np.ndarray, event_offset: np.ndarray, event_rev: np.ndarray, num_cohorts: int, max_offset: int) -> np.ndarray:
cohort_sizes =
valid = (event_offset >= 0) & (event_offset <= max_offset)
ev_c = user_cohort[event_user_idx[valid]]
ev_t = event_offset[valid]
ev_r = event_rev[valid]
rev_mat = np.zeros((num_cohorts, max_offset + 1), dtype=np.float64)
np.add.at(rev_mat, (ev_c, ev_t), ev_r)
denom = np.where(cohort_sizes > 0, cohort_sizes, 1.0)[:, None]
arpu = np.where(cohort_sizes[:, None] > 0, rev_mat / denom, 0.0)
return
Step 3 · 反例与边界断言核对
Step 4 · 面试追问盲答与错题记录
Q1: 为什么 rev_mat[ev_c, ev_t] += ev_r 在有重复下标时会算错?
Q2: 如果 Cohort 尚未经过完整 W 天(Right Censoring)怎么处理展示?
下一题: 辛普森悖论检测与 Kitagawa 漏斗拆因(Rate vs Mix Effect) →
💡

实战一句话记忆口诀

bincount 定分母,add.at 散列累加,cumsum 出 LTV

📐 核心数学公式与机理推导

$$\text{ARPU}_{c,t} = \frac{\sum_{u \in c} R_{u,t}}{|\{u \in c : \text{active}_{u,0}\}|},\quad t \in [0, W]$$
在 SQL 中构建 Cohort 累计 ARPU 需要多表 Self-Join + SUM() OVER (PARTITION BY cohort ORDER BY day);迁移到 NumPy 向量化时,先用 bincount 计算每个 Cohort 初始分母 ∣C∣|C|,再用 np.add.at 完成离散 (cohort, offset) 稀疏累加,最后沿时间轴 cumsum 得到单调递增的累计 LTV 曲线。

🔄 张量维度与形状流转说明

user_cohort: (U,) + event_rev: (E,) -> rev_mat: (C, W+1) -> cum_arpu: (C, W+1)

🛡️ 数值稳定性自检与边界要点

  • 必须使用注册初始分母 cohort_sizes 做除法,切忌用当期活跃人数代替导致幸存者偏差
  • 用 np.add.at 而非直接 rev_mat[c, t] += r,否则同一索引重复写入会丢失增量
  • 过滤掉 event_offset < 0(脏数据时间戳回拨)或超过窗口期的异常事件

💻 完整参考代码实现

import numpy as np

def compute_cohort_arpu_matrix(signup_cohorts: np.ndarray, event_offsets: np.ndarray, revenues: np.ndarray, num_cohorts: int, max_window: int) -> np.ndarray:
    # signup_cohorts: (N_users,), event_offsets & revenues: (N_events,) paired with user_ids via event_user_idx
    raise NotImplementedError('Use explicit signature below')

def cohort_arpu_matrix(user_cohort: np.ndarray, event_user_idx: np.ndarray, event_offset: np.ndarray, event_rev: np.ndarray, num_cohorts: int, max_offset: int) -> np.ndarray:
    cohort_sizes = np.bincount(user_cohort, minlength=num_cohorts).astype(np.float64)
    valid = (event_offset >= 0) & (event_offset <= max_offset)
    ev_c = user_cohort[event_user_idx[valid]]
    ev_t = event_offset[valid]
    ev_r = event_rev[valid]
    rev_mat = np.zeros((num_cohorts, max_offset + 1), dtype=np.float64)
    np.add.at(rev_mat, (ev_c, ev_t), ev_r)
    denom = np.where(cohort_sizes > 0, cohort_sizes, 1.0)[:, None]
    arpu = np.where(cohort_sizes[:, None] > 0, rev_mat / denom, 0.0)
    return np.cumsum(arpu, axis=1)

🧪 本地测试与正确性断言

可直接复制到本地 Python / Jupyter 验证:

uc = np.array([0, 0, 1, 1])
eu = np.array([0, 1, 0, 2, 3])
eo = np.array([0, 1, 2, 0, 1])
er = np.array([10.0, 20.0, 10.0, 4.0, 6.0])
out = cohort_arpu_matrix(uc, eu, eo, er, 2, 2)
assert np.allclose(out[0], [5.0, 15.0, 20.0]), f'Unexpected cohort 0: {out[0]}'
assert np.allclose(out[1], [2.0, 5.0, 5.0]), f'Unexpected cohort 1: {out[1]}'
print('O1 PASS')

🎯 核心工程追问与标准应答

Q1:为什么 rev_mat[ev_c, ev_t] += ev_r 在有重复下标时会算错?
NumPy 普通花式索引先读取旧值切片再一次性写回,重复坐标只保留最后一次加法;np.add.at 执行无缓冲原地累加(unbuffered in-place scatter add)。
Q2:如果 Cohort 尚未经过完整 W 天(Right Censoring)怎么处理展示?
在推理/图表层需记录每个 Cohort 的最大观测天数 max_obs_day[c],将 offset > max_obs_day[c] 的格点置为 NaN 而非 0,避免新队列拉低均值曲线。
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!
🎯 立即在闪卡中盲测此题➔
← 上一题: 分布式通信 Ring-AllReduce 两阶段带宽最优仿真返回 Part O 与全部 105 题下一题: 辛普森悖论检测与 Kitagawa 漏斗拆因(Rate vs Mix Effect) →