| 1 | import os |
| 2 | import time |
| 3 | from pathlib import Path |
| 4 | |
| 5 | import matplotlib.pyplot as plt |
| 6 | import torch |
| 7 | from deep_kmeans import load_data, to_tensor_images |
| 8 | from torch.utils.data import DataLoader |
| 9 | from torchvision import datasets |
| 10 | from torchvision.transforms import v2 |
| 11 | |
| 12 | from ptintro import DATA_DIR |
| 13 | |
| 14 | torch.manual_seed(0) |
| 15 | device = torch.device("cpu") |
| 16 | |
| 17 | print("1) MNIST 원본은 어떻게 들어 있나") |
| 18 | raw = datasets.MNIST(DATA_DIR, train=True).data |
| 19 | print( |
| 20 | f" trainset.data : {tuple(raw.shape)} dtype={raw.dtype} 값 {raw.min().item()}~{raw.max().item()}" |
| 21 | ) |
| 22 | x = to_tensor_images(raw[:4]) |
| 23 | print( |
| 24 | f" to_tensor_images : {tuple(x.shape)} dtype={x.dtype} 값 {x.min().item():.1f}~{x.max().item():.1f}" |
| 25 | ) |
| 26 | print(" → 채널 축(1)을 끼워 넣고 255로 나눠 합성곱 층이 받는 (N, 1, 28, 28) 실수 텐서로 바꾼다") |
| 27 | print() |
| 28 | |
| 29 | print("2) load_data: 전체를 텐서 하나로") |
| 30 | train_x, test_x, test_y = load_data(device) |
| 31 | print(f" train_x : {tuple(train_x.shape)} {train_x.dtype} {train_x.numel() * 4 / 2**20:.0f} MB") |
| 32 | print(f" test_x : {tuple(test_x.shape)}") |
| 33 | print(f" test_y : {test_y.shape} {test_y.dtype} 앞 10개 {test_y[:10].tolist()}") |
| 34 | print(" → 학습 라벨은 돌려주지 않는다. 라벨은 마지막에 테스트 세트로 채점할 때만 쓴다") |
| 35 | print() |
| 36 | |
| 37 | print("3) 미니배치는 인덱싱으로 꺼낸다") |
| 38 | batches = torch.randperm(len(train_x)).split(128) |
| 39 | print(f" randperm(60000).split(128) → 배치 {len(batches)}개, 마지막 배치 {len(batches[-1])}장") |
| 40 | print(f" train_x[batches[0]] : {tuple(train_x[batches[0]].shape)}") |
| 41 | print() |
| 42 | |
| 43 | print("4) 한 에폭 분량의 배치를 꺼내는 데 걸리는 시간 (이 컴퓨터, CPU)") |
| 44 | start = time.perf_counter() |
| 45 | for idx in batches: |
| 46 | train_x[idx] |
| 47 | t_tensor = time.perf_counter() - start |
| 48 | |
| 49 | loader = DataLoader( |
| 50 | datasets.MNIST( |
| 51 | DATA_DIR, |
| 52 | train=True, |
| 53 | transform=v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)]), |
| 54 | ), |
| 55 | batch_size=128, |
| 56 | shuffle=True, |
| 57 | ) |
| 58 | start = time.perf_counter() |
| 59 | for _ in loader: |
| 60 | pass |
| 61 | t_loader = time.perf_counter() - start |
| 62 | print(f" {t_tensor:6.2f}초 ← 텐서 인덱싱") |
| 63 | print(f" {t_loader:6.2f}초 ← Dataset + DataLoader ({t_loader / t_tensor:.0f}배)") |
| 64 | print(" → 30 에폭을 돌면 이 차이가 30번 쌓인다 (시간은 실행할 때마다 조금씩 다르다)") |
| 65 | print() |
| 66 | |
| 67 | print("5) 테스트 이미지 앞 10장") |
| 68 | fig, axes = plt.subplots(1, 10, figsize=(8, 1.2)) |
| 69 | for ax, img, label in zip(axes, test_x[:10], test_y[:10]): |
| 70 | ax.imshow(img[0], cmap="gray") |
| 71 | ax.set_title(int(label), fontsize=9) |
| 72 | ax.axis("off") |
| 73 | image_dir = Path(os.environ["IMAGE_DIR"]) |
| 74 | image_dir.mkdir(parents=True, exist_ok=True) |
| 75 | fig.savefig(image_dir / "digits.png", dpi=100, bbox_inches="tight") |
| 76 | print("[[image:digits]]") |