16.6  조건부 생성

16.1절 및 16.5절 의 생성자들은 무조건부(unconditional) 생성자였습니다. 즉 원하는 클래스나 텍스트 프롬프트, 입력 이미지를 지정할 방법 없이 주변 데이터 분포 \(p(x)\) 에서 확률 표본만 뽑았습니다. 원조 GAN 논문 직후 Mirza 와/과 Osindero (2014년) 의 연구는 생성자 \(G(z, c)\) 와 판별자 \(D(x, c)\) 양쪽 모두에 조건 변수 \(c\) 를 입력하는 조건부 GAN(conditional GAN, cGAN)을 도입했습니다.

이 절에서는 세 가지 질문을 다룹니다:

  1. 조건부 정식화는 어떤 목적 함수를 최적화하며 최적 크리틱은 무엇을 추정할까요?
  2. 조건 변수 \(c\) 를 생성자와 판별자 아키텍처에 어떻게 통합해야 할까요?
  3. 조건부 생성자를 조건 정렬도, 샘플 충실도, 클래스 내 다양성에 대해 어떻게 각각 분리 평가할 수 있을까요?

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)\) 를 유도합니다. 조건부 로그 손실 목적 함수는 쌍 \((x, c)\) 들에 고전적 이진 로그 손실 정식화(16.1절)를 그대로 적용합니다:

\[ \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 에 대입하면 기대 조건부 젠센–섀넌 발산을 얻습니다:

\[ \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}\]

이 식은 \(p(c) > 0\) 인 모든 조건 \(c\) 에 대해 \(q(\cdot \mid c) = p(\cdot \mid c)\) 일 때 그리고 그때만 전역 최솟값 \(-2\log 2\) 를 달성합니다.

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\) 를 주입하는 세 가지 대표 방식을 보여 줍니다:

  1. 이어붙이기 (Mirza 와/과 Osindero 2014년) 는 \(c\) 를 벡터 \(e_c\) 로 임베딩하여 잠재 벡터 \(z\) 와 이어 붙입니다(또는 공간 특성 맵에 브로드캐스팅해 이어 붙입니다).
  2. 특성 변조(feature modulation)는 학습된 \(c\) 의 함수들을 통해 중간 특성 맵 \(h\) 의 각 채널을 스케일링하고 이동시킵니다: \(a(c) \odot h + b(c)\). \(h\) 를 먼저 정규화하면 생성자의 모든 해상도마다 조건을 주입하는 조건부 배치 정규화 Vries 기타 (2017년); Brock 기타 (2019년)가 됩니다.
  3. 투영 판별자 헤드 (Miyato 와/과 Koyama 2018년) 는 클래스 임베딩 \(e_c\) 와 판별자의 풀링된 특성 벡터 \(\phi(x)\) 의 내적을 구하고 무조건부 점수 \(\psi_0(x)\) 를 더합니다.
그림 16.6.1: GAN을 위한 세 가지 조건화 메커니즘. 왼쪽: 이어붙이기는 입력이나 특성 맵에 임베딩 \(e_c\) 를 덧붙입니다. 가운데: 특성 변조는 조건에 의존하는 채널별 스케일과 이동 \(a(c) \odot h + b(c)\) 를 적용합니다. 오른쪽: 투영 판별자 헤드는 \(e_c^\top \phi(x) + \psi_0(x)\) 를 계산합니다.

아래에서는 \(a(c) = 1\), \(b(c) = 0\)(항등 사상)으로 초기화된 클래스별 스케일·이동 임베딩 테이블을 갖춘 Modulate를 구현하고 클래스 3에 대한 그레이디언트 스텝이 임베딩 테이블의 3번 행만 갱신함을 확인합니다.

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]
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 베이즈 법칙을 통한 투영 헤드 유도

공유 사전 분포 \(p(c)\) 를 가진 식 16.6.2 의 분자와 분모에 베이즈 법칙 \(p(x \mid c) = p(c \mid x)p(x)/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)\) 위의 소프트맥스 분류기 \(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과 비교해 보십시오):

\[ D(x, c) \;=\; e_c^\top \phi(x) + \psi_0(x). \tag{16.6.5}\]

16.6.3 CIFAR-10에서의 클래스 조건부 생성

이제 레이블이 달린 CIFAR-10 \(32 \times 32\) 훈련 이미지 50,000장(클래스당 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\) 해상도에서 d2l.Generator와 d2l.Discriminator(16.5절)를 확장합니다:

  • CondGenerator는 \(4 \times 4 \times 64\) 로 브로드캐스팅한 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의 기본 초기화기는 임베딩 폭 제곱근의 역수(여기서는 1/8)를 표준 편차로 원소를 추출하므로 코드에서 단위 분산을 명시적으로 지정합니다.

