본문 바로가기
C.W.K.
Stream
Lesson 04 of 06 · published

GAN 학습 패턴

~8 min · custom-train

Level 0Keras 도제
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

GAN은 단일 손실 구조로 표현할 수 없어

GAN은 최소최대 게임으로 연결된 두 신경망이야. 판별자는 실제 자료와 생성 자료를 구분하도록 배우고, 생성자는 판별자가 가려내기 어려운 가짜를 만들도록 배워. 두 목적은 서로 반대이며 가중치와 옵티마이저도 따로 관리해. 따라서 fit()이 기본으로 가정하는 단일 손실·단일 옵티마이저 구조에는 들어맞지 않고, 배치마다 서로 다른 두 갱신 단계를 순서대로 실행해야 해.

그래도 train_step() 재정의가 알맞은 이유

번갈아 학습한다고 곧바로 수동 루프가 필요한 건 아니야. GAN 객체가 두 하위 모델을 보유하고, 한 train_step() 안에서 첫째 실제·가짜 배치로 판별자를 학습하고, 둘째 판별자를 통과한 신호로 생성자를 학습한 뒤, 두 손실을 반환하면 돼. fit() 안에 남아 있으므로 콜백, 체크포인트, 분산 처리도 그대로 사용할 수 있어. 아래 뼈대는 두 갱신을 _train_discriminator_train_generator라는 보조 메서드로 분리했어. 각 메서드가 자신의 그래디언트 기록 장치와 옵티마이저를 맡아, 코드가 두 모델의 대결 구조처럼 읽히지.

Code

train_step() 재정의로 구현한 GAN·python
class GAN(keras.Model):
    def __init__(self, generator, discriminator, latent_dim):
        super().__init__()
        self.generator = generator
        self.discriminator = discriminator
        self.latent_dim = latent_dim

    def train_step(self, real_images):
        batch_size = keras.ops.shape(real_images)[0]
        noise = keras.random.normal(
            shape=(batch_size, self.latent_dim)
        )

        # Train discriminator on real + fake
        fake_images = self.generator(noise)
        combined = keras.ops.concatenate([real_images, fake_images])
        labels = keras.ops.concatenate([
            keras.ops.ones((batch_size, 1)),
            keras.ops.zeros((batch_size, 1)),
        ])
        d_loss = self._train_discriminator(combined, labels)

        # Train generator to fool the discriminator
        noise = keras.random.normal(shape=(batch_size, self.latent_dim))
        misleading_labels = keras.ops.ones((batch_size, 1))
        g_loss = self._train_generator(noise, misleading_labels)

        return {"d_loss": d_loss, "g_loss": g_loss}

External links

Exercise

MNIST용 작은 DCGAN을 구현해. 생성자는 Dense → reshape → ConvTranspose로, 판별자는 작게 구성하고 train_step()을 재정의해. 5에포크 동안 학습하며 g_loss의 변화와 생성 표본의 질적 개선을 함께 확인해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.