4주 실습. PyTorch 로 3주차 MLP 다시 만들기¶
- 목표: Tensor, autograd,
nn.Module,DataLoader를 직접 만져 보고, 3주차에 NumPy 로 만든 손글씨 숫자(MNIST) 분류기를 PyTorch 로 다시 만들어요. - 예상 시간: 40~60분 (실행은 CPU 에서 5분 안쪽)
- 실행 환경: CPU (GPU·Apple GPU 가 있으면 자동으로 써요. 없어도 괜찮아요)
- 빈칸 미션:
# TODO:가 붙은 셀의...를 채워요. 막히면 같은 폴더의04-pytorch-basics-solution.ipynb를 보세요. - 데이터: MNIST 손글씨 숫자 (출처: http://yann.lecun.com/exdb/mnist/). 원 페이지에는 라이선스 문구가 없고, Hugging Face 데이터 카드(ylecun/mnist)에 MIT 로 표시돼 있어요(2026-11-24 확인). 이 노트북은 내려받아 학습에만 쓰고 다시 배포하지 않아요.
%pip install -q matplotlib==3.11.2
torch·torchvision 은 Colab 에 이미 들어 있어요. 내 PC 에서는
uv add torch torchvision matplotlib로 설치해요. 이 노트북은 torch 2.15.0, torchvision 0.29.2 로 확인했어요.
0. 준비¶
라이브러리를 불러오고, 계산을 할 장치(device)를 골라요.
import os, random, time
import numpy as np
import torch
from torch import nn
import matplotlib.pyplot as plt
QUICK = False # True 로 바꾸면 데이터·에폭을 크게 줄여 아주 빨리 끝나요(점검용)
FORCE_CPU = False # True 로 바꾸면 GPU 가 있어도 CPU 로 고정해요
SEED = 0
random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED)
if FORCE_CPU:
device = "cpu"
elif torch.cuda.is_available():
device = "cuda" # Colab GPU, NVIDIA 그래픽카드
elif torch.backends.mps.is_available():
device = "mps" # Apple Silicon Mac
else:
device = "cpu"
print("torch", torch.__version__, "| device:", device)
1. Tensor — 장치에서 계산할 수 있는 배열¶
NumPy 배열과 거의 똑같이 쓰는데, GPU 로 옮길 수 있고 미분도 기록할 수 있어요.
a = torch.tensor([[1., 2., 3.],
[4., 5., 6.]])
print("shape:", a.shape, "| dtype:", a.dtype) # (2, 3), float32
print("합:", a.sum().item(), "| 열마다 평균:", a.mean(dim=0))
# NumPy 와 서로 바꾸기 (CPU 에서는 메모리를 같이 써요)
n = a.numpy()
print(type(n), torch.from_numpy(n).shape)
미션 1. a(2×3) 와 모두 1 인 b(3×2) 를 행렬곱해서 c(2×2) 를 만드세요. torch.ones(3, 2) 와 @ 를 써요.
b = torch.ones(3, 2)
c = ... # TODO: a 와 b 의 행렬곱
assert c.shape == (2, 2) and c[0, 0].item() == 6.0
print(c)
2. device — 계산할 곳 정하기¶
Tensor 와 모델이 같은 장치에 있어야 계산돼요. .to(device) 로 옮겨요.
x = torch.arange(6, dtype=torch.float32).reshape(2, 3).to(device)
print(x.device)
print((x * 2).cpu().numpy()) # NumPy 로 바꾸려면 먼저 .cpu()
3. autograd — 미분을 대신 해 줘요¶
2주차에 손으로 한 미분을 PyTorch 가 계산해요. \(y = x^3 + 2x\) 이면 \(\frac{dy}{dx} = 3x^2 + 2\) 이고, \(x=2\) 에서 14 예요.
x = torch.tensor(2.0, requires_grad=True) # "이 값의 기울기를 기록해 줘"
y = x**3 + 2*x
y.backward() # 연쇄법칙으로 거꾸로 계산
print(x.grad) # tensor(14.)
미션 2. \(L(w) = (3w - 6)^2\) 일 때, \(w=1\) 에서의 기울기 \(\frac{dL}{dw}\) 를 autograd 로 구하세요. 손으로 하면 \(2(3w-6)\cdot 3 = -18\) 이에요.
w = torch.tensor(1.0, requires_grad=True)
L = ... # TODO: (3w - 6) 의 제곱
... # TODO: 거꾸로 계산하기 (L.backward())
assert abs(w.grad.item() + 18.0) < 1e-6
print("dL/dw =", w.grad.item())
4. nn.Module — 모델을 클래스로 만들기¶
3주차 MLP 는 입력 784 → 은닉 128 → 출력 10 이었어요. nn.Linear 가 가중치 \(W\) 와 편향 \(b\) 를 알아서 들고 있어요.
미션 3. __init__ 에 층 두 개를 만들고, forward 에서 fc1 → ReLU → fc2 순서로 계산하세요.
class MLP(nn.Module):
def __init__(self, n_in=784, n_hidden=128, n_out=10):
super().__init__()
self.fc1 = ... # TODO: nn.Linear(n_in, n_hidden)
self.fc2 = ... # TODO: nn.Linear(n_hidden, n_out)
def forward(self, x):
x = ... # TODO: fc1 을 지나 ReLU (torch.relu)
return self.fc2(x) # softmax 는 손실 함수 안에 들어 있어요
model = MLP().to(device)
n_params = sum(p.numel() for p in model.parameters())
print(model)
print("파라미터 수:", n_params) # 784*128+128 + 128*10+10 = 101770
assert n_params == 101770
5. Dataset 과 DataLoader — 데이터를 배치로 꺼내기¶
Dataset 은 "몇 개고(__len__), i 번째는 뭐냐(__getitem__)"만 답하면 돼요. DataLoader 가 그걸 섞고(shuffle) 묶어서(batch) 줘요.
from torchvision import datasets
train_raw = datasets.MNIST("data", train=True, download=True)
test_raw = datasets.MNIST("data", train=False, download=True)
def to_xy(raw, n=None):
X = raw.data.float().div(255).reshape(-1, 784) # 0~255 → 0~1, 28x28 → 784
y = raw.targets
return (X[:n], y[:n]) if n else (X, y)
N_TRAIN = 3000 if QUICK else 60000
EPOCHS = 1 if QUICK else 3
X_train, y_train = to_xy(train_raw, N_TRAIN)
X_test, y_test = to_xy(test_raw, 1000 if QUICK else None)
print(X_train.shape, y_train.shape, X_test.shape)
class ArrayDataset(torch.utils.data.Dataset):
def __init__(self, X, y):
self.X, self.y = X, y
def __len__(self):
return len(self.X)
def __getitem__(self, i):
return self.X[i], self.y[i]
train_loader = torch.utils.data.DataLoader(ArrayDataset(X_train, y_train), batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(ArrayDataset(X_test, y_test), batch_size=256)
xb, yb = next(iter(train_loader))
print("한 배치:", xb.shape, yb.shape) # (64, 784), (64,)
fig, axes = plt.subplots(1, 6, figsize=(9, 2))
for ax, img, lab in zip(axes, xb, yb):
ax.imshow(img.reshape(28, 28), cmap="gray"); ax.set_title(int(lab)); ax.axis("off")
plt.show()
6. 학습 루프 5줄¶
학습은 어떤 모델이든 이 다섯 줄이에요: 예측 → 손실 → 기울기 지우기 → 거꾸로 계산 → 한 걸음.
zero_grad() 를 빼면 기울기가 계속 쌓여요(PyTorch 는 backward() 때마다 더해요).
미션 4. 다섯 줄을 채우세요. 손실은 nn.CrossEntropyLoss()(softmax + 교차 엔트로피), 옵티마이저는 torch.optim.SGD 예요.
def train_one_epoch(model, loader, loss_fn, opt):
model.train()
total, n = 0.0, 0
for xb, yb in loader:
xb, yb = xb.to(device), yb.to(device)
pred = ... # TODO 1. 예측: model(xb)
loss = ... # TODO 2. 손실: loss_fn(pred, yb)
... # TODO 3. 쌓인 기울기 지우기: opt.zero_grad()
... # TODO 4. 기울기 계산: loss.backward()
... # TODO 5. 가중치 한 걸음: opt.step()
total += loss.item() * len(xb); n += len(xb)
return total / n
@torch.no_grad()
def evaluate(model, loader, loss_fn):
model.eval()
total, correct, n = 0.0, 0, 0
for xb, yb in loader:
xb, yb = xb.to(device), yb.to(device)
out = model(xb)
total += loss_fn(out, yb).item() * len(xb)
correct += (out.argmax(dim=1) == yb).sum().item(); n += len(xb)
return total / n, correct / n
이제 에폭(epoch, 데이터 전체를 한 바퀴)을 돌려요. 매 에폭마다 손실과 정확도를 적어 둬요.
torch.manual_seed(SEED)
model = MLP().to(device)
loss_fn = nn.CrossEntropyLoss()
opt = torch.optim.SGD(model.parameters(), lr=0.1)
history = {"train_loss": [], "test_loss": [], "test_acc": []}
t0 = time.time()
for epoch in range(EPOCHS):
tr = train_one_epoch(model, train_loader, loss_fn, opt)
te_loss, te_acc = evaluate(model, test_loader, loss_fn)
history["train_loss"].append(tr); history["test_loss"].append(te_loss); history["test_acc"].append(te_acc)
print(f"epoch {epoch+1}: train_loss={tr:.4f} test_loss={te_loss:.4f} test_acc={te_acc:.4f}")
print(f"걸린 시간 {time.time()-t0:.1f}초")
assert history["train_loss"][-1] < history["train_loss"][0] or EPOCHS == 1
assert history["test_acc"][-1] > 0.5 # 찍기(10%)보다 훨씬 나아야 해요
plt.plot(history["train_loss"], marker="o", label="train loss")
plt.plot(history["test_loss"], marker="o", label="test loss")
plt.xlabel("epoch"); plt.ylabel("loss"); plt.legend(); plt.show()
정리¶
- 3주차에 직접 쓴 순전파·역전파·가중치 갱신이 PyTorch 에서는
model(x),loss.backward(),opt.step()이에요. - 3주차 NumPy 결과와 정확도를 비교해 보세요. 비슷하면 잘 옮긴 거예요.
- 도전:
n_hidden을 32 와 512 로 바꿔 정확도와 파라미터 수가 어떻게 달라지는지 적어 보세요.