| 1 | import os |
| 2 | from pathlib import Path |
| 3 | |
| 4 | import matplotlib.pyplot as plt |
| 5 | import torch |
| 6 | from resnet import CLASSES, classifier_head, conv3x3, make_loaders |
| 7 | from torch import nn |
| 8 | |
| 9 | torch.manual_seed(0) |
| 10 | image_dir = Path(os.environ["IMAGE_DIR"]) |
| 11 | image_dir.mkdir(parents=True, exist_ok=True) |
| 12 | |
| 13 | print("1) 풀링: 가중치 없이, 구역마다 값 하나만 남긴다") |
| 14 | a = torch.tensor( |
| 15 | [[1.0, 3.0, 2.0, 0.0], [5.0, 2.0, 1.0, 1.0], [0.0, 1.0, 4.0, 2.0], [2.0, 0.0, 3.0, 8.0]] |
| 16 | ) |
| 17 | print(" 입력 4×4:") |
| 18 | for row in a.tolist(): |
| 19 | print(" " + " ".join(f"{v:.0f}" for v in row)) |
| 20 | mx = nn.MaxPool2d(2)(a[None, None])[0, 0] |
| 21 | av = nn.AvgPool2d(2)(a[None, None])[0, 0] |
| 22 | print(" MaxPool2d(2): 2×2 구역의 최댓값 AvgPool2d(2): 2×2 구역의 평균") |
| 23 | for r1, r2 in zip(mx.tolist(), av.tolist()): |
| 24 | print(" " + " ".join(f"{v:.0f}" for v in r1) + " " * 32 + " ".join(f"{v:.2f}" for v in r2)) |
| 25 | n_pool = sum(p.numel() for p in nn.MaxPool2d(2).parameters()) |
| 26 | print(f" → 4×4가 2×2가 됐다. 풀링 층의 파라미터 수: {n_pool}") |
| 27 | print() |
| 28 | |
| 29 | print("2) 특징 맵을 줄이는 두 가지 방법") |
| 30 | trainloader, _ = make_loaders() |
| 31 | image, label = trainloader.dataset[4] |
| 32 | x = image[None] |
| 33 | fmap = conv3x3(3, 16)(x) |
| 34 | print(f" conv3x3(3, 16)의 출력 : {tuple(fmap.shape)}") |
| 35 | print( |
| 36 | f" 거기에 MaxPool2d(2) : {tuple(nn.MaxPool2d(2)(fmap).shape)} ← 채널 수는 그대로, 세로와 가로만 절반" |
| 37 | ) |
| 38 | print( |
| 39 | f" 처음부터 conv3x3(3, 16, stride=2) : {tuple(conv3x3(3, 16, stride=2)(x).shape)} ← 이 코드는 이쪽을 쓴다" |
| 40 | ) |
| 41 | print( |
| 42 | " → 둘 다 크기를 절반으로 줄인다. 풀링은 구역에서 고르고, stride 2는 필터를 두 칸씩 건너뛴다" |
| 43 | ) |
| 44 | print() |
| 45 | |
| 46 | print("3) 줄여도 윤곽은 남는다") |
| 47 | gray = image.mean(dim=0, keepdim=True)[None] |
| 48 | sobel = torch.tensor([[-1.0, 0.0, 1.0], [-1.0, 0.0, 1.0], [-1.0, 0.0, 1.0]]) |
| 49 | kernels = torch.stack([sobel, sobel.T]).unsqueeze(1) |
| 50 | edges = nn.functional.conv2d(gray, kernels, padding=1).pow(2).sum(dim=1, keepdim=True).sqrt() |
| 51 | levels = [edges, nn.MaxPool2d(2)(edges), nn.MaxPool2d(4)(edges), nn.MaxPool2d(8)(edges)] |
| 52 | fig, axes = plt.subplots(1, 5, figsize=(8, 2)) |
| 53 | axes[0].imshow((image * 0.5 + 0.5).permute(1, 2, 0).numpy()) |
| 54 | axes[0].set_title(f"image ({CLASSES[label]})", fontsize=9) |
| 55 | for ax, level in zip(axes[1:], levels): |
| 56 | ax.imshow(level[0, 0].numpy(), cmap="gray") |
| 57 | size = level.shape[-1] |
| 58 | ax.set_title("edges 32x32" if size == 32 else f"max pool → {size}x{size}", fontsize=9) |
| 59 | for ax in axes: |
| 60 | ax.axis("off") |
| 61 | fig.savefig(image_dir / "pooling.png", dpi=100, bbox_inches="tight") |
| 62 | print(" 2단계의 경계 필터 결과(32×32)를 최대 풀링으로 16×16, 8×8, 4×4로 줄였다") |
| 63 | print("[[image:pooling]]") |
| 64 | print( |
| 65 | " → 16×16(256칸)에서도 차의 윤곽과 바퀴가 보인다. 4×4(16칸)에는 '아래쪽에 경계가 많다'는 정도만 남는다" |
| 66 | ) |
| 67 | print(" → 풀링은 정확한 위치를 버리고 '이 근처에 그 특징이 있는가'를 남긴다") |
| 68 | print() |
| 69 | |
| 70 | print("4) 전역 평균 풀링: 채널마다 숫자 하나") |
| 71 | features = torch.randn(2, 64, 4, 4) # 사진 2장, 채널 64개, 4×4 특징 맵이라고 하자 |
| 72 | gap = nn.AdaptiveAvgPool2d(1) |
| 73 | pooled = gap(features) |
| 74 | print(f" 입력 {tuple(features.shape)} → AdaptiveAvgPool2d(1) → {tuple(pooled.shape)}") |
| 75 | print( |
| 76 | f" 0번 사진 3번 채널: 16칸의 평균 {features[0, 3].mean():+.4f} = 풀링 결과 {pooled[0, 3, 0, 0]:+.4f}" |
| 77 | ) |
| 78 | print( |
| 79 | f" 입력이 8×8여도: {tuple(torch.randn(2, 64, 8, 8).shape)} → {tuple(gap(torch.randn(2, 64, 8, 8)).shape)} ← 결과 크기를 1×1로 정해 두는 풀링이다" |
| 80 | ) |
| 81 | print(" → 채널 하나가 '어떤 특징'이라면, 그 평균은 '이 사진에 그 특징이 얼마나 있는가'다") |
| 82 | print() |
| 83 | |
| 84 | print("5) 분류 머리: classifier_head(64)") |
| 85 | head = classifier_head(64) |
| 86 | h = features |
| 87 | for layer in head: |
| 88 | h = layer(h) |
| 89 | print(f" {layer.__class__.__name__:<18} → {tuple(h.shape)}") |
| 90 | n_head = sum(p.numel() for p in head.parameters()) |
| 91 | n_flat = 64 * 4 * 4 * 10 + 10 |
| 92 | print(f" 파라미터 수: 64 × 10 + 10 = {n_head}") |
| 93 | print(f" 평균 내지 않고 4×4를 그대로 펴서 Linear에 넣었다면: 1,024 × 10 + 10 = {n_flat:,}") |
| 94 | print() |
| 95 | |
| 96 | print("6) 점수 10개 읽기") |
| 97 | scores = head(features)[0] |
| 98 | probs = scores.softmax(dim=0) |
| 99 | print(" 클래스 " + " ".join(f"{c:>6}" for c in CLASSES)) |
| 100 | print(" 점수 " + " ".join(f"{v:+6.2f}" for v in scores.tolist())) |
| 101 | print(" 확률 " + " ".join(f"{v:6.3f}" for v in probs.tolist())) |
| 102 | print( |
| 103 | f" 확률의 합 {probs.sum():.3f}, 가장 큰 점수는 {scores.argmax().item()}번 → 예측 '{CLASSES[scores.argmax()]}'" |
| 104 | ) |
| 105 | print(" → 모델이 내는 것은 점수(logit)다. softmax를 거치면 확률이 되고, 가장 큰 칸이 예측이다") |
| 106 | print(" → 입력도 가중치도 무작위라 지금 예측에는 뜻이 없다") |