| 1 | import os |
| 2 | from pathlib import Path |
| 3 | |
| 4 | import matplotlib.pyplot as plt |
| 5 | import torch |
| 6 | from resnet import BATCH_SIZE, CLASSES, make_loaders |
| 7 | |
| 8 | torch.manual_seed(0) |
| 9 | |
| 10 | print("1) 로더 만들기: make_loaders()") |
| 11 | trainloader, testloader = make_loaders() |
| 12 | trainset, testset = trainloader.dataset, testloader.dataset |
| 13 | print( |
| 14 | f" 학습용 {len(trainset):,}장 → 배치 {len(trainloader)}개 (한 배치 {BATCH_SIZE}장, 순서를 섞는다)" |
| 15 | ) |
| 16 | print(f" 평가용 {len(testset):,}장 → 배치 {len(testloader)}개 (섞지 않는다)") |
| 17 | print(f" 클래스 {len(CLASSES)}개: {', '.join(CLASSES)}") |
| 18 | print() |
| 19 | |
| 20 | print("2) 이미지 한 장: trainset[0]") |
| 21 | image, label = trainset[0] |
| 22 | print(f" 모양 : {tuple(image.shape)} ← (채널 3, 세로 32, 가로 32)") |
| 23 | print(f" 자료형: {image.dtype}") |
| 24 | print(f" 라벨 : {label} ← CLASSES[{label}] = '{CLASSES[label]}'") |
| 25 | print(f" 숫자의 개수: 3 × 32 × 32 = {image.numel():,}") |
| 26 | print() |
| 27 | |
| 28 | print("3) 채널 = 색 하나의 밝기 지도") |
| 29 | raw = torch.from_numpy(trainset.data[0]) # 변환 전 원본: (32, 32, 3), 0~255 정수 |
| 30 | print( |
| 31 | f" 변환 전 원본의 모양: {tuple(raw.shape)}, 값의 범위 {raw.min()}~{raw.max()} ← (세로, 가로, 채널)" |
| 32 | ) |
| 33 | print(" 맨 왼쪽 위 픽셀 한 칸 R G B") |
| 34 | print(f" 원본 (0~255) {raw[0, 0, 0]:4d} {raw[0, 0, 1]:4d} {raw[0, 0, 2]:4d}") |
| 35 | r, g, b = image[:, 0, 0].tolist() |
| 36 | print(f" 변환 뒤 (-1~1) {r:+.3f} {g:+.3f} {b:+.3f} ← (값/255 - 0.5) / 0.5") |
| 37 | print(f" 변환 뒤 전체의 최솟값 {image.min():+.3f}, 최댓값 {image.max():+.3f}") |
| 38 | print( |
| 39 | " 채널별 평균: " + ", ".join(f"{n} {v:+.3f}" for n, v in zip("RGB", image.mean(dim=(1, 2)))) |
| 40 | ) |
| 41 | image_dir = Path(os.environ["IMAGE_DIR"]) |
| 42 | image_dir.mkdir(parents=True, exist_ok=True) |
| 43 | shown = image * 0.5 + 0.5 # 그림으로 볼 때는 정규화를 되돌려 0~1로 |
| 44 | fig, axes = plt.subplots(1, 4, figsize=(8, 2.3)) |
| 45 | axes[0].imshow(shown.permute(1, 2, 0).numpy()) |
| 46 | axes[0].set_title(f"image ({CLASSES[label]})", fontsize=9) |
| 47 | for ax, channel, name in zip(axes[1:], shown, ["R", "G", "B"]): |
| 48 | ax.imshow(channel.numpy(), cmap="gray", vmin=0, vmax=1) # 밝을수록 그 색이 강하다 |
| 49 | ax.set_title(f"channel {name} (32, 32)", fontsize=9) |
| 50 | for ax in axes: |
| 51 | ax.axis("off") |
| 52 | fig.savefig(image_dir / "channels.png", dpi=100, bbox_inches="tight") |
| 53 | print("[[image:channels]]") |
| 54 | print(" → 컬러 이미지 한 장은 32×32 크기의 밝기 지도 3장을 겹친 것이다") |
| 55 | print() |
| 56 | |
| 57 | print("4) 배치 하나: next(iter(trainloader))") |
| 58 | images, labels = next(iter(trainloader)) |
| 59 | print(f" 이미지: {tuple(images.shape)} ← (장수, 채널, 세로, 가로)") |
| 60 | print(f" 라벨 : {tuple(labels.shape)}, 앞의 8개 {labels[:8].tolist()}") |
| 61 | print(" → 앞으로 모든 층은 이 4차원 모양 (장수, 채널, 세로, 가로)을 받고 내놓는다") |
| 62 | print() |
| 63 | |
| 64 | print("5) 배치의 앞 16장") |
| 65 | fig, axes = plt.subplots(2, 8, figsize=(8, 2.4)) |
| 66 | for ax, img, lab in zip(axes.flat, images, labels): |
| 67 | ax.imshow((img * 0.5 + 0.5).permute(1, 2, 0).numpy()) |
| 68 | ax.set_title(CLASSES[lab], fontsize=8) |
| 69 | ax.axis("off") |
| 70 | fig.savefig(image_dir / "samples.png", dpi=100, bbox_inches="tight") |
| 71 | print("[[image:samples]]") |
| 72 | print() |
| 73 | |
| 74 | print("6) 클래스마다 몇 장씩인가") |
| 75 | counts = torch.bincount(torch.tensor(trainset.targets), minlength=10) |
| 76 | print(" 학습용: " + ", ".join(f"{n} {c}" for n, c in zip(CLASSES, counts.tolist()))) |
| 77 | print( |
| 78 | f" → 10개 클래스가 똑같이 5,000장씩이다. 아무거나 찍으면 정확도는 {100 / len(CLASSES):.0f}%다" |
| 79 | ) |