P paper2skillsPlaybook
开始业务诊断
访客模式
05-推荐系统

因果图聚合权重去偏推荐 - CAGED

Skill-CAGED-Debiased-Rec

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

Momcozy 吸奶器爆款 SKU 占全部流量的 60%+,200 余款配件(替换配件、特殊尺码)几乎零曝光

来源
paper2skills-vault/05-推荐系统/Skill-CAGED-Debiased-Rec.md
适用边界
论文方法到业务问题的项目侧映射,不自动证明客户根因。
声明类型示例验证状态待企业数据验证

500 万元

来源
paper2skills-vault/05-推荐系统/Skill-CAGED-Debiased-Rec.md#business-value
适用边界
方法估算或场景示例,不等于客户结果或收益承诺。

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

业务视角
适用角色运营负责人 / 选品负责人 · 产品经理 · 广告优化师
适用平台Amazon · DTC 独立站 · 邮件/SMS 个性化
什么情况下用老客来了只买一件就走,相关产品没被推出去;Bundle 商品连带销售做不起来;站内推荐位点击率低
示例目标(需企业数据验证)老客连带购买率提升 20-35%,客单价提升,品类交叉销售做起来
业务痛点
老客复购率上不去相关产品没有被看到Bundle 凑单没人用新品没有曝光机会

1. 解决的问题

Momcozy 吸奶器爆款 SKU 占全部流量的 60%+,200 余款配件(替换配件、特殊尺码)几乎零曝光

2. 核心算法逻辑

核心思想

GNN 推荐系统(如 LightGCN)在图上做邻居聚合时,边权重天然由度数平方根决定。热门商品度数高,信息在传播时被反复放大,形成"回声室效应"——推荐系统拼命推爆款,长尾优质商品彻底失声。

CAGED 的洞察是:这个度数归一化权重,本质上就是观测数据的交互似然分布,带着流行度偏差的"指纹"。解法不是修改损失函数或丢弃边,而是直接把图聚合权重本身视为一个因果推断问题——用后门调整去除流行度这个混淆变量,估计出无偏的真实偏好权重,再代回 LightGCN 做传播。

数学直觉

标准 LightGCN 聚合权重(带偏):

w_{ui}^{\text{biased}} = \frac{1}{\sqrt{d_u} \cdot \sqrt{d_i}}

其中 $d_u, d_i$ 是节点度数,热门商品 $d_i$ 大 → 权重被压低但聚合频次高,长尾商品被系统性压制。

CAGED 目标(无偏权重):

w_{ui}^{*} = \underbrace{\mathbb{E}_{p(z)}[\hat{r}_{ui}]}_{\text{干预后期望}} \cdot \underbrace{\frac{1}{1 + \text{pop}_i}}_{\text{流行度校正}}

通过最大化 ELBO 优化 Encoder-Decoder:

\mathcal{L}_{\text{ELBO}} = \mathbb{E}_{q(z|r)}[\log p(r|z)] - \text{KL}[q(z|r) \| p(z)]
  • Encoder $q(z|r)$:从交互矩阵推断潜在"真实偏好强度" $z$
  • Decoder $p(r|z)$:从 $z$ 重建交互,输出校正后的偏好概率

动量平滑(训练稳定性):

w_t^{\text{unbiased}} = \alpha^{t/T} \cdot w^{\text{biased}} + (1 - \alpha^{t/T}) \cdot w^{\text{causal}}

早期 $\alpha$ 接近 1 保留有偏权重,随训练推进逐步注入无偏权重,避免训练早期的分布突变。

关键假设

  1. 流行度是主要混淆变量:商品被曝光/交互的概率主要由流行度驱动,而非用户真实偏好
  2. 后门可调整:流行度对推荐结果的因果路径可以通过条件化被阻断
  3. Plug-and-play:算法不绑定特定的推荐骨干,任何使用图聚合的 GNN 均可注入无偏权重

关键效果(论文实验)

数据集整体 NDCG长尾商品召回
Amazon-Beauty与 SOTA 持平显著提升
Yelp-2018与 SOTA 持平显著提升
MIND(新闻推荐)与 SOTA 持平显著提升

核心结论:整体指标不降的前提下,长尾商品召回大幅提升。

3. 业务应用场景

业务问题: Momcozy 吸奶器爆款 SKU 占全部流量的 60%+,200 余款配件(替换配件、特殊尺码)几乎零曝光。新品在首页推荐中竞争不过历史交互量高的爆款,导致配件库存积压,复购品类单一。

