rng = np.random.default_rng()
n = 1000
X_src = rng.normal(0, 1, (n, 2)) # source p_S: centered at (0, 0)
X_tgt = rng.normal(0, 1, (n, 2)) + [2, 0] # target p_T: centered at (2, 0)
label = lambda X: (X[:, 1] > 0.5 * X[:, 0]**2 - 1).astype(float)
y_src, y_tgt = label(X_src), label(X_tgt) # one labeling rule for both3.6 环境与分布偏移
3.5 节 中的每一条保证都建立在一个隐含前提之上:部署数据与训练集、测试集来自完全相同的分布。现实世界不断打破这一假设。扫描仪和相机会升级换代,季节性流感一夜之间就会改变患病率,地方俚语也在持续演变;更糟的是,部署模型本身就可能促使人群改变行为。假设银行从历史记录中发现穿牛津鞋的贷款申请人比穿运动鞋的更常按时还款,于是部署了一个“批准牛津鞋、拒绝运动鞋”的分类器;不出几周,所有申请人都会穿着牛津鞋上门,而实际的违约率纹丝不动——这正是 Goodhart 定律(Goodhart’s law)的经典案例:当一个统计相关指标成为决策目标时,它就不再是有效的相关指标。
本节研究如何检测并校正源分布(source distribution)\(p_S(\mathbf{x}, y)\)(拥有带标签的训练数据)与目标分布(target distribution)\(p_T(\mathbf{x}, y)\)(仅观测到无标签的部署输入 \(\mathbf{x}\))之间的分布偏移。我们按联合分布中保持不变的因子梳理三种经典的被动偏移类型,推导并实现重要性加权协变量偏移校正与混淆矩阵标签偏移校正,最后讨论概念偏移与反馈循环。
3.6.1 分布偏移的类型
如果没有某种连接 \(p_S(\mathbf{x}, y)\) 与 \(p_T(\mathbf{x}, y)\) 的结构假设,适应无标签目标域在数学上是不可能的:如果 \(p_T(\mathbf{x}) = p_S(\mathbf{x})\) 保持不变,而猫和狗的标签在一夜之间悄然互换(\(p_T(y = \textrm{cat} \mid \mathbf{x}) = p_S(y = \textrm{dog} \mid \mathbf{x})\)),任何只看无标签目标图像的算法都不可能察觉这种互换。
每个联合分布都可以按两种方式分解:
\[p(\mathbf{x}, y) = p(\mathbf{x})\, p(y \mid \mathbf{x}) = p(y)\, p(\mathbf{x} \mid y). \tag{3.6.1}\]
固定其中一个条件因子、令边缘分布发生漂移,就定义了三种经典的分布偏移情形(图 3.6.1):
| 偏移类型 | 变化量 | 不变量 | 自然因果场景 |
|---|---|---|---|
| 协变量偏移 | \(p(\mathbf{x})\) | \(p(y \mid \mathbf{x})\) | 特征 \(\mathbf{x}\) 导致标签 \(y\) |
| 标签偏移 | \(p(y)\) | \(p(\mathbf{x} \mid y)\) | 标签 \(y\) 导致特征 \(\mathbf{x}\) |
| 概念偏移 | \(p(y \mid \mathbf{x})\) | 通常为 \(p(\mathbf{x})\) | 标签定义随时间或空间漂移 |
3.6.1.1 协变量偏移、标签偏移与概念偏移
- 协变量偏移(\(p(y \mid \mathbf{x})\) 不变):当 \(\mathbf{x}\) 导致 \(y\) 时自然出现。假设我们在真实照片(图 3.6.2)上训练猫狗分类器,再部署到卡通图像(图 3.6.3)上。卡通猫依然是猫(\(p(y \mid \mathbf{x})\) 未变),但边缘输入分布 \(p(\mathbf{x})\) 已移入像素空间的新区域。尽管真实的贝叶斯边界没有移动,在源照片上拟合的误设定或容量受限模型会把准确率集中在 \(p_S(\mathbf{x})\) 稠密的区域,而在 \(p_T(\mathbf{x})\) 所在区域严重失灵。
- 标签偏移(\(p(\mathbf{x} \mid y)\) 不变):当 \(y\) 导致 \(\mathbf{x}\) 时自然出现。例如疾病导致症状,流感爆发期间流感的患病率 \(p(y)\) 激增,但流感患者的症状分布 \(p(\mathbf{x} \mid y)\) 保持不变。由贝叶斯定理,\(p(y \mid \mathbf{x}) \propto p(\mathbf{x} \mid y)\,p(y)\),因此类别先验的变化会移动最优决策边界。校正标签偏移只需估计 \(q\) 个类别先验比值,而无须估计高维输入 \(\mathbf{x}\) 上的密度比。
- 概念偏移(\(p(y \mid \mathbf{x})\) 变化):标签本身的含义随地域或时间改变,例如美国各县对碳酸软饮料的不同叫法(图 3.6.4)、不断修订的诊断标准或季节性购物意图。
3.6.2 协变量偏移校正
3.6.2.1 重要性权重
部署时我们希望最小化目标风险(target risk)\(R_T[f] = \mathbb{E}_{(\mathbf{x}, y) \sim p_T}[l(f(\mathbf{x}), y)]\)。在协变量偏移(\(p_T(y \mid \mathbf{x}) = p_S(y \mid \mathbf{x}) = p(y \mid \mathbf{x})\))下,只要源分布的支集覆盖目标分布(凡 \(p_T(\mathbf{x}) > 0\) 处均有 \(p_S(\mathbf{x}) > 0\)),通过同时乘除以 \(p_S(\mathbf{x})\) 即可将目标风险改写为源分布上的期望 (Shimodaira 2000年):
\[ \begin{aligned} R_T[f] &= \sum_{y} \int l(f(\mathbf{x}), y)\, p(y \mid \mathbf{x})\, p_T(\mathbf{x}) \;d\mathbf{x} \\ &= \sum_{y} \int l(f(\mathbf{x}), y)\, p(y \mid \mathbf{x})\, p_S(\mathbf{x})\, \frac{p_T(\mathbf{x})}{p_S(\mathbf{x})} \;d\mathbf{x} \\ &= \mathbb{E}_{(\mathbf{x}, y) \sim p_S}\left[\beta(\mathbf{x})\, l(f(\mathbf{x}), y)\right], \end{aligned} \tag{3.6.2}\]
其中 \(\beta(\mathbf{x}) = p_T(\mathbf{x}) / p_S(\mathbf{x})\) 为输入 \(\mathbf{x}\) 的重要性权重(importance weight)。在 \(n\) 个带标签源样本上近似 式 3.6.2,就得到加权经验风险最小化(weighted empirical risk minimization):
\[ \begin{aligned} \mathop{\mathrm{minimize}}_f \; &\frac{1}{n} \sum_{i=1}^n \beta_i\, l(f(\mathbf{x}^{(i)}), y^{(i)}), \\ \textrm{where } &\beta_i = \frac{p_T(\mathbf{x}^{(i)})}{p_S(\mathbf{x}^{(i)})}. \end{aligned} \tag{3.6.3}\]
注意为什么支集重叠(support overlap,凡 \(p_T(\mathbf{x}) > 0\) 处均有 \(p_S(\mathbf{x}) > 0\))不可或缺:如果一家医疗初创公司从老年患者采集患病血样,而健康对照组全部采自 20 岁的大学生,任何重加权都无法在 \(p_S(\mathbf{x}) = 0\) 的区域凭空造出老年健康对照样本。即便支集重叠,右尾的极端比值(图 3.6.5)也可能导致极少数样本主导求和,使有效样本量(effective sample size)\(n_{\textrm{eff}} = (\sum_i \beta_i)^2 / \sum_i \beta_i^2\) 骤降;将权重截断到上限 \(\min(\beta_i, c)\) 可以用微小偏差换取大得多的 \(n_{\textrm{eff}}\)。
3.6.2.2 用域分类器估计权重
如何在不分别估计高维密度 \(p_S\) 和 \(p_T\) 的情况下估计 \(\beta(\mathbf{x}) = p_T(\mathbf{x}) / p_S(\mathbf{x})\)?将 \(n\) 个源输入(赋予域标签 \(z = 0\))与 \(m\) 个无标签目标输入(赋予域标签 \(z = 1\))合并,训练一个二元逻辑回归域分类器(domain classifier)\(P(z = 1 \mid \mathbf{x}) = \sigma(h(\mathbf{x}))\),其 logit 为 \(h(\mathbf{x})\)。由贝叶斯定理,
\[ \begin{aligned} \frac{P(z = 1 \mid \mathbf{x})}{P(z = 0 \mid \mathbf{x})} &= \frac{m}{n}\,\frac{p_T(\mathbf{x})}{p_S(\mathbf{x})} = \exp(h(\mathbf{x})), \\ \textrm{so} \quad \beta(\mathbf{x}) &= \frac{n}{m}\exp(h(\mathbf{x})). \end{aligned} \]
省去常数因子 \(n/m\)(它只缩放目标函数而不改变极小点),只需用 \(\beta_i = \exp(h(\mathbf{x}^{(i)}))\)(或 \(\min(\exp(h(\mathbf{x}^{(i)})), c)\))对每个源样本加权即可。
域分类器还有第二个用途:判断是否存在需要校正的偏移。如果 \(p_T(\mathbf{x}) = p_S(\mathbf{x})\),源输入与目标输入无法区分,域分类器在未用于训练的合并输入上准确率停留在随机猜测水平(\(n = m\) 时为 \(1/2\))。因此,准确率明显高于随机水平就是输入发生偏移的证据;这一检验称为分类器双样本检验(classifier two-sample test)(Lopez-Paz 和 Oquab 2017年)。标签偏移的检测代价更低:在无标签目标输入上运行已部署分类器,比较各类别的预测频率与源验证集上的对应频率即可。上线系统应当同时监控这两项指标,因为偏移必须先被发现才能校正。
3.6.2.3 二维示例
下面看一个二维问题,观察域分类器重加权如何挽救线性分类器:设 \(p_S = \mathcal{N}(\mathbf{0}, \mathbf{I}_2)\),\(p_T = \mathcal{N}((2, 0)^\top, \mathbf{I}_2)\),真实标签为 \(y = \mathbf{1}(x_2 > \frac{1}{2}x_1^2 - 1)\)。由于真实的抛物线边界向上弯曲,在 \((0, 0)\) 附近最优的直线边界几乎是水平的,到了 \((2, 0)\) 附近就会彻底失效。我们生成 \(n = 1{,}000\) 个源样本点和 \(1{,}000\) 个目标样本点,拟合逻辑回归域分类器 \(h(\mathbf{x})\) 以估计 \(\beta_i = \exp(h(\mathbf{x}^{(i)}))\),并比较无权重、重要性加权以及截断权重(\(c = 5\))的逻辑回归:
我们唯一用到的学习组件是用梯度下降训练的加权逻辑回归。由 3.1.2.2 节 可知,交叉熵关于 logit 的梯度就是残差 \(\sigma(\mathbf{w}^\top \mathbf{x} + b) - y\),因此给样本 \(i\) 加权 \(\beta_i\) 只需将其残差乘以 \(\beta_i\)。
def fit_logreg(X, y, weights=None, lr=0.1, steps=2000):
"""Logistic regression by gradient descent on the weighted mean loss."""
w, b = np.zeros(X.shape[1]), 0.0
v = np.ones(len(y)) if weights is None else weights / weights.mean()
for _ in range(steps):
r = v * (1 / (1 + np.exp(-(X @ w + b))) - y) # weighted error
w -= lr * X.T @ r / len(y)
b -= lr * r.mean()
return w, b首先,我们将 X_src(域标签 \(z = 0\))和 X_tgt(\(z = 1\))合并,用 fit_logreg 训练域分类器 (w_h, b_h),把学到的 logit \(h(\mathbf{x})\) 与解析高斯对数密度比 \(2x_1 - 2\) 对比,并检查所得的源重要性权重 beta 及其有效样本量 ess。最后几行重新抽取新的源输入和目标输入,测量域分类器区分两者的准确率:
z = np.concatenate([np.zeros(n), np.ones(n)]) # domain label: 1 = target
w_h, b_h = fit_logreg(np.concatenate([X_src, X_tgt]), z)
beta = np.exp(X_src @ w_h + b_h) # weights of source examples
ess = lambda v: v.sum()**2 / (v**2).sum() # effective sample size
print(f'learned h(x) = {w_h[0]:.2f} x1 {w_h[1]:+.2f} x2 {b_h:+.2f}'
f' (true log-ratio: 2 x1 - 2)')
print(f'largest weight: {beta.max():.0f}; effective sample size: '
f'{ess(beta):.0f} of {n}, {ess(np.minimum(beta, 5)):.0f} if clipped at 5')
X_out = np.concatenate([rng.normal(0, 1, (n, 2)), # fresh source and
rng.normal(0, 1, (n, 2)) + [2, 0]]) # target inputs
print(f'domain classifier accuracy on held-out inputs: '
f'{((X_out @ w_h + b_h > 0) == (z == 1)).mean():.2f} (chance: 0.50)')learned h(x) = 1.98 x1 +0.09 x2 -1.98 (true log-ratio: 2 x1 - 2)
largest weight: 193; effective sample size: 23 of 1000, 221 if clipped at 5
domain classifier accuracy on held-out inputs: 0.84 (chance: 0.50)
learned h(x) = 1.97 x1 +0.01 x2 -1.95 (true log-ratio: 2 x1 - 2)
largest weight: 124; effective sample size: 40 of 1000, 219 if clipped at 5
domain classifier accuracy on held-out inputs: 0.84 (chance: 0.50)
learned h(x) = 2.03 x1 -0.10 x2 -2.01 (true log-ratio: 2 x1 - 2)
largest weight: 91; effective sample size: 54 of 1000, 216 if clipped at 5
domain classifier accuracy on held-out inputs: 0.83 (chance: 0.50)
learned h(x) = 1.99 x1 +0.04 x2 -2.02 (true log-ratio: 2 x1 - 2)
largest weight: 87; effective sample size: 51 of 1000, 218 if clipped at 5
domain classifier accuracy on held-out inputs: 0.85 (chance: 0.50)
在新输入上,域分类器区分源与目标的准确率约为 \(0.84\),远高于随机猜测的 \(0.50\),可见这种偏移很容易检测。这里没有分类器能做得更好:两个高斯分布仅在 \(x_1\) 的均值上不同,最优判别规则是 \(x_1 > 1\),其正确概率为 \(\Phi(1) \approx 0.84\),其中 \(\Phi\) 为标准正态分布函数。
接下来,我们在带标签源数据 (X_src, y_src) 上分别采用三种加权方案(无权重 'unweighted'、原始重要性权重 'weighted',以及在 \(5\) 处截断的权重 'clipped')调用 fit_logreg 训练,并在 X_tgt 和 X_src 上评估各分类器的准确率:
acc = lambda wb, X, y: ((X @ wb[0] + wb[1] > 0) == (y == 1)).mean()
models = {name: fit_logreg(X_src, y_src, v) for name, v in [
('unweighted', None), ('weighted', beta), ('clipped', np.minimum(beta, 5))]}
for name, wb in models.items():
print(f'{name:10s} target accuracy {acc(wb, X_tgt, y_tgt):.3f}'
f' source accuracy {acc(wb, X_src, y_src):.3f}')
print(f'always predicting the most common target class: '
f'{max(y_tgt.mean(), 1 - y_tgt.mean()):.3f}')unweighted target accuracy 0.603 source accuracy 0.853
weighted target accuracy 0.945 source accuracy 0.854
clipped target accuracy 0.944 source accuracy 0.854
always predicting the most common target class: 0.711
unweighted target accuracy 0.572 source accuracy 0.858
weighted target accuracy 0.939 source accuracy 0.837
clipped target accuracy 0.940 source accuracy 0.850
always predicting the most common target class: 0.704
unweighted target accuracy 0.494 source accuracy 0.853
weighted target accuracy 0.947 source accuracy 0.799
clipped target accuracy 0.953 source accuracy 0.807
always predicting the most common target class: 0.716
unweighted target accuracy 0.522 source accuracy 0.850
weighted target accuracy 0.957 source accuracy 0.837
clipped target accuracy 0.956 source accuracy 0.841
always predicting the most common target class: 0.723
为了直观展示重加权为何效果如此显著,我们绘制目标与源点云(将每个源样本点的面积按 beta 缩放),同时画出真实抛物线 \(x_2 = \frac{1}{2}x_1^2 - 1\) 以及 'unweighted' 和 'weighted' 的线性决策边界:
x1 = np.linspace(-2.5, 4.5, 50)
d2l.set_figsize((4.5, 3.5))
d2l.plt.scatter(*X_tgt.T, s=2, c='C1', label='target')
d2l.plt.scatter(*X_src.T, s=np.clip(beta, 0.2, 20), c='C0',
label=r'source, area $\propto \beta$')
d2l.plt.plot(x1, 0.5 * x1**2 - 1, 'k--', label='true boundary')
for name, fmt in [('unweighted', 'C2'), ('weighted', 'C3')]:
(w1, w2), b = models[name]
d2l.plt.plot(x1, -(w1 * x1 + b) / w2, fmt, label=name)
d2l.plt.xlabel('$x_1$'), d2l.plt.ylabel('$x_2$'), d2l.plt.ylim(-3, 5)
d2l.plt.legend();结果一目了然:在偏移后的目标点云上,无权重训练的准确率只有 \(\sim 50\%\)–\(60\%\)(甚至不如永远猜多数类的 \(\sim 70\%\)),而重要性重加权在零目标标签的情况下,把线性决策边界倾斜贴合到抛物线右支上,将目标准确率提升到 \(\sim 95\%\)。
不过,不能由此断言协变量偏移下就一定应该重加权。这里重加权奏效是因为直线无法拟合抛物线:模型存在误设定,必须在何处保持准确之间做取舍。如果模型足够灵活、在源分布有数据的地方都能拟合好 \(p(y \mid \mathbf{x})\),那么加权与无权重目标具有相同的极小点,重加权不会带来增益 (Shimodaira 2000年)。深度网络正接近这种情形:一旦训练到很低的训练损失,重要性权重的作用就会消退 (Byrd 和 Lipton 2019年);在真实世界偏移基准 WILDS 上,专门针对分布偏移设计的方法也很少超过普通的经验风险最小化 (Koh 等 2021年)。实践中应对协变量偏移的主要手段还是在更广泛的数据上训练,并用少量带标签目标样本做微调。
3.6.3 标签偏移校正
在标签偏移(\(p_T(\mathbf{x} \mid y) = p_S(\mathbf{x} \mid y)\) 而类别比例 \(p_T(y) \neq p_S(y)\) 发生变化)下,同样的重要性加权恒等关系给类别 \(y\) 的每个源样本赋予类别先验比值 \(\beta(y) = p_T(y) / p_S(y)\)。由于 \(p_S(y)\) 可由训练标签直接获知,唯一的挑战在于仅凭无标签目标数据估计目标类别比例 \(\mathbf{p}_T \in \mathbb{R}^q\)。
3.6.3.1 通过混淆矩阵估计目标比例
设 \(\mathbf{C} \in \mathbb{R}^{q \times q}\) 为 3.3 节 中源分类器的列归一化混淆矩阵,其元素 \(C_{ij} = P_S(\hat{c} = i \mid y = j)\) 在带标签源验证集上估计得到。因为 \(\hat{c}\) 仅是 \(\mathbf{x}\) 的函数,且在标签偏移下 \(p(\mathbf{x} \mid y)\) 不变,所以 \(P_T(\hat{c} = i \mid y = j) = C_{ij}\) 在目标域同样成立。由全概率公式,无标签目标输入上各类别预测频率组成的向量 \(\boldsymbol{\mu} \in \mathbb{R}^q\) 满足 (Saerens 等 2002年; Lipton 等 2018年)
\[ \begin{aligned} \mu_i &= \sum_{j=1}^q P(\hat{c} = i \mid y = j)\, p_T(y = j) = \sum_{j=1}^q C_{ij}\, p_T(y = j), \\ \textrm{or} \quad \mathbf{C}\, \mathbf{p}_T &= \boldsymbol{\mu}. \end{aligned} \tag{3.6.4}\]
只要 \(\mathbf{C}\) 可逆(只要分类器在每个类别上的正确率都超过一半,即 \(C_{jj} > 1/2\) 即可保证;见 3),求解这个 \(q \times q\) 线性方程组 \(\hat{\mathbf{p}}_T = \mathbf{C}^{-1}\boldsymbol{\mu}\) 就能在不需要任何目标标签的情况下恢复未知的目标类别比例。此外,如果源分类器输出的概率近似源后验分布 \(p_S(y \mid \mathbf{x})\)(这一要求比 3.4 节 中的最高类别校准更强),则根据贝叶斯定理,无需重新训练,只需给每个类别的 logit 加上对数先验偏移 \(\log(\hat{p}_T(y) / p_S(y))\),即可立即将其预测适配到目标域。
下面在 Fashion-MNIST 上检验混淆矩阵求逆与贝叶斯 logit 调整。我们先在均衡训练集上训练 d2l.SoftmaxRegression,并收集验证集上的 logit O、标签 y 与预测类别 pred = O.argmax(axis=1):
data = d2l.FashionMNIST(batch_size=256)
model = d2l.SoftmaxRegression(num_outputs=10, lr=0.1)
trainer = d2l.Trainer(max_epochs=10)
trainer.board.display = False
trainer.fit(model, data)
O, y = [], []
for X, Y in data.val_dataloader():
O.append(d2l.numpy(model(X)))
y.append(d2l.numpy(Y))
O, y = np.concatenate(O), np.concatenate(y)
pred = O.argmax(axis=1)接下来,将 \(10{,}000\) 个验证样本随机划分为包含 \(5{,}000\) 张图像的源验证集 src(用于估计列归一化的 \(10 \times 10\) 混淆矩阵 C)和目标池 pool;再从目标池抽取一个偏斜目标集 tgt,其中 \(50\%\) 的服饰是衬衫(\(400\) 件衬衫,其余每类各 \(45\) 件),然后根据无标签目标预测频率 mu 求解 p_hat = np.linalg.solve(C, mu):
perm = rng.permutation(len(y))
src, pool = perm[:5000], perm[5000:] # Source validation set; target pool
C = np.zeros((10, 10))
np.add.at(C, (pred[src], y[src]), 1) # The confusion matrix of the source
C /= C.sum(axis=0, keepdims=True) # Each column sums to 1
counts = np.full(10, 45)
counts[6] = 400 # Half of the target images are shirts
p_T = counts / counts.sum()
tgt = np.concatenate([rng.choice(pool[y[pool] == j], counts[j], replace=False)
for j in range(10)])
mu = np.bincount(pred[tgt], minlength=10) / len(tgt) # Needs no labels
p_hat = np.linalg.solve(C, mu)
for j, name in enumerate(data.text_labels(range(10))):
print(f'{name:10s} true {p_T[j]:.2f}, predicted {mu[j]:.3f}, '
f'estimated {p_hat[j]:.3f}')T-shirt true 0.06, predicted 0.133, estimated 0.067
trouser true 0.06, predicted 0.055, estimated 0.055
pullover true 0.06, predicted 0.133, estimated 0.091
dress true 0.06, predicted 0.070, estimated 0.051
coat true 0.06, predicted 0.082, estimated 0.050
sandal true 0.06, predicted 0.052, estimated 0.054
shirt true 0.50, predicted 0.294, estimated 0.468
sneaker true 0.06, predicted 0.058, estimated 0.055
bag true 0.06, predicted 0.066, estimated 0.054
ankle boot true 0.06, predicted 0.057, estimated 0.057
T-shirt true 0.06, predicted 0.133, estimated 0.050
trouser true 0.06, predicted 0.055, estimated 0.054
pullover true 0.06, predicted 0.081, estimated 0.043
dress true 0.06, predicted 0.068, estimated 0.055
coat true 0.06, predicted 0.161, estimated 0.046
sandal true 0.06, predicted 0.056, estimated 0.058
shirt true 0.50, predicted 0.263, estimated 0.537
sneaker true 0.06, predicted 0.060, estimated 0.059
bag true 0.06, predicted 0.070, estimated 0.048
ankle boot true 0.06, predicted 0.053, estimated 0.051
T-shirt true 0.06, predicted 0.153, estimated 0.114
trouser true 0.06, predicted 0.052, estimated 0.052
pullover true 0.06, predicted 0.118, estimated 0.048
dress true 0.06, predicted 0.088, estimated 0.069
coat true 0.06, predicted 0.129, estimated 0.077
sandal true 0.06, predicted 0.055, estimated 0.057
shirt true 0.50, predicted 0.215, estimated 0.411
sneaker true 0.06, predicted 0.065, estimated 0.062
bag true 0.06, predicted 0.076, estimated 0.062
ankle boot true 0.06, predicted 0.050, estimated 0.049
T-shirt true 0.06, predicted 0.112, estimated 0.045
trouser true 0.06, predicted 0.056, estimated 0.055
pullover true 0.06, predicted 0.083, estimated 0.023
dress true 0.06, predicted 0.072, estimated 0.043
coat true 0.06, predicted 0.125, estimated 0.098
sandal true 0.06, predicted 0.052, estimated 0.054
shirt true 0.50, predicted 0.314, estimated 0.515
sneaker true 0.06, predicted 0.061, estimated 0.059
bag true 0.06, predicted 0.068, estimated 0.052
ankle boot true 0.06, predicted 0.056, estimated 0.054
最后,我们将对数先验偏移 log_w = np.log(np.maximum(p_hat, 1e-6) / 0.1) 加到目标 logit O[tgt] 上以适配估计出的目标分布,并对比调整前后的目标准确率:
log_w = np.log(np.maximum(p_hat, 1e-6) / 0.1) # log p_T(y) - log p_S(y)
accuracy = lambda O: (O.argmax(axis=1) == y[tgt]).mean()
print(f'target accuracy: {accuracy(O[tgt]):.3f} as trained, '
f'{accuracy(O[tgt] + log_w):.3f} adapted to the estimated proportions')target accuracy: 0.706 as trained, 0.816 adapted to the estimated proportions
target accuracy: 0.663 as trained, 0.807 adapted to the estimated proportions
target accuracy: 0.666 as trained, 0.799 adapted to the estimated proportions
target accuracy: 0.725 as trained, 0.807 adapted to the estimated proportions
尽管原始分类器只在 \(\sim 20\%\)–\(40\%\) 的目标图像上预测为“衬衫”(其余溢出到外观相近的上衣类别),\(\mathbf{C}^{-1}\boldsymbol{\mu}\) 仍能解开这种混淆,恢复出接近真实值 \(0.50\) 的衬衫比例(通常偏差在百分之几以内,偶尔接近十分之一);而将 \(\log(\hat{\mathbf{p}}_T / 0.1)\) 加到 logit 上后,零目标标签、零梯度步就能将目标准确率提高约 5~15 个百分点。
3.6.4 概念偏移与反馈
当概念偏移改变了 \(p(y \mid \mathbf{x})\) 本身时,历史标签已经过时,对旧数据做任何重要性重加权都无法学到新的标注规则;持续在少量新标注样本上监控并定期微调或重新训练至关重要。
当模型的预测触发重塑未来训练数据的动作——即施为预测(performative prediction)与反馈循环(feedback loop)——时,更需格外谨慎。在预测性警务(图 3.6.6)中,向预测犯罪率高的社区增派巡逻会导致当地记录下更多案件;将这些带偏差的逮捕记录反馈回下一轮训练,就会在失控循环中不断强化原有预测。打破或审计这类循环需要随机探索或独立数据采集,这已从被动监督学习跨入强化学习(第 14 章)。
3.6.5 小结
如果没有连接源分布 \(p_S(\mathbf{x}, y)\) 与目标分布 \(p_T(\mathbf{x}, y)\) 的结构不变性——无论是协变量偏移(\(p(y \mid \mathbf{x})\) 不变而 \(p(\mathbf{x})\) 漂移)、标签偏移(\(p(\mathbf{x} \mid y)\) 不变而 \(p(y)\) 漂移)还是概念偏移(\(p(y \mid \mathbf{x})\) 漂移)——就无法适应无标签的部署环境。在支集重叠的协变量偏移下,用区分源输入与无标签目标输入的逻辑回归域分类器估计权重 \(\beta(\mathbf{x}) = p_T(\mathbf{x})/p_S(\mathbf{x}) \propto \exp(h(\mathbf{x}))\) 并对源损失加权,可使误设定模型与目标风险对齐。在标签偏移下,通过 \(\hat{\mathbf{p}}_T = \mathbf{C}^{-1}\boldsymbol{\mu}\) 对源混淆矩阵求逆可从无标签目标预测恢复目标类别比例,并给校准后的 logit 直接加上 \(\log(\hat{\mathbf{p}}_T/\mathbf{p}_S)\) 完成适配。当概念偏移或决策驱动的反馈循环改变环境本身时,被动重加权不再足够,上线系统需要新鲜的目标标签和独立探索。
3.6.6 练习
支集缺失。设输入区域 \(\mathcal{A}\) 上满足 \(p_S(\mathbf{x}) = 0\),且该区域在目标分布下的概率为 \(\pi > 0\),而在其余各处 \(p_S(\mathbf{x}) > 0\)。在 \(\mathcal{A}\) 外定义 \(\beta(\mathbf{x}) = p_T(\mathbf{x})/p_S(\mathbf{x})\)。
- 证明加权源风险 \(\mathbb{E}_{(\mathbf{x}, y) \sim p_S}[\beta(\mathbf{x})\, l(f(\mathbf{x}), y)]\) 等于扣除 \(\mathcal{A}\) 的贡献后的目标风险,并将缺失项写作 \(\pi\) 乘以一个条件期望。
- 解释为什么对源样本做任何加权都无法恢复该缺失项。构造两个在 \(\mathcal{A}\) 外完全一致、加权源风险相同但目标风险不同的模型。
[code] 重加权失效之时。3.6.2 节 的代码(
fit_logreg、X_src、X_tgt、label)将目标均值置于 \((2, 0)\)。保持 \(n = 1000\) 和标注规则不变,将目标均值在 \((s, 0)\)(\(s \in \{0, 0.5, 1, 2, 3, 4, 6\}\))上扫描。- 对每个 \(s\),报告域分类器 \(h\) 在留出合并数据上的准确率,并从偏移可检测性的角度解释它随 \(s\) 的增长。
- 对每个 \(s\),记录无权重、加权、截断(\(c = 5\))模型以及永远预测最常见目标类别的目标准确率。解释为什么在 \(s\) 较大时仅凭目标准确率无法说明重加权是否奏效。
标签偏移方程组。设 \(\mathbf{C}\) 为 式 3.6.4 中的列归一化混淆矩阵。
- 证明只要对每个类别 \(j\) 都有 \(C_{jj} > \frac{1}{2}\),\(\mathbf{C}\) 就可逆。提示:假设存在 \(\mathbf{v} \neq \mathbf{0}\) 使得 \(\mathbf{v}^\top \mathbf{C} = \mathbf{0}\),考察 \(|v_j|\) 最大的那一列 \(j\),并利用每列元素之和为 1。
- 举一个使 \(\mathbf{C}\) 奇异的分类器例子,并说明此时 \(\boldsymbol{\mu}\) 仍能揭示关于 \(\mathbf{p}_T\) 的哪些信息。
- 对二分类情形,证明正类预测比例 \(\mu_1\) 中出现误差 \(\delta\) 会使估计的正类比例变化 \(\delta/(C_{11} - C_{10})\)。利用 \(m\) 个目标输入上比例估计的标准误 \(\sqrt{\mu_1 (1 - \mu_1)/m}\),求出筛查例子中要使患病比例估计的标准误达到 0.01 需要多少目标输入。再对同一人群上较弱的检测(\(C_{11} = 0.6\) 且 \(C_{10} = 0.4\))重复计算。
[code] 学到的权重与真实权重。● 沿用 2 中对目标均值 \((s, 0)\) 的扫描。
- 推导真实对数密度比 \(\log(p_T(\mathbf{x})/p_S(\mathbf{x}))\) 关于 \(s\) 的表达式,并在每个 \(s\) 上与学到的 \(h\) 比较。解释为什么当 \(s\) 较大时,域分类器能达到很高准确率,而 \(h\) 却远离真实对数密度比。
- 证明在源分布下真实权重满足 \(\mathbb{E}[\beta(\mathbf{x})] = 1\) 和 \(\mathbb{E}[\beta(\mathbf{x})^2] = e^{s^2}\),因此 \(n\) 较大时其有效样本量约为 \(n e^{-s^2}\)。对 \(n = 1000\) 和 \(s = 1, 2, 3\) 计算该值。
- 对每个 \(s\),在实际源样本上计算真实权重和学到权重的有效样本量。解释为什么在 \(s = 2\) 时样本估计值通常远大于 \(1000\, e^{-4} \approx 18\),以及这对仅凭样本判断重加权拟合的可靠性意味着什么。在 \(c = 5\) 处截断能弥补样本量不足吗?
从无标签数据辨别偏移假设。● 在二元源域中,\(p_S(y = 1) = p_S(y = 0) = \frac{1}{2}\),标量输入满足 \(x \mid y = 1 \sim \mathcal{N}(1, 1)\) 和 \(x \mid y = 0 \sim \mathcal{N}(-1, 1)\),从而 \(p_S(y = 1 \mid x) = 1/(1 + \exp(-2x))\)。无标签目标输入服从混合分布
\[p_T(x) = 0.8\, \mathcal{N}(x; 1, 1) + 0.2\, \mathcal{N}(x; -1, 1).\]
- 假设为标签偏移。给出 \(p_T(y = 1)\) 以及贝叶斯最优目标分类器关于 \(x\) 的阈值。
- 改设在相同 \(p_T(x)\) 下为协变量偏移。数值计算 \(p_T(y = 1)\) 并给出贝叶斯最优阈值。
- 结合你的结果解释,为什么无标签目标样本的任何统计量都无法判断本节的哪一种校正适用。