C.W.K.
Stream
Lesson 06 of 06 · published

실전 — Custom GAN training loop

~8 min · custom-train

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

capstone — 한 번은 어렵게 짜보기

GAN 을 깔끔한 train_step() override 로 짠 건 이미 봤어. 이번 lesson 은 같은 모델을 fully manual loop 으로 — fit() 도, train_step() 도 없이 — 짜. 이유는 하나야: fit() 이 짊어지고 있던 게 전부 얼마나 무거운지 직접 느껴보는 거. epoch loop, tape 두 개, metric 출력, checkpoint 로직을 손으로 짜보면 '위 칸의 가치' 가 추상적 주장이 아니라 라인 수로 보여.

manual GAN loop 가 실제로 하는 일

mechanics 는 안 바뀌어 — 책임자만 바뀔 뿐. 각 step 은 여전히 real+fake 섞은 batch 로 discriminator 학습 → generator 가 그걸 속이게 학습, 네트워크마다 optimizer 따로. 아래 뼈대는 two-tape 핵심만 보여줘. 진짜 실행이면 progress 출력, 주기적 sample 이미지 저장, checkpoint 를 직접 감싸야 해 — override 버전이 공짜로 상속하던 것들.

  • discriminator 는 real + fake 를 함께 학습
  • generator 는 discriminator 를 속이려 시도하며 학습
  • 네트워크마다 optimizer 따로
  • 두 loss 모두 모니터링 — 건강한 학습은 둘이 긴장 속에 진동 하지, 0 으로 무너지지 않아

Code

Manual GAN step (TensorFlow backend)·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

lesson 4 의 DCGAN 을 fully manual training loop (fit 도, train_step 도 없이) 으로 재구현. 그 다음 logging / checkpoint / progress 출력에 쓴 라인 수를 override 버전과 나란히 세어봐. fit() 이 공짜로 주던 것 중 가장 아쉬웠던 게 뭔지 한 문장으로.

Progress

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

댓글 0

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

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