学术
模块更新于 2026-11-21· 浏览 0· 下载 0

QSHP 乘积博弈归因

利用乘积结构把归因化为一维多项式积分,以高斯求积配合对数前后缀扫描共享计算。首页使用原论文完整算法框,不是网络架构图;理论误差证书只控制精确算术下的求积误差。

医学影像可解释人工智能Shapley值数值计算高斯求积模型解释

结构图

QSHP 乘积博弈归因结构图
QSHP 乘积博弈归因结构图

利用乘积结构把归因化为一维多项式积分,以高斯求积配合对数前后缀扫描共享计算。首页使用原论文完整算法框,不是网络架构图;理论误差证书只控制精确算术下的求积误差。

论文信息

  • 论文:QuadraSHAP: ε-Exact Shapley Values for Product Games in Logarithmic Parallel Time

核心痛点

Shapley联盟枚举成本高,逐特征长乘积还有数值溢出、下溢与重复计算问题。

模块亮点

  • 利用乘积结构把归因化为一维多项式积分,以高斯求积配合对数前后缀扫描共享计算。首页使用原论文完整算法框,不是网络架构图;理论误差证书只控制精确算术下的求积误差。

适用场景

乘积核、对数链接模型、Cox相对风险及赔率尺度的模型解释。不是任意黑盒网络的直接替代品,其他任务需单独验证。

插入位置建议

  • 模型训练后先构造存在和缺失因子表,再调用归因器。核对基线、尺度与精度;当前源码多分量上界未按论文累加,不能直接用自动预算认证最终误差。

适用任务

  • 乘积核
  • 对数链接模型
  • Cox相对风险及赔率尺度的模型解释。不是任意黑盒网络的直接替代品

完整代码

qshp.py
"""QuadraSHAP:乘积博弈的 ε-精确 Shapley 值(Gauss–Legendre 求积)。

论文:QuadraSHAP: ε-Exact Shapley Values for Product Games in Logarithmic Parallel Time
(ICLR 2027 投稿)。模块名:QuadraSHAP(本文件 quadra_shap.py)。

问题:乘积博弈 v(S)=∏_{j∈S} u_j 的 Shapley 值需枚举 2^d 个联盟,且逐特征连乘上千个因子
会溢出/下溢。方法:借用 Shapley 权重的积分表示 µ(s)=∫_0^1 t^s(1-t)^{d-s-1}dt,把联盟和化为
φ_i=(u_i-ũ_i)∫_0^1 ∏_{j≠i}[(1-t)ũ_j + t u_j] dt,即一条次数 ≤ d-1 的一维多项式积分;再用
m_q 点 Gauss–Legendre 求积(m_q ≥ ⌈d/2⌉ 时精确),并由因子直接算出几何衰减的误差界,在求值
前选出满足容差 ε 的最小节点预算。该模块作用:给定每个特征的存在因子 u 与缺失因子 ũ,一次前向
输出全部 d 个 Shapley 值;内部在对数空间用前后缀共享乘积,复杂度 O(d·m_q),支持 batch 与 CPU/GPU。
"""

import math
import sys

import torch
import torch.nn as nn


def _excl_cumsum(x: torch.Tensor, dim: int = -1) -> torch.Tensor:
    """指定维上不含当前元素的前缀和:out[..., i] = Σ_{j<i} x[..., j](空和取 0)。"""
    c = torch.cumsum(x, dim=dim)
    head = torch.zeros_like(c.narrow(dim, 0, 1))
    return torch.cat((head, c.narrow(dim, 0, c.size(dim) - 1)), dim=dim)


