본문 바로가기
C.W.K.
Stream
Lesson 06 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을 train_step() 재정의로 깔끔하게 구현했어. 이번에는 같은 모델을 fit()train_step()도 없이 전체 수동 루프로 작성해. 목적은 fit()이 대신 맡던 책임의 무게를 몸으로 확인하는 거야. 에포크 반복, 그래디언트 기록 장치 두 개, 평가지표 출력, 체크포인트 로직을 직접 쓰면 높은 수준의 학습 API가 주는 가치가 코드 줄 수로 드러나.

수동 GAN 루프의 실제 동작

학습 원리는 같고 담당자만 바뀌어. 각 단계에서 실제 자료와 생성 자료를 섞은 배치로 판별자를 학습한 뒤, 생성자가 판별자를 속이도록 학습해. 두 신경망은 각자의 옵티마이저를 사용해. 아래 뼈대는 두 그래디언트 기록 장치가 만드는 핵심 갱신만 보여 줘. 실제 실행에서는 진행 상황 출력, 주기적인 표본 이미지 저장, 체크포인트까지 직접 둘러야 해. 모두 재정의 버전이 fit()에서 물려받던 기능이야.

  • 판별자는 실제 자료와 생성 자료를 함께 학습해
  • 생성자는 판별자를 속이는 방향으로 학습해
  • 각 신경망은 별도의 옵티마이저를 사용해
  • 두 손실을 모두 관찰해. 건강한 학습에서는 경쟁 속에서 값이 진동하며, 둘 중 하나가 0으로 무너지지 않아

Code

수동 GAN 단계(TensorFlow 백엔드)·python
import tensorflow as tf

for epoch in range(epochs):
    for real_images in dataset:
        batch_size = tf.shape(real_images)[0]
        noise = keras.random.normal((batch_size, latent_dim))

        # --- Discriminator step ---
        fake_images = generator(noise)
        combined = tf.concat([real_images, fake_images], axis=0)
        labels = tf.concat([
            tf.ones((batch_size, 1)),
            tf.zeros((batch_size, 1)),
        ], axis=0)
        with tf.GradientTape() as tape:
            preds = discriminator(combined)
            d_loss = loss_fn(labels, preds)
        d_grads = tape.gradient(d_loss, discriminator.trainable_variables)
        d_opt.apply_gradients(zip(d_grads, discriminator.trainable_variables))

        # --- Generator step (fool the discriminator) ---
        noise = keras.random.normal((batch_size, latent_dim))
        misleading = tf.ones((batch_size, 1))
        with tf.GradientTape() as tape:
            preds = discriminator(generator(noise))
            g_loss = loss_fn(misleading, preds)
        g_grads = tape.gradient(g_loss, generator.trainable_variables)
        g_opt.apply_gradients(zip(g_grads, generator.trainable_variables))

    print(f"epoch {epoch}: d_loss={float(d_loss):.3f} g_loss={float(g_loss):.3f}")

External links

Exercise

4과의 DCGAN을 fit()과 train_step() 없이 전체 수동 학습 루프로 다시 구현해. 기록, 체크포인트, 진행 상황 출력에 사용한 코드 줄 수를 재정의 버전과 비교하고, fit()이 제공하던 기능 중 가장 아쉬웠던 것을 한 문장으로 적어.

Progress

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

댓글 0

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

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