| 1 | import os |
| 2 | from pathlib import Path |
| 3 | |
| 4 | import matplotlib.pyplot as plt |
| 5 | import torch |
| 6 | from gan import BATCH_SIZE, Discriminator, Generator, make_loader, sample_noise |
| 7 | |
| 8 | torch.manual_seed(0) |
| 9 | device = torch.device("cpu") |
| 10 | |
| 11 | print("1) 진짜 그림을 배치로 꺼내기: make_loader()") |
| 12 | loader = make_loader() |
| 13 | real, labels = next(iter(loader)) |
| 14 | print( |
| 15 | f" 전체 그림 수: {len(loader.dataset):,}장, 배치 크기 {BATCH_SIZE} → 한 에폭에 배치 {len(loader)}개" |
| 16 | ) |
| 17 | print(f" 배치 하나 : {tuple(real.shape)} ← 생성자 출력과 같은 (장수, 1, 28, 28)") |
| 18 | print( |
| 19 | f" 라벨 : {tuple(labels.shape)}, 앞 8개 {labels[:8].tolist()} ← 옷 종류 번호. GAN은 쓰지 않는다" |
| 20 | ) |
| 21 | print() |
| 22 | |
| 23 | print("2) 값의 범위를 생성자와 맞춘다") |
| 24 | raw = loader.dataset.data # 변환을 거치기 전의 원본 (uint8) |
| 25 | print( |
| 26 | f" 파일에 든 원본 : 최솟값 {raw.min().item():4d}, 최댓값 {raw.max().item():4d} (정수 0~255)" |
| 27 | ) |
| 28 | scaled = raw[:BATCH_SIZE].float() / 255 |
| 29 | print(f" ToDtype(scale=True) : 최솟값 {scaled.min():4.1f}, 최댓값 {scaled.max():4.1f} (0~1)") |
| 30 | print( |
| 31 | f" Normalize(0.5, 0.5) : 최솟값 {real.min():4.1f}, 최댓값 {real.max():4.1f} (-1~1) ← (x - 0.5) / 0.5" |
| 32 | ) |
| 33 | generator = Generator().to(device) |
| 34 | fake = generator(sample_noise(BATCH_SIZE, device)).detach() |
| 35 | print( |
| 36 | f" 생성자 출력(학습 전): 최솟값 {fake.min():4.1f}, 최댓값 {fake.max():4.1f} (Tanh라 -1~1 안)" |
| 37 | ) |
| 38 | print( |
| 39 | f" 진짜 그림에서 값이 정확히 -1(검정 배경)인 픽셀의 비율: {(real == -1).float().mean():.1%}" |
| 40 | ) |
| 41 | print() |
| 42 | |
| 43 | print("3) 진짜(위)와 학습 전 가짜(아래)") |
| 44 | fig, axes = plt.subplots(2, 8, figsize=(8, 2.3)) |
| 45 | for col in range(8): |
| 46 | axes[0, col].imshow(real[col, 0], cmap="gray", vmin=-1, vmax=1) |
| 47 | axes[1, col].imshow(fake[col, 0], cmap="gray", vmin=-1, vmax=1) |
| 48 | axes[0, col].axis("off") |
| 49 | axes[1, col].axis("off") |
| 50 | axes[0, 0].set_title("real", fontsize=9, loc="left") |
| 51 | axes[1, 0].set_title("fake (untrained)", fontsize=9, loc="left") |
| 52 | image_dir = Path(os.environ["IMAGE_DIR"]) |
| 53 | image_dir.mkdir(parents=True, exist_ok=True) |
| 54 | fig.savefig(image_dir / "real_vs_fake.png", dpi=100, bbox_inches="tight") |
| 55 | print("[[image:real_vs_fake]]") |
| 56 | print() |
| 57 | |
| 58 | print("4) 학습 전 판별자는 둘을 구분하지 못한다") |
| 59 | discriminator = Discriminator().to(device).eval() |
| 60 | with torch.no_grad(): |
| 61 | p_real = discriminator(real).sigmoid().mean() |
| 62 | p_fake = discriminator(fake).sigmoid().mean() |
| 63 | print(f" 진짜 {BATCH_SIZE}장에 준 '진짜일 확률'의 평균: {p_real:.3f}") |
| 64 | print(f" 가짜 {BATCH_SIZE}장에 준 '진짜일 확률'의 평균: {p_fake:.3f}") |
| 65 | print(" → 사람 눈에는 뻔히 다른데 판별자는 둘 다 0.5 근처다. 다음 단계에서 판별자를 가르친다") |