class QuadraSHAP(nn.Module):
    """乘积博弈(及加权和)上的 ε-精确 Shapley 值求积器。

    输入每个特征的“存在因子” u_j 与“缺失因子” ũ_j(neutral-factor 取 ũ≡1,baseline 取
    ũ_j=u_j(x^b),经验干预式则把背景点与分量一起放进 R 轴并给权重 c_r/n_b),输出全部特征的
    Shapley 值。逐特征共享 ∏_{j≠i} T_{q,j},因此总工作量 O(d·m_q) 而非 O(d^2·m_q)。
    """

    def __init__(self, eps: float = 1e-6, num_nodes: int | None = None, n_rho: int = 48):
        super().__init__()
        self.eps = float(eps)            # 逐特征允许的绝对误差;0 表示精确(⌈d/2⌉ 个节点)
        self.num_nodes = num_nodes       # 显式覆盖节点数;None 时由 ε 自动认证预算
        self.n_rho = int(n_rho)          # 误差界中 inf over ρ 的网格密度
        self._rule_cache: dict = {}
        lo, hi = math.log(1e-6), math.log(1e4)   # ρ-1 的取值网格(对数均匀)
        self._delta = tuple(math.exp(lo + i * (hi - lo) / (self.n_rho - 1)) for i in range(self.n_rho))
        self.last_num_nodes: int | None = None   # 本次前向实际使用的节点数
        self.last_error_bound: float | None = None  # 本次前向的认证误差界(精确算术下)

    # ------------------------------------------------------------------ 求积规则
    def _gauss_legendre(self, m: int, device):
        """[0,1] 上的 m 点 Gauss–Legendre 节点/权重(Jacobi 矩阵特征分解,双精度)。"""
        rule = self._rule_cache.get(m)
        if rule is None:
            k = torch.arange(1, m, dtype=torch.float64)
            beta = k / torch.sqrt(4.0 * k * k - 1.0)          # 三对角 Jacobi 矩阵的次对角线
            jac = torch.zeros(m, m, dtype=torch.float64)
            idx = torch.arange(m - 1)
            jac[idx, idx + 1], jac[idx + 1, idx] = beta, beta
            nodes, vecs = torch.linalg.eigh(jac)
            rule = (0.5 * (nodes + 1.0), vecs[0] ** 2)         # 仿射映射到 [0,1],权重 = v_0^2
            self._rule_cache[m] = rule
        return rule[0].to(device), rule[1].to(device)

    # --------------------------------------------------------------- 误差界(命题 3)
    def _bound_terms(self, u, ua, w):
        """返回 (log_scale, Λ):误差界为 |c_r|·|u_i-ũ_i|·Π_i·B(m,Λ_i)。"""
        M = torch.maximum(u.abs(), ua.abs())                  # M_j := max(|u_j|, |ũ_j|)
        diff = (u - ua).abs()
        pos = M > 0
        M_safe = torch.where(pos, M, torch.ones_like(M))
        var = torch.where(pos, diff / M_safe, torch.zeros_like(M))
        logM = torch.where(pos, torch.log(M_safe), torch.zeros_like(M))
        # 不含第 i 个特征的前/后缀乘积与和:Π_i = ∏_{j≠i} M_j,Λ_i 即“总相对变差”
        log_pi = _excl_cumsum(logM) + _excl_cumsum(logM.flip(-1)).flip(-1)
        lam = _excl_cumsum(var) + _excl_cumsum(var.flip(-1)).flip(-1)
        log_scale = torch.log(w.abs()).unsqueeze(-1) + torch.log(diff) + log_pi
        return log_scale, lam

    def _log_bound(self, log_scale, lam, m: int) -> torch.Tensor:
        """log of max_i bound,其中 B(m,Λ)=inf_{ρ>1} C_ρ exp(Λ(ρ+1/ρ-2)/4) ρ^{-2m}。"""
        best = None
        for delta in self._delta:
            rho = 1.0 + delta
            log_b = (math.log(32.0 / 15.0) - math.log1p(-1.0 / (rho * rho))
                     + lam * ((rho + 1.0 / rho - 2.0) * 0.25) - 2.0 * m * math.log(rho))
            lb = log_b + log_scale
            best = lb if best is None else torch.minimum(best, lb)
        return best.max()

    def _bound_to_float(self, lb: float) -> float:
        if lb <= -745.0:
            return 0.0
        return math.exp(lb) if lb < 709.0 else math.inf

    def _select_nodes(self, u, ua, w, m_exact: int):
        """二分出满足容差 ε 的最小节点预算;无更小预算被认证时退回 ⌈d/2⌉。"""
        if self.eps <= 0.0:
            return m_exact, 0.0
        log_scale, lam = self._bound_terms(u, ua, w)
        thr = math.log(self.eps)
        lo, hi = 1, m_exact
        while lo < hi:                                        # 误差界关于 m 单调不增
            mid = (lo + hi) // 2
            if self._log_bound(log_scale, lam, mid).item() <= thr:
                hi = mid
            else:
                lo = mid + 1
        lb = self._log_bound(log_scale, lam, lo).item()
        if lb > thr:
            return m_exact, 0.0
        return lo, self._bound_to_float(lb)

    # ------------------------------------------------------------------------ 前向
    def forward(self, u_present, u_absent=None, component_weights=None, num_nodes=None):
        """u_present: (B,R,d) 或 (B,d) 的存在因子;u_absent: 同形的缺失因子(None → 全 1)。
        component_weights: (B,R) 或 (R,) 的分量权重 c_r(默认 1/R,即对背景点均匀平均)。
        返回 (B,d)(或 (d,) 形式按输入维度对齐)的全部特征 Shapley 值。"""
        u = torch.as_tensor(u_present)
        out_dtype = u.dtype
        squeeze = u.dim() == 2
        if squeeze:
            u = u.unsqueeze(1)                                # (B,d) → (B,1,d)
        u = u.to(torch.float64)
        B, R, d = u.shape
        ua = torch.ones_like(u) if u_absent is None else torch.as_tensor(u_absent).to(u)
        if ua.dim() == 2:
            ua = ua.unsqueeze(1)
        ua = ua.expand_as(u)                                  # (B,R,d) 缺失因子 ũ_j
        if component_weights is None:
            w = torch.full((B, R), 1.0 / R, dtype=torch.float64, device=u.device)
        else:
            w = torch.as_tensor(component_weights).to(u)      # (R,) 或 (B,R)
            w = w.expand(B, R) if w.dim() == 1 and w.numel() == R else w
            if w.shape != (B, R):
                raise ValueError("component_weights 需为 (R,) 或 (B,R)")

        m_exact = (d + 1) // 2                                # ⌈d/2⌉ 个节点即多项式精确
        m = num_nodes if num_nodes is not None else self.num_nodes
        if m is None:
            m, bound = self._select_nodes(u, ua, w, m_exact)
        else:
            m = max(1, int(m))
            lb = -math.inf if m >= m_exact else self._log_bound(*self._bound_terms(u, ua, w), m).item()
            bound = 0.0 if m >= m_exact else self._bound_to_float(lb)
        self.last_num_nodes, self.last_error_bound = m, bound

        taus, omegas = self._gauss_legendre(m, u.device)      # (mq,), (mq,)
        # 式(11):T_{q,j} = (1-τ_q)ũ_j + τ_q u_j
        T = u.unsqueeze(-1) * taus + ua.unsqueeze(-1) * (1.0 - taus)      # (B,R,d,mq)
        nz = T != 0
        logmag = torch.where(nz, torch.log(torch.where(nz, T.abs(), torch.ones_like(T))), torch.zeros_like(T))
        neg = (T < 0).to(torch.int64)
        zer = (~nz).to(torch.int64)
        # 对数空间 + 符号/零计数:得到每个节点上“去掉第 i 个因子”的共享乘积,零因子也安全
        F = -2                                                # 特征维(B,R,d,mq 中的 d)
        log_excl = _excl_cumsum(logmag, F) + _excl_cumsum(logmag.flip(F), F).flip(F)
        neg_excl = _excl_cumsum(neg, F) + _excl_cumsum(neg.flip(F), F).flip(F)
        zer_excl = _excl_cumsum(zer, F) + _excl_cumsum(zer.flip(F), F).flip(F)
        sgn = torch.where(zer_excl > 0, torch.zeros_like(log_excl),
                          torch.where(neg_excl % 2 == 0, torch.ones_like(log_excl), -torch.ones_like(log_excl)))
        prod_excl = sgn * torch.exp(log_excl)                 # ∏_{j≠i} T_{q,j},shape (B,R,d,mq)
        phi = ((u - ua).unsqueeze(-1) * prod_excl * omegas).sum(-1)   # (B,R,d)
        phi = (phi * w.unsqueeze(-1)).sum(1)                  # (B,d) 按权重聚合分量/背景
        phi = phi.to(out_dtype)
        return phi.squeeze(1) if squeeze else phi


