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 節 の生成器は無条件(unconditional)である。すなわち、周辺データ分布 \(p(x)\) からランダムにサンプルを抽出するだけで、目的のクラスやテキストプロンプト、入力画像を指定する手段を持たない。最初の GAN 論文の発表から間もなく、Mirza と Osindero (2014年) は条件付け変数(conditioning variable)\(c\) を生成器 \(G(z, c)\) と識別器 \(D(x, c)\) の両方に入力する条件付き GAN(conditional GAN、cGAN)を導入した。
本節では、次の 3 つの問いに取り組む。
- 条件付き定式化はどのような目的関数を最適化し、その最適クリティックは何を推定するのか。
- 条件付け変数 \(c\) を生成器と識別器のアーキテクチャにどのように組み込むべきか。
- 条件付き生成器を、条件アライメント(condition alignment)、サンプル忠実度(sample fidelity)、クラス内多様性(within-class diversity)のそれぞれについて個別に評価するにはどうすればよいか。
これらの概念を具体的に示すため、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 divergence)が得られる。
\[ \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\) に到達するのは、\(q(\cdot \mid c) = p(\cdot \mid c)\) がすべての条件 \(c\)(ただし \(p(c) > 0\))に対して成り立つとき、かつそのときに限る。
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)。
逆に、各条件 \(c\) が事前頻度 \(p(c)\) によって 式 16.6.3 の中で重み付けされていることにも注意が必要である。確率 \(p(c) = \epsilon\) の希少な条件が目的関数に寄与する量は高々 \(2\epsilon \log 2\) であるため、不均衡なデータセットでは、生成器が希少クラスを無視するのを防ぐためにクラス均衡サンプリングが必要になることが多い。
16.6.2 条件付けのアーキテクチャ
16.6.2.1 3 つの条件付け機構
図 16.6.1 に、条件 \(c\) を生成器や識別器に入力する主な 3 つの方法を示す。
- 連結(concatenation)(Mirza と Osindero 2014年) は、\(c\) をベクトル \(e_c\) に埋め込み、潜在ベクトル \(z\) と連結する(あるいは空間特徴マップにブロードキャストして連結する)。
- 特徴変調(feature modulation)は、中間特徴マップ \(h\) の各チャネルを、学習された \(c\) の関数によってスケーリングおよびシフトする(\(a(c) \odot h + b(c)\))。先に \(h\) を正規化する場合、これは条件付きバッチ正規化(conditional batch normalization)(Vries ほか 2017年; Brock ほか 2019年)(あるいは AdaIN や FiLM)となり、生成器のあらゆる解像度で条件を注入する。
- 射影識別器ヘッド(projection discriminator head)(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, :]この層を実行する前に、2 つのことが予測できる。初期化時点では、クラスによらず出力は入力と一致するはずである。また、クラス 3(以下で用いる CIFAR-10 の並び順では猫)のみを指定するバッチで勾配ステップを実行すると、各テーブルの第 3 行だけが変化し、他の行は一切変化しないはずである。埋め込みの参照は、読み出した行にしか勾配を伝播しないからである。以下の確認コードでは、トイ目標値 \(2h + 1\) に向けてそのようなステップを 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 ベイズの定理による射影ヘッドの導出
ベイズの定理 \(p(x \mid c) = p(c \mid x)p(x)/p(c)\) を 式 16.6.2 の分子と分母(共通の事前分布 \(p(c)\) を持つ)に適用すると、最適条件付きクリティックは次の 2 つの項に分解される。
\[ \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}\]
第 1 項はクラスアライメント(class alignment、\(x\) における実データと生成データのクラス事後分布の対数比)を測り、第 2 項は無条件のサンプルリアリズム(unconditional sample realism)を測る。両方のクラス事後分布を、共有の特徴表現 \(\phi(x)\) 上のソフトマックス分類器、すなわち \(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年) の射影識別器(projection discriminator)が得られる(演習問題 2。演習問題 6 の補助分類器 GAN(auxiliary classifier GAN)と比較せよ)。
\[ D(x, c) \;=\; e_c^\top \phi(x) + \psi_0(x). \tag{16.6.5}\]
16.6.3 CIFAR-10 におけるクラス条件付き生成
ここで、ラベル付きの訓練画像 50,000 枚(解像度 \(32 \times 32\))からなる CIFAR-10(クラスあたり 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 条件付き生成器と射影クリティック
d2l.Generator と d2l.Discriminator(16.5 節)を解像度 \(32 \times 32\) に拡張する。
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 のデフォルトの初期化器は、埋め込み幅の平方根の逆数(ここでは 8 分の 1)を標準偏差として要素を抽出するため、コードでは単位分散を明示的に指定している。
ProjectionCritic は 式 16.6.5 を実装したものである。基底クラスの phi は混合畳み込みの後に \(4 \times 4\) の特徴マップを返し、それを空間位置にわたって足し合わせることで \(\phi(x)\) が得られる。\(\phi(x)\) 上の線形ヘッドが \(\psi_0(x)\) を出力して、平坦化したマップを読み取る基底クラスのヘッドを置き換え、さらにテーブルがクラスごとに 1 つの埋め込み \(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 節)を用い、15,000 ステップにわたってバッチサイズ 128、勾配ペナルティの重み \(\gamma = 0.5\) で訓練する。各ミニバッチでは、生成画像が実データのミニバッチとまったく同じクラスラベル \(y\) で条件付けされるため、相対論的ペアリング損失 \(\log \sigma(D(x, c) - D(x', c))\) は常に同一クラス \(c\) の実画像と生成画像を比較する。なお、比較は純粋にクラス内でのみ行われるため、\(D(x, c)\) はクラスごとに独立な加法定数 \(\zeta_c\) の違いを除いてシフト不変である(演習問題 3)。記録されるホールドアウトのペアワイズランキング正解率 \(\hat P(D(x, c) > D(x', c))\)(512 組のテストペアで評価)も、このクラスごとのシフトに対して不変である。
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
loss_D、loss_G、およびホールドアウトの accuracy について全 15,000 ステップにわたる軌跡をプロットすると、射影クリティックと条件付き生成器がいかに速やかに安定したゲームへと落ち着くかがわかる。
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 クラス条件付き生成サンプル
以下では、CIFAR-10 の 10 クラスそれぞれについて 9 枚のサンプルを ema_G から生成する。
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 条件付き生成器の評価
条件付き生成器は、次の 3 つの異なる軸で失敗しうる。
- 誤ったクラス(低い条件アライメント)
- 非現実的な画像(低いサンプル忠実度)
- クラス内多様性の欠如(各クラス内でのモード欠落)
表 16.6.1 にまとめるように、単一の指標でこれら 3 つの失敗モードすべてを捉えることはできない。そこで、クラスアライメントを測るレフェリー分類器(referee classifier)に、周辺特徴距離(FD と \(\mathrm{MMD}^2\))およびクラスごとの \(K\)-NN 適合率(precision)と再現率(recall)を組み合わせる。
| 失敗モード | クラスアライメント | 周辺 FD、\(\mathrm{MMD}^2\) | クラスごとの適合率 | クラスごとの再現率 |
|---|---|---|---|---|
| 誤ったクラス | 検出可 | 検出不可 | 検出可 | 検出可 |
| 低い画像忠実度 | 部分的 | 検出可 | 検出可 | 部分的 |
| 低いクラス内多様性 | 検出不可(高く評価しうる) | 検出可 | 検出不可(高く評価しうる) | 検出可 |
16.6.4.1 レフェリー分類器とクラスアライメント
3 ブロックの CIFAR-10 分類器 d2l.FeatureCNN(16.5 節)を独立したレフェリーとして 15 エポック訓練し(テスト正解率は \(\sim 78\%\) に達する)、そのクラス予測と最終層の 1 つ手前にある 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
クラスあたり 500 枚の画像を ema_G から生成し、生成画像に対するレフェリーの分類正解率(アライメント)を、各クラスの実テスト画像に対する正解率と比較する。
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)]align を実テスト画像に対するレフェリーの正解率 cls_acc と並べて 10 クラスそれぞれについて表にまとめると、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\) と、わずか \(4\text{--}6\) パーセントポイントだけ CIFAR-10 の実テスト画像に対するレフェリーの正解率(\(0.78\))を下回るにすぎない。
16.6.4.2 忠実度とクラス内多様性
次に、クラスあたり 1,000 枚のテスト画像を 500 枚の参照セット(f_real)と 500 枚の実データ下限セット(real floor、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)それでは、周辺特徴距離(d2l.fid_score)と二乗 MMD(d2l.kid_score)を参照セット f_real との間で計算して、実データのテスト下限 f_real2 と 2 回の生成サンプル群(f_gen、f_gen2)を比較し、あわせて範囲外となった生のピクセル値の割合 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 で見ると、生成セットは参照セットから下限セットの 10〜12 倍離れており、2 回目の抽出による FD の変動は 0.1 未満であるため、この距離は抽出の偶然ではなく生成器自体に起因するものである。\(\mathrm{MMD}^2\) では、下限セットがノイズの範囲内で 0 付近にあるのに対し、生成セットは約 0.11 となる。クランプ前の生のピクセル値のうち \([-1, 1]\) の外に出るのは 100 個に 1 個程度であり、クランプによって変化するピクセルはわずかで、問題が隠蔽されることもほとんどない。
これらの距離指標は、あらゆる違いを 1 つの数値に畳み込んでしまう。これに対し、クラスごとの適合率と再現率は 2 種類の違いを切り分ける。すなわち、そのクラスのどの実画像にも似ていない生成画像と、どの生成画像にも似ていない実画像である。各特徴ベクトルの周囲に、同じ集合内で 3 番目に近い近傍点まで届く球を描く(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 重心プロトタイプベースライン
高いアライメントと高い適合率がなぜ多様性の欠如を覆い隠してしまうのかを確認するため、実データ下限セットの中から特徴量がクラスの重心(centroid)に最も近い画像をクラスあたり 100 枚選んでプロトタイプベースライン(prototype baseline)を構築し、ランダムに選んだ実データ下限セットの画像 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 の切断トリック(truncation trick)は、潜在分布 \(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] 既知の密度を持つ 2 つのガウス分布スライス。\(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.3 を 1 次元の数値求積法によって計算せよ。
- 小規模な MLP クリティックを \((x, \text{one\_hot}(c))\) 上で訓練して 式 16.6.1 を最大化し、収束後の目的関数値が (a) と一致することを確認したうえで、両方のスライスについて \(D(x, c)\) を厳密な対数密度比 式 16.6.2 と重ねてプロットせよ。
- 次に、生成器が 2 つのクラスを入れ替えた場合、すなわち \(q(\cdot \mid 1) = \mathcal{N}(2, 1)\) かつ \(q(\cdot \mid 2) = \mathcal{N}(-2, 1)\) の場合を考える。条件付き目的関数値 式 16.6.3 と周辺分布に対する無条件目的関数値(\(c\) を無視した場合)の両方を計算し、訓練によって確認せよ。
射影識別器ヘッドの表現力。式 16.6.5 の導出では、\(\phi(x)\) という共有の特徴マップを \(p(c \mid x)\) と \(q(c \mid 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\) 個の離散クラスに対し、任意の関数 \(D(x, c)\) が \(e_c^\top \phi(x) + \psi_0(x)\) の形式で表せることを、\(\dim(\phi(x)) \geq K\) が成り立つ場合について示せ。
[short-code] 分類器としての射影クリティックの利用。訓練済みの射影クリティック
net_Dは、10 個のスコア \(S_{ic} = D(x_i, c)\) を各画像 \(x_i\) に対して割り当てる。- 式 16.6.4 を用いて、\(D^\star(x, c) - D^\star(x, c')\) を \(p(c \mid x)\) と \(q(c \mid x)\) によって表せ。なぜ \(\arg\max_c D^\star(x, c)\) はベイズ分類器 \(\arg\max_c p(c \mid x)\) と一致しないのか。
- 同一クラスペアリングではクラスごとに任意のシフト \(\zeta_c\) が \(D(x, c)\) に残るため、\(\hat\zeta_c\) をクラス \(c\) の生成画像に対するクリティックスコアの平均として推定し、
test_X上での分類正解率を、補正なしの \(\arg\max_c S_{ic}\) とシフト補正後の \(\arg\max_c (S_{ic} - \hat\zeta_c)\) の間で比較せよ。 - シフト補正後のクリティックの正解率がランダム予測(\(1/10\))へと、\(q(\cdot \mid c) \to p(\cdot \mid c)\) となるにつれて近づかなければならないのはなぜか。
[code] 特徴変調型生成器と入力連結の比較。● クラス情報が入力の連結ではなく、すべての畳み込みブロックの後に置かれた
Modulate層を通じて入力される条件付き生成器を構築せよ。- 初期化時点(\(a(c) = 1, b(c) = 0\))では、変調型生成器の出力は \(c\) に依存しない。最初の生成器ステップにおいて、\(a(c)\) と \(b(c)\) に関する非ゼロの勾配が射影クリティックからどのように生じるかをたどれ。
- 変調型生成器と
CondGeneratorの両方をそれぞれ 2 つのシードで 4,000 ステップ訓練し、平均クラスアライメントとクラスごとの再現率を比較せよ。
[code] 切断トリックと適合率・再現率のトレードオフ。切断トリック (Brock ほか 2019年) は、各潜在座標を \([-\tau, \tau]\) に切断された標準正規分布からサンプリングする。
- 100 次元の潜在ベクトルと \(\tau \in \{0.5, 1, 2\}\) に対し、切断サンプリングのもとでの二乗ノルムの期待値 \(\mathbb{E}[\|z\|^2]\) を計算し、訓練時の \(\mathbb{E}[\|z\|^2] = 100\) と比較せよ。
ema_Gを \(\tau \in \{0.5, 1, 2, \infty\}\) の切断サンプリングのもとで評価し、クラスアライメント、クラスごとの適合率と再現率、および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)と比べてクラス内多様性が損なわれる理由を説明せよ。