class Modulate(nn.Module):
"""Scale and shift each channel of h by a(c) and b(c), one row per class."""
def __init__(self, num_classes, channels):
super().__init__()
self.a = nn.Embedding(num_classes, channels)
self.b = nn.Embedding(num_classes, channels)
nn.init.ones_(self.a.weight) # a(c) = 1, b(c) = 0: the identity
nn.init.zeros_(self.b.weight)
def forward(self, h, c):
return self.a(c)[:, :, None, None] * h + self.b(c)[:, :, None, None]16.6 条件生成
16.1 节 与 16.5 节 中的生成器都是无条件的:它们从边缘数据分布 \(p(x)\) 中随机采样,却无法指定所需的类别、文本提示或输入图像。在原始 GAN 论文问世后不久,Mirza 和 Osindero (2014年) 通过将条件变量 \(c\) 同时输入生成器 \(G(z, c)\) 与判别器 \(D(x, c)\),提出了条件 GAN(cGAN)。
本节围绕三个问题展开:
- 条件形式优化的是什么目标,其最优评判器估计的是什么?
- 应如何将条件变量 \(c\) 融入生成器与判别器的架构?
- 如何分别从条件一致性、样本保真度与类内多样性三个维度评估条件生成器?
我们将通过在 CIFAR-10 的 10 个类别上训练并评估类别条件生成器来阐明这些概念。
16.6.1 条件目标函数
16.6.1.1 最优条件评判器
设数据–条件对 \((x, c) \sim p(x, c)\) 抽自联合数据分布,其中 \(c\) 可以是离散类别标签、文本嵌入或图像。为匹配条件边缘分布 \(p(c)\),我们从真实数据采样 \(c \sim p(c)\),并生成 \(x' = G(z, c) \sim q(\cdot \mid c)\),从而诱导生成联合分布 \(q(x, c) = p(c)\,q(x \mid c)\)。条件对数损失目标将经典二元对数损失形式(16.1 节)直接应用于样本对 \((x, c)\):
\[ \begin{aligned} V(D) &= \mathbb{E}_{(x, c) \sim p}\big[\log \sigma(D(x, c))\big] \\ &\quad + \mathbb{E}_{c \sim p(c),\; x' \sim q(\cdot \mid c)}\big[\log \sigma(-D(x', c))\big]. \end{aligned} \tag{16.6.1}\]
由于关于 \(D(x, c)\) 的逐点优化与乘积空间 \(\mathcal{X} \times \mathcal{C}\) 上的无条件推导完全一致,最优条件评判器即为联合密度的对数比,其中共享边缘分布 \(p(c)\) 相互抵消:
\[ \begin{aligned} D^\star(x, c) &= \log \frac{p(x, c)}{q(x, c)} = \log \frac{p(c)\, p(x \mid c)}{p(c)\, q(x \mid c)} = \log \frac{p(x \mid c)}{q(x \mid c)} . \end{aligned} \tag{16.6.2}\]
因此,对每个条件 \(c\),最优评判器计算的是条件分布 \(p(\cdot \mid c)\) 与 \(q(\cdot \mid c)\) 之间的对数密度比。将 \(D^\star(x, c)\) 代回 式 16.6.1,即得期望条件 Jensen–Shannon 散度:
\[ \begin{aligned} \max_D V(D) &= \mathbb{E}_{c \sim p(c)}\Big[\, 2\, \mathrm{JS}\big(p(\cdot \mid c),\, q(\cdot \mid c)\big) \Big] - 2 \log 2 . \end{aligned} \tag{16.6.3}\]
它在全局最小值 \(-2\log 2\) 处取等,当且仅当对所有满足 \(p(c) > 0\) 的条件 \(c\) 均有 \(q(\cdot \mid c) = p(\cdot \mid c)\)。
16.6.1.2 条件匹配与边缘匹配
匹配每一个条件切片 \(q(\cdot \mid c) = p(\cdot \mid c)\) 严格强于匹配边缘图像分布 \(q(x) = p(x)\)。例如,假设一个 CIFAR-10 生成器产出逼真图像,却将所有类别标签循环错位(\(q(\cdot \mid c) = p(\cdot \mid c + 1)\))。由于 10 个类别具有相同的先验概率 \(p(c) = 1/10\),其边缘图像分布 \(q(x)\) 与 \(p(x)\) 完全一致,在无条件散度上达到最小值 \(\mathrm{JS}(p(x), q(x)) = 0\)。然而在条件目标 式 16.6.3 中,每个切片都与错配类别比较(\(\mathrm{JS}(p(\cdot \mid c), p(\cdot \mid c+1)) \approx \log 2\)),从而产生接近最大的条件散度(练习 1)。
反之要注意,在 式 16.6.3 中每个条件 \(c\) 按其先验频率 \(p(c)\) 加权:概率为 \(p(c) = \epsilon\) 的罕见条件对目标的贡献至多为 \(2\epsilon \log 2\),因此不均衡数据集通常需要类别均衡采样,以防生成器忽略罕见类别。
16.6.2 条件化架构
16.6.2.1 三种条件注入机制
图 16.6.1 展示了将条件 \(c\) 注入生成器或判别器的三种主要方式:
- 拼接 (Mirza 和 Osindero 2014年):将 \(c\) 嵌入为向量 \(e_c\) 并与潜在向量 \(z\) 拼接(或广播后与空间特征图拼接)。
- 特征调制:用关于 \(c\) 的可学习函数对中间特征图 \(h\) 的每个通道做缩放和平移:\(a(c) \odot h + b(c)\)。当 \(h\) 先经归一化时,这就是条件批量归一化 (Vries 等 2017年; Brock 等 2019年)(或 AdaIN / FiLM),可在生成器的每个分辨率上注入条件。
- 投影判别器头 (Miyato 和 Koyama 2018年):计算类别嵌入 \(e_c\) 与判别器汇聚特征向量 \(\phi(x)\) 的内积,再加上一个无条件打分 \(\psi_0(x)\)。
下面我们实现 Modulate,其逐类缩放与平移嵌入表初始化为 \(a(c) = 1\) 与 \(b(c) = 0\)(恒等映射),并验证针对类别 3 的一次梯度更新只修改嵌入表的第 3 行。
class Modulate(nnx.Module):
"""Scale and shift each channel of h by a(c) and b(c), one row per class."""
def __init__(self, num_classes, channels, *, rngs):
# a(c) = 1, b(c) = 0: the identity
self.a = nnx.Embed(num_classes, channels, rngs=rngs,
embedding_init=nnx.initializers.ones)
self.b = nnx.Embed(num_classes, channels, rngs=rngs,
embedding_init=nnx.initializers.zeros)
def __call__(self, h, c):
return self.a(c)[:, None, None, :] * h + self.b(c)[:, None, None, :]在运行该层之前,我们可以先做出两项预测:初始化时无论输入何种类别,输出必等于输入;而仅请求类别 3(下方 CIFAR-10 顺序中的猫)的小批量执行一步梯度更新后,必且只改变每张表的第 3 行,因为嵌入查表只将梯度传回被读取的行。该检验向玩具目标 \(2h + 1\) 执行这样的一步更新。
torch.manual_seed(0)
mod = Modulate(10, 8)
h = torch.randn(10, 8, 4, 4) # one feature map per class
with torch.no_grad():
print('at initialization: max |out - h| =',
float((mod(h, torch.arange(10)) - h).abs().max()))
a0, b0 = mod.a.weight.detach().clone(), mod.b.weight.detach().clone()
c3 = torch.full((10,), 3) # a batch that requests class 3 only
loss = ((mod(h, c3) - (2 * h + 1)) ** 2).mean()
loss.backward()
torch.optim.SGD(mod.parameters(), lr=0.1).step()
rows = lambda w, w0: (w != w0).any(1).nonzero().flatten().tolist()
print('after one step on class 3: rows changed in a', rows(mod.a.weight, a0),
'and in b', rows(mod.b.weight, b0))at initialization: max |out - h| = 0.0
after one step on class 3: rows changed in a [3] and in b [3]
mod = Modulate(10, 8, rngs=nnx.Rngs(0))
h = jax.random.normal(jax.random.key(0), (10, 4, 4, 8)) # one map per class
print('at initialization: max |out - h| =',
float(jnp.abs(mod(h, jnp.arange(10)) - h).max()))
a0, b0 = mod.a.embedding[...], mod.b.embedding[...]
c3 = jnp.full(10, 3) # a batch that requests class 3 only
grads = nnx.grad(lambda m: ((m(h, c3) - (2 * h + 1)) ** 2).mean())(mod)
nnx.Optimizer(mod, optax.sgd(0.1), wrt=nnx.Param).update(mod, grads)
rows = lambda w, w0: np.nonzero(np.any(w != w0, axis=1))[0].tolist()
print('after one step on class 3: rows changed in a',
rows(mod.a.embedding[...], a0), 'and in b',
rows(mod.b.embedding[...], b0))at initialization: max |out - h| = 0.0
after one step on class 3: rows changed in a [3] and in b [3]
16.6.2.2 用贝叶斯法则推导投影头
对 式 16.6.2 的分子与分母应用贝叶斯法则 \(p(x \mid c) = p(c \mid x)p(x)/p(c)\)(利用共享先验 \(p(c)\)),可将最优条件评判器分解为两项:
\[ \log \frac{p(x \mid c)}{q(x \mid c)} \;=\; \log \frac{p(c \mid x)}{q(c \mid x)} + \log \frac{p(x)}{q(x)} . \tag{16.6.4}\]
第一项度量类别一致性(\(x\) 处真实与生成类别后验的对数比),第二项度量无条件样本逼真度。若将两个类别后验均建模为共享特征表示 \(\phi(x)\) 上的 softmax 分类器,即 \(p(c \mid x) \propto \exp(u_c^\top \phi(x))\) 与 \(q(c \mid x) \propto \exp(w_c^\top \phi(x))\),则它们的对数比为 \((u_c - w_c)^\top \phi(x)\) 加上一个与 \(c\) 无关的对数配分函数之差。将该对数配分差与 \(\log(p(x)/q(x))\) 合并为单个标量头 \(\psi_0(x)\),并令 \(e_c = u_c - w_c\),即得 Miyato 和 Koyama (2018年) 的投影判别器(练习 2;与练习 6 中的辅助分类器 GAN 对比):
\[ D(x, c) \;=\; e_c^\top \phi(x) + \psi_0(x). \tag{16.6.5}\]
16.6.3 CIFAR-10 上的类别条件生成
现在我们在 CIFAR-10 的 50,000 张带标签 \(32 \times 32\) 训练图像(每类 5,000 张,通过 d2l.load_cifar10_arrays 加载)上训练一个类别条件生成器。
classes = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
device = d2l.try_gpu()
train_X, train_y, test_X, test_y = d2l.load_cifar10_arrays()
first = [int((train_y == c).nonzero()[0]) for c in range(10)]
d2l.show_images(train_X[first].cpu().permute(0, 2, 3, 1) / 2 + 0.5,
num_rows=2, num_cols=5, titles=classes);
classes = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
train_X, train_y, test_X, test_y = d2l.load_cifar10_arrays()
first = [int(np.nonzero(np.asarray(train_y) == c)[0][0]) for c in range(10)]
d2l.show_images(np.asarray(train_X[np.array(first)]) / 2 + 0.5,
num_rows=2, num_cols=5, titles=classes);
16.6.3.1 条件生成器与投影评判器
我们在 \(32 \times 32\) 分辨率上扩展 16.5 节 中的 d2l.Generator 与 d2l.Discriminator:
CondGenerator将 64 维单位方差类别嵌入广播至 \(4 \times 4 \times 64\),送入生成器的extra输入槽(练习 4 将这种输入拼接与逐块Modulate层作对比)。ProjectionCritic对 \(4 \times 4\) 特征图self.phi(x)作空间求和得到 \(\phi(x)\),并计算 \(e_c^\top \phi(x) + \psi_0(\phi(x))\)(式 16.6.5),同时将 \(e_c = 0\) 初始化,使评判器从无条件判别器起步。
class CondGenerator(d2l.Generator):
"""The backbone generator with a class embedding as extra 4x4 maps."""
def __init__(self, latent_dim, resolution, base_ch, embed_dim=64,
num_classes=10):
super().__init__(latent_dim, resolution, base_ch, extra_ch=embed_dim)
self.embed = nn.Embedding(num_classes, embed_dim) # unit variance
def forward(self, z, y):
ec = self.embed(y)[:, :, None, None].expand(-1, -1, 4, 4)
return super().forward(z, ec)class CondGenerator(d2l.Generator):
"""The backbone generator with a class embedding as extra 4x4 maps."""
def __init__(self, latent_dim, resolution, base_ch, embed_dim=64,
num_classes=10, *, rngs):
super().__init__(latent_dim, resolution, base_ch, extra_ch=embed_dim,
rngs=rngs)
self.embed = nnx.Embed(num_classes, embed_dim, rngs=rngs,
embedding_init=nnx.initializers.normal(1.0))
def __call__(self, z, y):
e = self.embed(y)[:, None, None, :]
ec = jnp.broadcast_to(e, (z.shape[0], 4, 4, e.shape[-1]))
return super().__call__(z, ec)nnx.Embed 的默认初始化器按嵌入宽度平方根的倒数(此处为八分之一)设定标准差,因此代码中显式要求单位方差。
ProjectionCritic 实现了 式 16.6.5。基类的 phi 返回混合卷积后的 \(4 \times 4\) 特征图;在空间位置上对其求和即得 \(\phi(x)\)。作用在 \(\phi(x)\) 上的线性头给出 \(\psi_0(x)\),取代原来读取展平特征图的基类头,而嵌入表为每个类别保存一个向量 \(e_c\)。嵌入表初始化为零,因此评判器从无条件评判器起步,再从数据中学习标签项。
class ProjectionCritic(d2l.Discriminator):
"""The backbone critic with a projection head: e_c . phi(x) + psi_0(x)."""
def __init__(self, resolution, base_ch, num_classes=10):
super().__init__(resolution, base_ch)
width = self.mix.out_channels
self.head = nn.Linear(width, 1) # psi_0 on the pooled features
d2l.fan_in_init(self.head)
self.embed = nn.Embedding(num_classes, width)
nn.init.zeros_(self.embed.weight) # start as an unconditional critic
def forward(self, x, y):
phi = self.phi(x).sum(dim=(2, 3)) # sum over the 4x4 positions
return (self.embed(y) * phi).sum(dim=1) + self.head(phi).squeeze(-1)
net_G, net_D = CondGenerator(100, 32, 256), ProjectionCritic(32, 64)
print(net_G(torch.zeros(2, 100), torch.zeros(2, dtype=torch.long)).shape)
print(net_D(torch.zeros(2, 3, 32, 32),
torch.zeros(2, dtype=torch.long)).shape)torch.Size([2, 3, 32, 32])
torch.Size([2])
class ProjectionCritic(d2l.Discriminator):
"""The backbone critic with a projection head: e_c . phi(x) + psi_0(x)."""
def __init__(self, resolution, base_ch, num_classes=10, *, rngs):
super().__init__(resolution, base_ch, rngs=rngs)
width = self.mix.out_features
self.head = nnx.Linear(width, 1, kernel_init=d2l.fan_in_init,
rngs=rngs) # psi_0 on the pooled features
self.embed = nnx.Embed(num_classes, width, rngs=rngs,
embedding_init=nnx.initializers.zeros)
def __call__(self, x, y):
phi = self.phi(x).sum(axis=(1, 2)) # sum over the 4x4 positions
return (self.embed(y) * phi).sum(axis=1) + self.head(phi).squeeze(-1)
net_G = CondGenerator(100, 32, 256, rngs=nnx.Rngs(0))
net_D = ProjectionCritic(32, 64, rngs=nnx.Rngs(0))
print(net_G(jnp.zeros((2, 100)), jnp.zeros(2, dtype=jnp.int32)).shape)
print(net_D(jnp.zeros((2, 32, 32, 3)), jnp.zeros(2, dtype=jnp.int32)).shape)(2, 32, 32, 3)
(2,)
16.6.3.2 同类配对训练
我们使用 d2l.train_r3gan(16.5 节)以批量大小 128、梯度惩罚权重 \(\gamma = 0.5\) 训练 15,000 步。在每个小批量中,生成图像以真实小批量的准确类别标签 \(y\) 为条件,因此相对配对损失 \(\log \sigma(D(x, c) - D(x', c))\) 始终比较同一类别 \(c\) 的真实图像与生成图像。注意,由于比较完全在类内进行,\(D(x, c)\) 对每个类别各自独立的加性常数 \(\zeta_c\) 保持平移不变(练习 3);在 512 个测试样本对上记录的留出成对排序准确率 \(\hat P(D(x, c) > D(x', c))\) 对这些逐类平移不变。
torch.manual_seed(0) # the initialization
net_G = CondGenerator(100, 32, 256).to(device)
net_D = ProjectionCritic(32, 64).to(device)
gamma = 0.5
ema_G, history = d2l.train_r3gan(
net_G, net_D, d2l.rpgan_loss_D, d2l.rpgan_loss_G, gamma, 15000, train_X,
train_y, eval_images=test_X, eval_labels=test_y, eval_size=512,
batch_size=128, seed=1)rngs = nnx.Rngs(0) # the initialization
net_G = CondGenerator(100, 32, 256, rngs=rngs)
net_D = ProjectionCritic(32, 64, rngs=rngs)
gamma = 0.5
ema_G, history = d2l.train_r3gan(
net_G, net_D, d2l.rpgan_loss_D, d2l.rpgan_loss_G, gamma, 15000, train_X,
train_y, eval_images=test_X, eval_labels=test_y, eval_size=512,
batch_size=128, seed=1)我们对最后 5,000 步的日志取平均,同时统计前 2,000 步的配对准确率均值。
loss_D, loss_G, pen, acc = (np.mean(v[-5000 // 250:]) for v in (
history['loss_D'], history['loss_G'], history['R1'] + history['R2'],
history['accuracy']))
acc_early = history['accuracy'][history['step'] <= 2000].mean()
print(f'last 5,000 steps: critic loss {loss_D:.2f} (+ penalty '
f'{gamma / 2 * pen:.3f}), generator loss {loss_G:.2f}, '
f'pair accuracy {acc:.2f}')
print(f'first 2,000 steps: pair accuracy {acc_early:.2f}')last 5,000 steps: critic loss 0.52 (+ penalty 0.062), generator loss 1.05, pair accuracy 0.79
first 2,000 steps: pair accuracy 0.83
loss_D, loss_G, pen, acc = (np.mean(v[-5000 // 250:]) for v in (
history['loss_D'], history['loss_G'], history['R1'] + history['R2'],
history['accuracy']))
acc_early = history['accuracy'][history['step'] <= 2000].mean()
print(f'last 5,000 steps: critic loss {loss_D:.2f} (+ penalty '
f'{gamma / 2 * pen:.3f}), generator loss {loss_G:.2f}, '
f'pair accuracy {acc:.2f}')
print(f'first 2,000 steps: pair accuracy {acc_early:.2f}')last 5,000 steps: critic loss 0.52 (+ penalty 0.064), generator loss 1.09, pair accuracy 0.81
first 2,000 steps: pair accuracy 0.92
绘制全部 15,000 步中 loss_D、loss_G 与留出 accuracy 的完整轨迹,可以看到投影评判器与条件生成器迅速进入稳态博弈:
steps = history['step']
fig, axes = d2l.plt.subplots(1, 2, figsize=(9, 3.2))
d2l.plot(steps, [history['loss_D'], history['loss_G'],
np.full_like(steps, np.log(2))], 'step', 'loss',
legend=['critic (pairing part)', 'generator', 'log 2'],
fmts=('-', '--', 'k:'), yscale='log', axes=axes[0])
d2l.plot(steps, [history['accuracy'], np.full_like(steps, 0.5)], 'step',
'held-out pair accuracy', ylim=[0.3, 1], fmts=('-', 'k:'),
axes=axes[1]);steps = history['step']
fig, axes = d2l.plt.subplots(1, 2, figsize=(9, 3.2))
d2l.plot(steps, [history['loss_D'], history['loss_G'],
np.full_like(steps, np.log(2))], 'step', 'loss',
legend=['critic (pairing part)', 'generator', 'log 2'],
fmts=('-', '--', 'k:'), yscale='log', axes=axes[0])
d2l.plot(steps, [history['accuracy'], np.full_like(steps, 0.5)], 'step',
'held-out pair accuracy', ylim=[0.3, 1], fmts=('-', 'k:'),
axes=axes[1]);经历短暂初期过渡后,评判器配对损失稳定在 \(0.52\) 附近(低于 \(\log 2 \approx 0.69\)),留出同类成对排序准确率稳定在 \(0.80\) 左右。
16.6.3.3 类别条件样本
下面我们从 ema_G 为 CIFAR-10 的 10 个类别各生成 9 张样本。
torch.manual_seed(42)
z = torch.randn(90, 100, device=device)
y = torch.arange(10, device=device).repeat_interleave(9) # nine per class
with torch.no_grad():
imgs = ema_G(z, y)
panels = [d2l.tile_images(imgs[9 * c:9 * (c + 1)], 3) for c in range(10)]
d2l.show_images(panels, 2, 5, titles=classes, scale=2);z = jax.random.normal(jax.random.key(42), (90, 100))
y = jnp.repeat(jnp.arange(10), 9) # nine per class
imgs = ema_G(z, y)
panels = [d2l.tile_images(imgs[9 * c:9 * (c + 1)], 3) for c in range(10)]
d2l.show_images(panels, 2, 5, titles=classes, scale=2);每个 \(3 \times 3\) 面板都呈现出所请求类别的视觉特征(例如飞机与轮船的蓝天与水面、青蛙与鹿的绿色植被、汽车与卡车的道路背景),同时在 9 次潜在抽样中展现出多样的姿态与色彩。
16.6.4 评估条件生成器
条件生成器可能沿三个不同轴失效:
- 类别错误(条件一致性差),
- 图像不逼真(样本保真度差),或
- 缺乏类内多样性(各类内部的模式遗漏)。
如 表 16.6.1 所汇总,没有任何单一指标能够捕获全部三种失效模式。因此,我们将裁判分类器(度量类别一致性)与边缘特征距离(FD 与 \(\mathrm{MMD}^2\))以及逐类 \(K\)-NN 精确率和召回率结合起来。
| 失效模式 | 类别一致性 | 边缘 FD、\(\mathrm{MMD}^2\) | 逐类精确率 | 逐类召回率 |
|---|---|---|---|---|
| 类别错误 | 可检测 | 失明 | 可检测 | 可检测 |
| 图像保真度差 | 部分敏感 | 可检测 | 可检测 | 部分敏感 |
| 类内多样性低 | 失明(甚至奖励) | 可检测 | 失明(甚至奖励) | 可检测 |
16.6.4.1 裁判分类器与类别一致性
我们训练三块 CIFAR-10 分类器 d2l.FeatureCNN(16.5 节)15 轮作为独立裁判(测试准确率 \(\sim 78\%\)),并同时使用其类别预测与 128 维倒数第二层特征。
torch.manual_seed(0)
cnn = d2l.FeatureCNN(resolution=32).to(device)
d2l.train_feature_cnn(cnn, train_X, train_y, shift=4)
pred = d2l.batched(cnn, test_X).argmax(1)
cls_acc = [float((pred[test_y == c] == c).float().mean())
for c in range(10)]
print(f'CIFAR-10 test accuracy: {float((pred == test_y).float().mean()):.3f}')CIFAR-10 test accuracy: 0.779
cnn = d2l.FeatureCNN(resolution=32, rngs=nnx.Rngs(1))
d2l.train_feature_cnn(cnn, train_X, train_y, shift=4)
pred = d2l.batched(cnn, test_X).argmax(1)
cls_acc = [float((pred[test_y == c] == c).mean()) for c in range(10)]
print(f'CIFAR-10 test accuracy: {float((pred == test_y).mean()):.3f}')CIFAR-10 test accuracy: 0.780
我们从 ema_G 为每个类别生成 500 张图像,并将裁判在生成图像上的分类准确率(一致性)与它在各类真实测试图像上的准确率作对比。
def generate(seed, n=500):
"""n images of each class from the EMA generator, in class order."""
torch.manual_seed(seed)
z = torch.randn(10 * n, 100, device=device)
y = torch.arange(10, device=device).repeat_interleave(n)
with torch.no_grad():
return torch.cat([ema_G(z_k, y_k) for z_k, y_k in
zip(z.split(1000), y.split(1000))])
raw = generate(7)
gen = raw.clamp(-1, 1)
yg = np.repeat(np.arange(10), 500) # the requested classes
pred_gen = d2l.batched(cnn, gen).argmax(1).cpu().numpy()
align = [float((pred_gen[yg == c] == c).mean()) for c in range(10)]def generate(seed, n=500):
"""n images of each class from the EMA generator, in class order."""
z = jax.random.normal(jax.random.key(seed), (10 * n, 100))
y = jnp.repeat(jnp.arange(10), n)
return jnp.concatenate([ema_G(z[i:i + 1000], y[i:i + 1000])
for i in range(0, 10 * n, 1000)])
raw = generate(7)
gen = jnp.clip(raw, -1, 1)
yg = np.repeat(np.arange(10), 500) # the requested classes
pred_gen = np.asarray(d2l.batched(cnn, gen).argmax(1))
align = [float((pred_gen[yg == c] == c).mean()) for c in range(10)]将全部 10 个类别的 align 与裁判在真实测试图像上的准确率 cls_acc 并列制表,即可看出 ema_G 遵从所请求类别标签的程度:
print(f'{"class":12s}{"alignment":>11s}{"real":>7s}{"gap":>7s}')
for name, a, r in zip(classes + ['mean'], align + [np.mean(align)],
cls_acc + [np.mean(cls_acc)]):
print(f'{name:12s}{a:11.2f}{r:7.2f}{a - r:+7.2f}')class alignment real gap
airplane 0.80 0.78 +0.01
automobile 0.82 0.91 -0.09
bird 0.66 0.67 -0.01
cat 0.54 0.57 -0.03
deer 0.66 0.71 -0.05
dog 0.69 0.76 -0.06
frog 0.78 0.85 -0.07
horse 0.76 0.80 -0.05
ship 0.86 0.87 -0.01
truck 0.79 0.87 -0.08
mean 0.74 0.78 -0.04
print(f'{"class":12s}{"alignment":>11s}{"real":>7s}{"gap":>7s}')
for name, a, r in zip(classes + ['mean'], align + [np.mean(align)],
cls_acc + [np.mean(cls_acc)]):
print(f'{name:12s}{a:11.2f}{r:7.2f}{a - r:+7.2f}')class alignment real gap
airplane 0.76 0.79 -0.02
automobile 0.80 0.92 -0.12
bird 0.66 0.64 +0.01
cat 0.51 0.58 -0.07
deer 0.66 0.72 -0.06
dog 0.62 0.75 -0.13
frog 0.81 0.85 -0.05
horse 0.71 0.80 -0.10
ship 0.89 0.89 +0.00
truck 0.80 0.86 -0.06
mean 0.72 0.78 -0.06
10 个类别的平均类别一致性为 \(0.72\text{--}0.74\),仅比裁判在真实 CIFAR-10 测试图像上的准确率(\(0.78\))低 \(4\text{--}6\) 个百分点。
16.6.4.2 保真度与类内多样性
接下来,我们将每类 1,000 张测试图像划分为 500 张参考集(f_real)与 500 张真实下限集(f_real2),计算边缘 FD 与 \(\mathrm{MMD}^2\)(d2l.fid_score、d2l.kid_score)以及逐类 \(K\)-NN 精确率与召回率(d2l.precision_recall,\(K = 3\))。
features = lambda imgs: d2l.batched(cnn.features, imgs).cpu().numpy()
out_of_range = float((raw.abs() > 1).float().mean())
idx = test_y.argsort(stable=True).reshape(10, 1000) # row c: class c
f_real = features(test_X[idx[:, :500].flatten()]) # the reference
f_real2 = features(test_X[idx[:, 500:].flatten()]) # the floor
f_gen = features(gen)
f_gen2 = features(generate(8).clamp(-1, 1)) # a second draw
idx, pred_real = idx.cpu().numpy(), pred.cpu().numpy()features = lambda imgs: np.asarray(d2l.batched(cnn.features, imgs))
out_of_range = float((jnp.abs(raw) > 1).mean())
idx = jnp.argsort(test_y, stable=True).reshape(10, 1000) # row c: class c
f_real = features(test_X[idx[:, :500].flatten()]) # the reference
f_real2 = features(test_X[idx[:, 500:].flatten()]) # the floor
f_gen = features(gen)
f_gen2 = features(jnp.clip(generate(8), -1, 1)) # a second draw
idx, pred_real = np.asarray(idx), np.asarray(pred)现在我们对照参考集 f_real,比较真实测试下限 f_real2 与两组生成抽样(f_gen、f_gen2)的边缘特征距离(d2l.fid_score)和平方 MMD(d2l.kid_score),并检查原始像素值的越界比例 out_of_range:
draws = {'real (the floor)': f_real2, 'generated': f_gen,
'generated, second draw': f_gen2}
print(f'{"against the reference":24s}{"FD (CIFAR-CNN)":>16s}'
f'{"MMD^2 (CIFAR-CNN)":>19s}')
for name, f in draws.items():
print(f'{name:24s}{d2l.fid_score(f, f_real):16.2f}'
f'{d2l.kid_score(f, f_real):19.3f}')
print(f'generated values outside [-1, 1]: {out_of_range:.3f}')against the reference FD (CIFAR-CNN) MMD^2 (CIFAR-CNN)
real (the floor) 0.15 -0.001
generated 1.60 0.105
generated, second draw 1.65 0.108
generated values outside [-1, 1]: 0.010
draws = {'real (the floor)': f_real2, 'generated': f_gen,
'generated, second draw': f_gen2}
print(f'{"against the reference":24s}{"FD (CIFAR-CNN)":>16s}'
f'{"MMD^2 (CIFAR-CNN)":>19s}')
for name, f in draws.items():
print(f'{name:24s}{d2l.fid_score(f, f_real):16.2f}'
f'{d2l.kid_score(f, f_real):19.3f}')
print(f'generated values outside [-1, 1]: {out_of_range:.3f}')against the reference FD (CIFAR-CNN) MMD^2 (CIFAR-CNN)
real (the floor) 0.14 -0.001
generated 1.74 0.114
generated, second draw 1.66 0.109
generated values outside [-1, 1]: 0.008
在 FD 上,生成集距参考集的距离是下限基准的十到十二倍,而第二组抽样仅使 FD 变动不到十分之一,说明该距离归因于生成器本身而非抽样波动。在 \(\mathrm{MMD}^2\) 上,下限基准在噪声范围内为零,生成集约为 0.11。截断前约百分之一的原始值落在 \([-1, 1]\) 之外,因此截断改动的像素极少、并未掩盖问题。
单一距离将所有差异折叠为一个数,而逐类精确率与召回率则分离两种差异:不像该类任何真实图像的生成图像,以及不像任何生成图像的真实图像。以每个特征向量为球心,作触及其在自身集合中第三近邻的球(16.5.4.3 节)。精确率是落入类 \(c\) 某个真实球内的类 \(c\) 生成图像比例,召回率则是落入某个生成球内的类 \(c\) 真实图像比例。下方代码对照参考集为每个类别计算这两项指标,打印跨类均值与最差类别,最后报告类内特征方差(即每个类内特征方差在所有特征与类别上的均值)。
by_class = lambda f: np.asarray(f).reshape(10, -1, f.shape[-1])
def pr_by_class(f):
"""Precision and recall of each class of f against the reference."""
return np.array([d2l.precision_recall(r, g) for r, g in
zip(by_class(f_real), by_class(f))])
print(f'{"per class, k = 3":24s}{"precision":>10s}{"worst class":>17s}'
f'{"recall":>8s}{"worst class":>17s}')
for name, f in draws.items():
pr = pr_by_class(f)
lo = pr.argmin(0)
print(f'{name:24s}{pr[:, 0].mean():10.2f}{classes[lo[0]]:>12s}'
f'{pr[lo[0], 0]:5.2f}{pr[:, 1].mean():8.2f}'
f'{classes[lo[1]]:>12s}{pr[lo[1], 1]:5.2f}')
# Variance within each class, averaged over features and classes
cvar = lambda f: float(by_class(f).astype(np.float64).var(1).mean())
print(f'within-class feature variance: generated {cvar(f_gen):.3f}, '
f'real {cvar(f_real):.3f}, the floor {cvar(f_real2):.3f}')per class, k = 3 precision worst class recall worst class
real (the floor) 0.85 truck 0.77 0.84 bird 0.80
generated 0.90 truck 0.85 0.59 horse 0.52
generated, second draw 0.90 truck 0.84 0.59 truck 0.53
within-class feature variance: generated 0.174, real 0.217, the floor 0.212
by_class = lambda f: np.asarray(f).reshape(10, -1, f.shape[-1])
def pr_by_class(f):
"""Precision and recall of each class of f against the reference."""
return np.array([d2l.precision_recall(r, g) for r, g in
zip(by_class(f_real), by_class(f))])
print(f'{"per class, k = 3":24s}{"precision":>10s}{"worst class":>17s}'
f'{"recall":>8s}{"worst class":>17s}')
for name, f in draws.items():
pr = pr_by_class(f)
lo = pr.argmin(0)
print(f'{name:24s}{pr[:, 0].mean():10.2f}{classes[lo[0]]:>12s}'
f'{pr[lo[0], 0]:5.2f}{pr[:, 1].mean():8.2f}'
f'{classes[lo[1]]:>12s}{pr[lo[1], 1]:5.2f}')
# Variance within each class, averaged over features and classes
cvar = lambda f: float(by_class(f).astype(np.float64).var(1).mean())
print(f'within-class feature variance: generated {cvar(f_gen):.3f}, '
f'real {cvar(f_real):.3f}, the floor {cvar(f_real2):.3f}')per class, k = 3 precision worst class recall worst class
real (the floor) 0.85 truck 0.80 0.82 airplane 0.80
generated 0.90 truck 0.87 0.57 automobile 0.46
generated, second draw 0.91 truck 0.86 0.57 automobile 0.46
within-class feature variance: generated 0.170, real 0.213, the floor 0.207
生成图像的逐类精确率(\(0.90\))实际上高于真实下限(\(0.85\)),说明生成特征稳稳落在真实类簇内部;然而逐类召回率显著偏低(\(0.58\) 对比 \(0.83\),伴随约 20% 更低的类内特征方差),表明生成器集中在各类模式附近,而非覆盖其全部多样性。
16.6.4.3 质心原型基线
为说明高一致性与高精确率如何掩盖多样性缺失,我们构造一个原型基线:从每类真实下限图像中选出特征最接近类质心的 100 张图像,并与每类 100 张随机真实下限图像及 100 张生成图像对比。
floor = by_class(f_real2) # test images 500-999 of each class
dist = ((floor - floor.mean(1, keepdims=True)) ** 2).sum(-1)
near = np.argsort(dist, axis=1)[:, :100] # 100 distinct images per class
rows = np.arange(10)[:, None]
sets = { # 100 images per class: features and the referee's predictions
'real, random': (floor[:, :100], pred_real[idx[:, 500:600]]),
'real, nearest centroid': (floor[rows, near],
pred_real[idx[:, 500:][rows, near]]),
'generated': (by_class(f_gen)[:, :100],
pred_gen.reshape(10, 500)[:, :100])}
print(f'{"100 per class":24s}{"alignment":>10s}{"FD":>7s}{"MMD^2":>8s}'
f'{"precision":>10s}{"recall":>8s}')
for name, (f, p) in sets.items():
f = f.reshape(1000, -1)
prec, rec = pr_by_class(f).mean(0)
print(f'{name:24s}{(p == rows).mean():10.2f}'
f'{d2l.fid_score(f, f_real):7.2f}{d2l.kid_score(f, f_real):8.3f}'
f'{prec:10.2f}{rec:8.2f}')100 per class alignment FD MMD^2 precision recall
real, random 0.78 0.43 -0.003 0.85 0.85
real, nearest centroid 0.91 3.03 0.123 0.97 0.37
generated 0.74 1.59 0.077 0.89 0.67
floor = by_class(f_real2) # test images 500-999 of each class
dist = ((floor - floor.mean(1, keepdims=True)) ** 2).sum(-1)
near = np.argsort(dist, axis=1)[:, :100] # 100 distinct images per class
rows = np.arange(10)[:, None]
sets = { # 100 images per class: features and the referee's predictions
'real, random': (floor[:, :100], pred_real[idx[:, 500:600]]),
'real, nearest centroid': (floor[rows, near],
pred_real[idx[:, 500:][rows, near]]),
'generated': (by_class(f_gen)[:, :100],
pred_gen.reshape(10, 500)[:, :100])}
print(f'{"100 per class":24s}{"alignment":>10s}{"FD":>7s}{"MMD^2":>8s}'
f'{"precision":>10s}{"recall":>8s}')
for name, (f, p) in sets.items():
f = f.reshape(1000, -1)
prec, rec = pr_by_class(f).mean(0)
print(f'{name:24s}{(p == rows).mean():10.2f}'
f'{d2l.fid_score(f, f_real):7.2f}{d2l.kid_score(f, f_real):8.3f}'
f'{prec:10.2f}{rec:8.2f}')100 per class alignment FD MMD^2 precision recall
real, random 0.79 0.43 -0.002 0.86 0.83
real, nearest centroid 0.90 2.92 0.116 0.97 0.36
generated 0.72 2.02 0.115 0.89 0.65
正如 表 16.6.1 所预测,最近质心原型取得了近乎完美的一致性(约 \(0.9\),高于随机真实图像)与精确率(约 \(0.97\)),却遭受严重退化的召回率(低于 \(0.4\) 对比约 \(0.85\))与更差的 FD(约 \(3\) 对比 \(0.43\)),因为它们的特征协方差被人为收缩了。BigGAN 的截断技巧正是通过将潜在分布 \(z\) 向零截断,刻意以召回率换取更高精确率与一致性(练习 5)。
16.6.5 小结
将生成器 \(G(z, c)\) 与评判器 \(D(x, c)\) 同时以 \(c \sim p(c)\) 为条件,可得到最优切片评判器 \(D^\star(x, c) = \log(p(x \mid c)/q(x \mid c))\),并最小化期望条件散度 \(\mathbb{E}_{c \sim p(c)}[2\,\mathrm{JS}(p(\cdot \mid c), q(\cdot \mid c))] - 2\log 2\)。应用贝叶斯法则可将 \(D^\star(x, c)\) 分解为类别一致性项 \(\log(p(c \mid x)/q(c \mid x))\) 与无条件逼真度项 \(\log(p(x)/q(x))\),从而引出投影判别器头 \(D(x, c) = e_c^\top \phi(x) + \psi_0(x)\) (Miyato 和 Koyama 2018年)。评估条件生成器需要将条件一致性(独立裁判分类器)、样本保真度(逐类精确率)与类内多样性(逐类召回率与特征距离)分离开来。若缺少召回率指标,只产出典型类别原型的生成器便能在坍缩类内多样性的同时获得极高的分类器一致性与精确率。
16.6.6 练习
[code] 密度已知的两个高斯切片。设 \(c \in \{1, 2\}\) 等概率出现,其中 \(p(\cdot \mid 1) = \mathcal{N}(-2, 1)\)、\(p(\cdot \mid 2) = \mathcal{N}(2, 1)\),并假设 \(q(\cdot \mid 1) = \mathcal{N}(0, 1)\) 而 \(q(\cdot \mid 2) = \mathcal{N}(2, 1)\)。
投影判别器头的表达能力。式 16.6.5 的推导假定 \(p(c \mid x)\) 与 \(q(c \mid x)\) 共享同一特征映射 \(\phi(x)\)。
- 若 \(p(c \mid x) \propto \exp(u_c^\top \phi_p(x))\) 与 \(q(c \mid x) \propto \exp(w_c^\top \phi_q(x))\) 使用不同的特征映射,证明所得最优评判器在拼接特征向量 \((\phi_p(x), \phi_q(x))\) 上仍具有投影形式 式 16.6.5。
- 对 \(K\) 个离散类别,证明只要 \(\dim(\phi(x)) \geq K\),任意函数 \(D(x, c)\) 均可写成 \(e_c^\top \phi(x) + \psi_0(x)\) 的形式。
[short-code] 将投影评判器用作分类器。训练好的投影评判器
net_D为每张图像 \(x_i\) 给出十个分数 \(S_{ic} = D(x_i, c)\)。- 利用 式 16.6.4 用 \(p(c \mid x)\) 与 \(q(c \mid x)\) 表示 \(D^\star(x, c) - D^\star(x, c')\)。为何 \(\arg\max_c D^\star(x, c)\) 不同于贝叶斯分类器 \(\arg\max_c p(c \mid x)\)?
- 由于同类配对在 \(D(x, c)\) 中留有任意逐类平移 \(\zeta_c\),用类 \(c\) 生成图像的平均评判器分数估计 \(\hat\zeta_c\),并比较原始 \(\arg\max_c S_{ic}\) 与平移校正后 \(\arg\max_c (S_{ic} - \hat\zeta_c)\) 在
test_X上的分类准确率。 - 为何当 \(q(\cdot \mid c) \to p(\cdot \mid c)\) 时,平移校正后的评判器准确率必然趋近随机猜测(\(1/10\))?
[code] 调制生成器对比输入拼接。● 构建一个条件生成器,通过在每个卷积块后加入
Modulate层(而非输入拼接)注入类别信息。- 在初始化(\(a(c) = 1, b(c) = 0\))时,调制生成器的输出与 \(c\) 无关。追踪第一步生成器更新中,来自投影评判器的关于 \(a(c)\) 与 \(b(c)\) 的非零梯度是如何产生的。
- 用两个随机种子将调制生成器与
CondGenerator各训练 4,000 步,比较它们的平均类别一致性与逐类召回率。
[code] 截断技巧与精确率–召回率权衡。截断技巧 (Brock 等 2019年) 从截断至 \([-\tau, \tau]\) 的标准正态分布采样每个潜在坐标。
- 对 100 维潜在向量与 \(\tau \in \{0.5, 1, 2\}\),计算截断采样下的期望平方范数 \(\mathbb{E}[\|z\|^2]\),并与训练期间的 \(\mathbb{E}[\|z\|^2] = 100\) 作对比。
- 对 \(\tau \in \{0.5, 1, 2, \infty\}\) 在截断采样下评估
ema_G,报告类别一致性、逐类精确率与召回率以及对照f_real的 FD。验证减小 \(\tau\) 会以召回率换取更高的一致性与精确率,使生成器趋向质心原型状态。
改编自 Simon Prince,《Understanding Deep Learning》,习题 15.6。
辅助分类器 GAN(AC-GAN)的偏差。● AC-GAN (Odena 等 2017年) 训练一个辅助分类器 \(C(c \mid x)\),并将交叉熵 \(-\mathbb{E}_{c \sim p(c), x \sim q(\cdot \mid c)}[\log C(c \mid x)]\) 加入生成器损失。
证明该辅助生成器损失等于
\[\mathbb{E}_{x \sim q}\Big[H\big(q(\cdot \mid x)\big) + D_{\textrm{KL}}\big(q(\cdot \mid x) \,\|\, C(\cdot \mid x)\big)\Big].\]
当 \(C(c \mid x) = p(c \mid x)\) 且类别存在重叠(\(H(p(\cdot \mid x)) > 0\))时,解释为何最小化该项会驱使生成器避开数据分布的重叠区域,相比投影判别器(式 16.6.4)降低类内多样性。