if __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8")
    torch.manual_seed(0)
    B, R, d = 2, 4, 41                      # batch / 乘积分量数(含背景)/ 特征数
    u = torch.rand(B, R, d, dtype=torch.float64) * 1.5 + 0.5
    ua = torch.rand(B, R, d, dtype=torch.float64) * 0.8 + 0.1
    w = torch.full((B, R), 1.0 / R, dtype=torch.float64)

    approx, exact = QuadraSHAP(eps=1e-6), QuadraSHAP(eps=0.0)
    phi_hat = approx(u, ua, w)
    phi_exact = exact(u, ua, w)
    eff = ((u.prod(-1) - ua.prod(-1)) * w).sum(-1)          # 效率性:Σ_i φ_i = v(D) - v(∅)
    print("u_present   :", tuple(u.shape), " u_absent:", tuple(ua.shape))
    print("phi (eps=1e-6):", tuple(phi_hat.shape), " nodes:", approx.last_num_nodes,
          " bound: %.2e" % approx.last_error_bound)
    print("phi (eps=0)   :", tuple(phi_exact.shape), " nodes:", exact.last_num_nodes)
    print("|phi_hat - phi_exact|max : %.3e" % (phi_hat - phi_exact).abs().max().item())
    print("efficiency err           : %.3e" % (phi_exact.sum(-1) - eff).abs().max().item())
    one = QuadraSHAP(eps=1e-6)
    single = one(u[:, 0])                                   # 单分量 2D 输入分支
    print("single-game phi:", tuple(single.shape), " nodes:", one.last_num_nodes)

环境与依赖

Python 3.9+

继续浏览

下一篇RAP 径角随机投影精确保留锚点测地半径,只投影单位角向量,再归一化并重建低维双曲点。无需额外训练,主要计算为一次矩阵乘法;距离保证仍需要有界半径与点对分离等条件。

相关资源