数据要求: - 用户行为日志(session_id, user_id, item_id, event_type: view/add_cart/purchase, timestamp) - 商品属性表(item_id, category, price, stock, launch_date) - 最近 6 个月数据,至少 5 万用户 × 1000 SKU

预期产出: - 无偏因果偏好权重矩阵(user × item) - 去偏后的 Top-20 推荐列表,长尾商品(月销 < 50 件)占比提升至 40%+ - 每周更新一次权重,对接现有推荐服务

4. 输入数据要求

  • 用户行为日志(session_id, user_id, item_id, event_type: view/add_cart/purchase, timestamp)
  • 商品属性表(item_id, category, price, stock, launch_date)
  • 最近 6 个月数据,至少 5 万用户 × 1000 SKU
  • 全平台用户-商品交互图(含爆款和长尾商品)
  • 新品特征向量(商品描述 embedding、价格区间、品类标签)

5. 输出结果

  • 无偏因果偏好权重矩阵(user × item)
  • 去偏后的 Top-20 推荐列表,长尾商品(月销 < 50 件)占比提升至 40%+
  • 每周更新一次权重,对接现有推荐服务
  • 新品上架第 1 周即可被 CAGED 的无偏权重加入图传播
  • 为新品估计"如果没有流行度偏压,应该有多高的偏好概率"

6. 业务价值与 ROI

  • 实施成本:算法工程师 2 周集成(CAGED 模块 Plug-in 到现有 LightGCN 服务),训练额外耗时 +20%(ELBO 优化)
  • 预期收益:长尾商品 GMV 提升 10-25%,以中型跨境品牌月 GMV 500 万元计 → 年增 GMV 600-1500 万元
  • 隐性价值:降低爆款断货风险(库存分散)、提升平台生态健康度(卖家多样性增加)
  • 算法本身为 Plug-and-play,不重构推荐服务架构
  • 纯 numpy 可运行,无需 GPU(小数据集);大规模需 PyTorch 版本
  • 流行度偏差是跨境电商推荐系统的普遍性根本问题,不是边缘 case

7. 代码模板

代码块数量:2

Python211 行 · 完整显示
"""
CAGED 去偏推荐 · 自洽示例(只用 numpy,不依赖任何项目内模块)

对应卡片 ① 的三个动作:
  1) 有偏聚合权重 w_biased = 1/sqrt(d_u * d_i)(标准 LightGCN 度数归一化)——
     热门商品度数大、共现多,在图传播里被反复放大,形成「回声室」;
  2) 后门调整 w_causal = w_biased * 1/(1 + s * pop_i)——把流行度这个混淆变量从
     聚合权重里除掉,估计无偏的真实偏好权重;
  3) 动量注入 w_t = alpha^(t/T) * w_biased + (1 - alpha^(t/T)) * w_causal。
本示例把三步真算一遍,并用「长尾覆盖率 + 真实偏好命中」两个指标复现 ① 的结论:
整体指标不降的前提下,长尾商品召回显著提升。
"""
import numpy as np


def sigmoid(x):
    return 1.0 / (1.0 + np.exp(-np.clip(x, -30.0, 30.0)))


def long_tail_coverage(item_ids, item_popularity, tail_threshold=0.1):
    """长尾定义:归一化流行度 < tail_threshold 的商品在推荐结果中的占比。"""
    pop = np.asarray(item_popularity, dtype=float)
    norm = pop / pop.max() if pop.max() > 0 else pop
    ids = [int(i) for i in item_ids]
    if not ids:
        return 0.0
    return float(sum(1 for i in ids if norm[i] < tail_threshold)) / len(ids)


def _row_norm(w):
    return w / np.maximum(w.sum(axis=1, keepdims=True), 1e-12)


class CAGEDWeightEstimator:
    """把「图聚合权重」当因果推断问题:对观测边做流行度后门调整。"""

    def __init__(self, num_users, num_items, pop_strength=3.0):
        self.num_users, self.num_items = num_users, num_items
        self.pop_strength = pop_strength
        self.adj = np.zeros((num_users, num_items))
        self.user_degree = np.ones(num_users)
        self.item_degree = np.ones(num_items)
        self.item_popularity = np.zeros(num_items)
        self.pop_norm = np.zeros(num_items)

    def build_graph(self, interactions):
        for u, i in interactions:
            self.adj[u, i] = 1.0
        self.item_popularity = self.adj.sum(axis=0)
        self.user_degree = np.maximum(self.adj.sum(axis=1), 1.0)
        self.item_degree = np.maximum(self.item_popularity, 1.0)
        self.pop_norm = self.item_popularity / max(self.item_popularity.max(), 1.0)
        return self

    def biased_weights(self):
        """w_biased = A / sqrt(d_u * d_i),行内归一化 —— LightGCN 带偏基线。"""
        return _row_norm(self.adj / np.sqrt(np.outer(self.user_degree, self.item_degree)))

    def causal_weights(self):
        """后门调整:每条观测边再除以流行度校正项 1/(1 + s * pop_i)。"""
        corr = 1.0 / (1.0 + self.pop_strength * self.pop_norm)
        return _row_norm(self.biased_weights() * corr[None, :])


