| 1 | import os |
| 2 | from pathlib import Path |
| 3 | |
| 4 | import matplotlib.pyplot as plt |
| 5 | import torch |
| 6 | from deep_kmeans import LATENT_SIZE, Decoder, Encoder, load_data |
| 7 | from torch import nn |
| 8 | |
| 9 | torch.set_num_threads(1) # 작은 모델이라 스레드 하나가 오히려 빠르다 |
| 10 | device = torch.device("cpu") |
| 11 | train_x, test_x, _ = load_data(device) |
| 12 | |
| 13 | # demo는 1분 안에 끝나야 하므로 학습 이미지 60,000장 가운데 6,000장만 쓴다 |
| 14 | N_TRAIN, N_TEST, EPOCHS = 6000, 1000, 10 |
| 15 | train_x, test_x = train_x[:N_TRAIN], test_x[:N_TEST] |
| 16 | |
| 17 | torch.manual_seed(2) |
| 18 | encoder, decoder = Encoder(LATENT_SIZE), Decoder(LATENT_SIZE) |
| 19 | |
| 20 | print("1) 디코더는 인코더를 거꾸로 밟는다") |
| 21 | with torch.no_grad(): |
| 22 | h = encoder(test_x[:4]) |
| 23 | print(f" {'z':<24}{tuple(h.shape)} ← 잠재 변수") |
| 24 | for layer in decoder.net: |
| 25 | h = layer(h) |
| 26 | if not isinstance(layer, nn.ReLU | nn.Sigmoid): |
| 27 | print(f" {type(layer).__name__:<24}{tuple(h.shape)}") |
| 28 | print( |
| 29 | f" 출력 값 범위 {h.min().item():.3f}~{h.max().item():.3f} ← 마지막 Sigmoid 때문에 입력처럼 0~1 사이" |
| 30 | ) |
| 31 | print() |
| 32 | |
| 33 | print("2) 전치 합성곱 출력 크기 = (입력 - 1) × stride + 커널 (+ output_padding)") |
| 34 | print(f" 4 → (4 - 1) × 1 + 3 = {(4 - 1) * 1 + 3}") |
| 35 | print(f" 6 → (6 - 1) × 2 + 3 = {(6 - 1) * 2 + 3}") |
| 36 | print(f" 13 → (13 - 1) × 2 + 3 = {(13 - 1) * 2 + 3}, 여기에 output_padding=1 을 더해 28") |
| 37 | print() |
| 38 | |
| 39 | |
| 40 | def test_loss(encoder, decoder) -> float: |
| 41 | with torch.no_grad(): |
| 42 | return nn.functional.mse_loss(decoder(encoder(test_x)), test_x).item() |
| 43 | |
| 44 | |
| 45 | def train_autoencoder(encoder, decoder) -> list[float]: |
| 46 | """복원 손실만으로 EPOCHS 에폭 학습하고, 에폭마다 잰 테스트 복원 손실을 돌려준다.""" |
| 47 | optimizer = torch.optim.Adam([*encoder.parameters(), *decoder.parameters()], lr=1e-3) |
| 48 | history = [] |
| 49 | for _ in range(EPOCHS): |
| 50 | for idx in torch.randperm(N_TRAIN).split(128): |
| 51 | x = train_x[idx] |
| 52 | loss = nn.functional.mse_loss(decoder(encoder(x)), x) |
| 53 | optimizer.zero_grad() |
| 54 | loss.backward() |
| 55 | optimizer.step() |
| 56 | history.append(test_loss(encoder, decoder)) |
| 57 | return history |
| 58 | |
| 59 | |
| 60 | print("3) 복원 손실(MSE)만으로 오토인코더를 학습해 본다") |
| 61 | print(f" (학습 {N_TRAIN:,}장, 테스트 {N_TEST:,}장, {EPOCHS} 에폭으로 줄여서 실행. 시드 2)") |
| 62 | with torch.no_grad(): |
| 63 | before = decoder(encoder(test_x[:10])) |
| 64 | print(f" 에폭 0 테스트 복원 손실 {test_loss(encoder, decoder):.4f} ← 학습 전") |
| 65 | for epoch, value in enumerate(train_autoencoder(encoder, decoder)): |
| 66 | print(f" 에폭 {epoch + 1:2d} 테스트 복원 손실 {value:.4f}") |
| 67 | print(" → 라벨 없이 '입력 = 정답'으로만 학습했는데 손실이 줄어든다") |
| 68 | print() |
| 69 | |
| 70 | print("4) 복원 결과 (위: 입력, 가운데: 학습 전 복원, 아래: 학습 후 복원)") |
| 71 | with torch.no_grad(): |
| 72 | after = decoder(encoder(test_x[:10])) |
| 73 | fig, axes = plt.subplots(3, 10, figsize=(8, 2.6)) |
| 74 | for row, (images, name) in enumerate( |
| 75 | [(test_x[:10], "input"), (before, "before"), (after, "after")] |
| 76 | ): |
| 77 | for col in range(10): |
| 78 | axes[row, col].imshow(images[col, 0], cmap="gray", vmin=0, vmax=1) |
| 79 | axes[row, col].axis("off") |
| 80 | axes[row, 0].set_title(name, fontsize=8, loc="left") |
| 81 | image_dir = Path(os.environ["IMAGE_DIR"]) |
| 82 | image_dir.mkdir(parents=True, exist_ok=True) |
| 83 | fig.savefig(image_dir / "reconstruction.png", dpi=100, bbox_inches="tight") |
| 84 | print("[[image:reconstruction]]") |
| 85 | print() |
| 86 | |
| 87 | print("5) 같은 코드를 시드만 0으로 바꿔 다시 학습하면") |
| 88 | torch.manual_seed(0) |
| 89 | encoder0, decoder0 = Encoder(LATENT_SIZE), Decoder(LATENT_SIZE) |
| 90 | history = train_autoencoder(encoder0, decoder0) |
| 91 | print(" 에폭별 테스트 복원 손실:", " ".join(f"{v:.3f}" for v in history)) |
| 92 | print( |
| 93 | f" → 이 시드에서는 {EPOCHS} 에폭(= {EPOCHS * len(torch.randperm(N_TRAIN).split(128))} 스텝) 안에 손실이 거의 줄지 않았다. 출발점에 따라 초반이 느릴 수 있다" |
| 94 | ) |