ProjectionCritic은 식 16.6.5 의 투영 헤드를 구현합니다. 기반 클래스의 phi는 혼합 합성곱 직후의 \(4 \times 4\) 특성 맵을 반환하며 위치들에 걸쳐 합산하면 \(\phi(x)\) 가 됩니다. \(\phi(x)\) 위의 선형 헤드가 평탄화된 맵을 읽던 기반 헤드를 대신해 \(\psi_0(x)\) 를 내놓고, 임베딩 테이블이 클래스당 하나의 \(e_c\) 를 보관합니다. 테이블이 0에서 시작하므로 크리틱은 무조건부 크리틱으로 출발해 데이터로부터 레이블 항을 학습합니다.

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 동일 클래스 쌍을 이용한 훈련

배치 크기 128과 그레이디언트 페널티 가중치 \(\gamma = 0.5\) 로 d2l.train_r3gan(16.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로부터 10개 CIFAR-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 조건부 생성자 평가하기

조건부 생성자는 세 가지 뚜렷이 구별되는 축을 따라 실패할 수 있습니다:

  1. 잘못된 클래스(낮은 조건 정렬도),
  2. 비현실적인 이미지(낮은 샘플 충실도), 또는
  3. 클래스 내 다양성 부족(각 클래스 내부의 모드 누락).

표 16.6.1 에 요약되어 있듯 단일 지표 하나만으로는 세 가지 실패 양상을 모두 포착할 수 없습니다. 따라서 클래스 정렬도를 재는 심판 분류기(referee classifier)를 주변 특성 거리(FD와 \(\mathrm{MMD}^2\)) 및 클래스별 \(K\)-NN 정밀도·재현율과 결합합니다.

표 16.6.1: 조건부 생성 실패 양상에 대한 평가 지표별 민감도.
실패 양상 클래스 정렬도 주변 FD, \(\mathrm{MMD}^2\) 클래스별 정밀도 클래스별 재현율
잘못된 클래스 감지함 감지 못함 감지함 감지함
낮은 이미지 충실도 부분 감지 감지함 감지함 부분 감지
낮은 클래스 내 다양성 감지 못함(오히려 보상 가능) 감지함 감지 못함(오히려 보상 가능) 감지함

16.6.4.1 심판 분류기와 클래스 정렬도

독립 심판으로 3블록 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장씩을 생성하고 생성 이미지에 대한 심판 분류 정확도(정렬도, alignment)를 각 클래스 실제 테스트 이미지에 대한 심판 정확도와 비교합니다.

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개 클래스 각각에 대해 실제 테스트 이미지 심판 정확도 cls_acc 옆에 align을 표로 나열하면 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 정밀도와 재현율(\(K = 3\) 인 d2l.precision_recall)까지 계산합니다.

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를 0.1 미만으로만 움직이므로 이 거리는 표본 추출 운이 아니라 생성자 자체에서 비롯된 것입니다. \(\mathrm{MMD}^2\) 에서 바닥 기준선은 잡음 범위 내 0에 놓이고 생성 집합은 약 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.85\))보다 생성 이미지(\(0.90\))에서 더 높게 나와 생성 특성들이 실제 클래스 군집 안쪽 깊숙이 놓임을 보여 주는 반면, 클래스별 재현율은 약 20% 더 낮은 클래스 내 특성 분산과 함께 훨씬 낮게(\(0.83\) 대 \(0.58\)) 나와 생성자가 각 클래스의 전체 다양성을 덮는 대신 모드 중심 근처에 집중함을 보여 줍니다.

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.85\) 대 \(0.4\) 미만) FD도 악화됩니다(\(0.43\) 대 약 \(3\)). BigGAN의 절단 트릭(truncation trick)은 잠재 분포 \(z\) 를 0 쪽으로 잘라냄으로써 의도적으로 재현율을 내주고 더 높은 정밀도와 정렬도를 얻습니다(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 연습 문제

  1. [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)\) 이라 합시다.

    1. 1차원 수치 구적법으로 식 16.6.3 의 이론값을 계산하십시오.
    2. 식 16.6.1 의 목적 함수를 최대화하도록 \((x, \text{one\_hot}(c))\) 위에서 작은 MLP 크리틱을 훈련하고 수렴한 목적 함숫값이 (a)번과 일치함을 확인한 뒤 두 단면 모두에 대해 정확한 로그 밀도비 식 16.6.2 대비 \(D(x, c)\) 를 그리십시오.
    3. 이제 생성자가 두 클래스를 맞바꾼다고 가정합시다: \(q(\cdot \mid 1) = \mathcal{N}(2, 1)\), \(q(\cdot \mid 2) = \mathcal{N}(-2, 1)\). 식 16.6.3 의 조건부 가치와 (\(c\) 를 무시한) 주변 무조건부 가치를 둘 다 계산하고 훈련으로 확인하십시오.
  2. 투영 판별자 헤드의 표현력. 식 16.6.5 의 유도에서는 \(p(c \mid x)\) 와 \(q(c \mid x)\) 가 특성 맵 \(\phi(x)\) 를 공유한다고 가정했습니다.

    1. \(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 의 투영 형태를 가짐을 보이십시오.
    2. \(K\) 개의 이산 클래스에 대해 \(\dim(\phi(x)) \geq K\) 이기만 하면 임의의 함수 \(D(x, c)\) 를 \(e_c^\top \phi(x) + \psi_0(x)\) 형태로 쓸 수 있음을 보이십시오.
  3. [short-code] 투영 크리틱을 분류기로 활용하기. 훈련된 투영 크리틱 net_D는 각 이미지 \(x_i\) 에 열 개의 점수 \(S_{ic} = D(x_i, c)\) 를 부여합니다.

    1. 식 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)\) 와 다릅니까?
    2. 동일 클래스 페어링은 \(D(x, c)\) 에 임의의 클래스별 이동 \(\zeta_c\) 를 남기므로 클래스 \(c\) 생성 이미지들의 평균 크리틱 점수로 \(\hat\zeta_c\) 를 추정하고 test_X 위에서 원시 \(\arg\max_c S_{ic}\) 대 이동 보정된 \(\arg\max_c (S_{ic} - \hat\zeta_c)\) 의 분류 정확도를 비교하십시오.
    3. \(q(\cdot \mid c) \to p(\cdot \mid c)\) 일 때 이동 보정 크리틱 정확도가 왜 무작위 추측(\(1/10\))에 다가가야 합니까?
  4. [code] 변조 생성자 대 입력 이어붙이기. ● 입력 이어붙이기 대신 모든 합성곱 블록 뒤 Modulate 층을 통해 클래스 정보가 들어가는 조건부 생성자를 구축하십시오.

    1. 초기화 시점(\(a(c) = 1, b(c) = 0\))에 변조 생성자의 출력은 \(c\) 와 무관합니다. 첫 생성자 스텝에서 투영 크리틱으로부터 \(a(c)\) 와 \(b(c)\) 에 대한 0이 아닌 그레이디언트가 어떻게 생겨나는지 추적하십시오.
    2. 각각 두 시드에 걸쳐 변조 생성자와 CondGenerator를 모두 4,000스텝 동안 훈련하고 평균 클래스 정렬도와 클래스별 재현율을 비교하십시오.
  5. [code] 절단 트릭과 정밀도–재현율 트레이드오프. 절단 트릭 (Brock 기타 2019년) 은 각 잠재 좌표를 \([-\tau, \tau]\) 로 절단한 표준 정규 분포에서 샘플링합니다.

    1. 100차원 잠재 벡터와 \(\tau \in \{0.5, 1, 2\}\) 에 대해 절단 샘플링 아래 기대 제곱 노름 \(\mathbb{E}[\|z\|^2]\) 을 계산하고 훈련 시의 \(\mathbb{E}[\|z\|^2] = 100\) 과 비교하십시오.
    2. \(\tau \in \{0.5, 1, 2, \infty\}\) 에 대해 절단 샘플링 아래 ema_G를 평가하여 f_real 대비 클래스 정렬도, 클래스별 정밀도·재현율, FD를 보고하십시오. \(\tau\) 를 줄이면 재현율을 내주는 대신 정렬도와 정밀도가 높아지며 생성자가 중심 프로토타입 체제 쪽으로 이동함을 확인하십시오.

    Simon Prince, Understanding Deep Learning, Problem 15.6에서 발췌·수정.

  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)]\) 를 더합니다.

    1. 이 보조 생성자 손실이 다음 식과 같음을 보이십시오:

      \[\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].\]

    2. \(C(c \mid x) = p(c \mid x)\) 이고 클래스들이 서로 겹칠 때(\(H(p(\cdot \mid x)) > 0\)), 이 항을 최소화하면 왜 생성자가 데이터 분포의 중첩 영역을 기피하여 투영 판별자(식 16.6.4) 대비 클래스 내 다양성이 줄어드는지 설명하십시오.

토론