class CAGEDRecommendationPipeline:
    def __init__(self, num_users, num_items, embed_dim=16, latent_dim=16,
                 n_layers=2, momentum=0.9, pop_strength=3.0, item_embeddings=None, seed=0):
        self.num_users, self.num_items = num_users, num_items
        self.n_layers, self.momentum = n_layers, momentum
        self.embed_dim, self.latent_dim = embed_dim, latent_dim
        self.caged = CAGEDWeightEstimator(num_users, num_items, pop_strength=pop_strength)
        rng = np.random.default_rng(seed)
        if item_embeddings is None:                     # 生产里应传商品描述 embedding
            item_embeddings = rng.normal(size=(num_items, latent_dim)) / np.sqrt(latent_dim)
        self.item_embeddings = np.asarray(item_embeddings, dtype=float)
        self.history = []
        self.final_alpha = 1.0

    def build_graph(self, interactions):
        self.caged.build_graph(interactions)
        return self

    def train(self, interactions, epochs=50):
        """训练即动量路径 alpha^(t/T):记录有偏→无偏的注入进度(① 的第三式)。"""
        if self.caged.item_popularity.sum() == 0:
            self.build_graph(interactions)
        self.history = [self.momentum ** (t / float(epochs)) for t in range(1, epochs + 1)]
        self.final_alpha = self.history[-1]
        return self.history

    def weight_matrix(self, mode="unbiased"):
        biased = self.caged.biased_weights()
        if mode == "biased" or not self.history:
            return biased
        if mode == "causal":
            return self.caged.causal_weights()
        a = self.final_alpha                            # 收敛前:按动量混合
        return _row_norm(a * biased + (1.0 - a) * self.caged.causal_weights())

    def score_all(self, user_id, mode="unbiased"):
        """n 层传播 + 各层平均(LightGCN 口径),返回该用户对全部物品的打分。"""
        W = self.weight_matrix(mode)
        E = self.item_embeddings
        embs, users = [E], []
        for _ in range(max(self.n_layers, 1)):
            U = W @ E
            E = W.T @ U
            embs.append(E)
            users.append(U)
        item_final = np.mean(embs, axis=0)
        user_final = np.mean(users, axis=0) if users else W @ item_final
        return item_final @ user_final[user_id]

    def get_recommendations(self, user_id, top_k=20, exclude_items=(), use_unbiased=True,
                            mode=None):
        if mode is None:
            mode = "unbiased" if use_unbiased else "biased"
        scores = self.score_all(user_id, mode)
        excl = {int(x) for x in exclude_items}
        ranked = [int(i) for i in np.argsort(-scores) if int(i) not in excl]
        return [(i, float(scores[i])) for i in ranked[:top_k]]

    def compare_biased_vs_unbiased(self, user_id, top_k=20, exclude_items=()):
        return {
            "biased": self.get_recommendations(user_id, top_k, exclude_items, mode="biased"),
            "unbiased": self.get_recommendations(user_id, top_k, exclude_items, mode="unbiased"),
            "causal": self.get_recommendations(user_id, top_k, exclude_items, mode="causal"),
        }


def evaluate(pipeline, user_ids, pref, pairs, top_k=20, mode="unbiased"):
    """对一组用户取平均:① 的结论是群体口径,不是单用户口径。"""
    pop = pipeline.caged.item_popularity
    tails, hits = [], []
    for uid in user_ids:
        already = {i for (u, i) in pairs if u == uid}
        ranked = [i for i, _ in pipeline.get_recommendations(
            uid, top_k=top_k, exclude_items=already, mode=mode)]
        ideal = [int(i) for i in np.argsort(-pref[uid]) if int(i) not in already][:top_k]
        tails.append(long_tail_coverage(ranked, pop, tail_threshold=0.1))
        hits.append(len(set(ideal) & set(ranked)) / float(top_k))
    return float(np.mean(tails)), float(np.mean(hits))


def make_synthetic_interactions(n_users, n_items, latent_dim=12, pop_bias=2.4,
                                per_user=14, seed=7):
    """夹具:观测 = 真实偏好 + 流行度偏置(流行度正是被调整掉的混淆变量)。"""
    rng = np.random.default_rng(seed)
    item_true = rng.normal(size=(n_items, latent_dim)) / np.sqrt(latent_dim)
    user_true = rng.normal(size=(n_users, latent_dim)) / np.sqrt(latent_dim)
    pref = user_true @ item_true.T
    raw_pop = np.sort(rng.pareto(1.1, n_items))[::-1]
    pop_signal = np.log1p(raw_pop) / np.log1p(raw_pop).max()
    exposure = pref + pop_bias * pop_signal[None, :]
    pairs = []
    for u in range(n_users):
        idx = np.argsort(-exposure[u])[:per_user]
        keep = rng.random(len(idx)) < np.clip(sigmoid(exposure[u][idx]), 0.1, 0.95)
        pairs += [(u, int(i)) for i, kp in zip(idx, keep) if kp]
    return pairs, pref, item_true


def run_demo():
    # 演示规模夹具(② 的生产口径是 5 万用户 x 1000 SKU,此处缩小以保证可复现)
    n_users, n_items = 400, 150
    pairs, pref, item_true = make_synthetic_interactions(n_users, n_items, seed=7)
    pipeline = CAGEDRecommendationPipeline(
        num_users=n_users, num_items=n_items, embed_dim=item_true.shape[1],
        latent_dim=item_true.shape[1], n_layers=2, momentum=0.9, pop_strength=3.0,
        item_embeddings=item_true, seed=11)
    pipeline.build_graph(pairs)
    history = pipeline.train(pairs, epochs=50)
    assert len(history) == 50 and history[-1] < history[0], "动量系数应随训练单调衰减"

    cohort = list(range(0, n_users, 20))          # 20 个用户的群体口径
    pop = pipeline.caged.item_popularity
    b_tail, b_hit = evaluate(pipeline, cohort, pref, pairs, mode="biased")
    m_tail, m_hit = evaluate(pipeline, cohort, pref, pairs, mode="unbiased")   # 动量混合
    c_tail, c_hit = evaluate(pipeline, cohort, pref, pairs, mode="causal")     # 完全注入

    # 单用户示例:② 的「Top-20 推荐列表」口径
    user_id = int(np.argmax(pipeline.caged.user_degree))
    already = [i for (u, i) in pairs if u == user_id]
    result = pipeline.compare_biased_vs_unbiased(user_id=user_id, top_k=20,
                                                 exclude_items=already)
    b_rank = [i for i, _ in result["biased"]]
    c_rank = [i for i, _ in result["causal"]]
    tail_single = long_tail_coverage(c_rank, pop, tail_threshold=0.1)
    tail_single_biased = long_tail_coverage(b_rank, pop, tail_threshold=0.1)

    print("动量 alpha: 首 epoch %.3f -> 末 epoch %.3f(末轮保留 %.0f%% 有偏权重)"
          % (history[0], history[-1], 100 * history[-1]))
    print("群体长尾覆盖率: 有偏 %.1f%% -> 动量混合 %.1f%% -> 完全无偏 %.1f%%"
          % (100 * b_tail, 100 * m_tail, 100 * c_tail))
    print("群体真实偏好命中: 有偏 %.1f%% -> 动量混合 %.1f%% -> 完全无偏 %.1f%%"
          % (100 * b_hit, 100 * m_hit, 100 * c_hit))
    print("单用户示例(用户 %d, 交互 %d 条): 长尾覆盖 有偏 %.1f%% -> 无偏 %.1f%%"
          % (user_id, len(already), 100 * tail_single_biased, 100 * tail_single))
    print("有偏推荐前5: %s" % b_rank[:5])
    print("无偏推荐前5: %s" % c_rank[:5])

    # ① 的结论拆成三条必须同时成立的断言:长尾显著提升、整体命中不降、注入是单调的
    assert c_tail > b_tail, "无偏权重的长尾覆盖率必须高于有偏基线"
    assert c_hit >= b_hit, "去偏不得牺牲整体真实偏好命中"
    assert b_tail <= m_tail <= c_tail, "动量注入应按比例逐步起作用"
    assert set(c_rank).isdisjoint(already), "已交互商品不应出现在推荐里"
    print("[✓] CAGED Debiased Rec 测试通过")


if __name__ == "__main__":
    run_demo()

8. 论文来源

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