3주 실습. NumPy 만으로 손글씨 숫자(MNIST) 분류¶
- 목표: 층(layer)을 클래스로 만들어 순전파·역전파를 직접 구현하고, MLP 로 손글씨 숫자를 분류한다.
- 예상 시간: 약 4시간 (실행은 CPU 에서 1분 안팎)
- 환경: CPU (GPU 필요 없음)
- 데이터: MNIST (손글씨 숫자 28x28 흑백, 학습 60,000장·시험 10,000장). 만든 이: Yann LeCun, Corinna Cortes, Christopher J.C. Burges (원 페이지).
라이선스: Hugging Face 데이터 카드(ylecun/mnist)에 MIT 로 표시돼 있어요.
아래 코드는 Keras 가 공개한
mnist.npz사본을 내려받아요(약 11 MB). 시간을 아끼려고 학습 데이터는 일부만 써요. - 정답 노트북:
03-numpy-mlp-mnist-solution.ipynb
%pip install -q numpy==2.5.5 matplotlib==3.11.2
import os, time, urllib.request
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
1. 데이터 내려받기¶
한 번 받으면 같은 폴더에 mnist.npz 로 저장해 두고 다시 받지 않아요.
URL = "https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz"
PATH = "mnist.npz"
if not os.path.exists(PATH):
urllib.request.urlretrieve(URL, PATH)
with np.load(PATH) as d:
x_train, t_train = d["x_train"], d["y_train"]
x_test, t_test = d["x_test"], d["y_test"]
print(x_train.shape, t_train.shape, x_test.shape, t_test.shape)
2. 전처리¶
28x28 그림을 784 길이 벡터로 펴고, 0~255 를 0~1 로 줄여요. 시간을 위해 학습용 20,000장만 써요.
def preprocess(x):
# TODO: (N, 28, 28) uint8 -> (N, 784) float64, 값은 0~1
return None
N_TRAIN = 20000
X_train = preprocess(x_train[:N_TRAIN])
T_train = t_train[:N_TRAIN]
X_test = preprocess(x_test)
T_test = t_test
print(X_train.shape, X_train.min(), X_train.max())
assert X_train.shape == (20000, 784) and X_train.max() <= 1.0
fig, axes = plt.subplots(1, 8, figsize=(10, 1.8))
for ax, img, label in zip(axes, x_train[:8], t_train[:8]):
ax.imshow(img, cmap="gray")
ax.set_title(int(label))
ax.axis("off")
plt.show()
3. 층 만들기¶
층마다 forward(순전파)와 backward(역전파)가 있어요. backward(dout) 는 "뒤에서 온 기울기" 를 받아 "앞으로 보낼 기울기" 를 돌려줘요.
먼저 ReLU 는 완성해 둘게요.
class ReLU:
def forward(self, x):
self.mask = x <= 0
out = x.copy()
out[self.mask] = 0
return out
def backward(self, dout):
dx = dout.copy()
dx[self.mask] = 0
return dx
Affine 층 (행렬곱 + 편향)¶
\(out = xW + b\) 일 때 (x: (N, in), W: (in, out), b: (out,))
shape 이 맞는지 눈으로 확인하세요. dout 은 (N, out) 이에요.
class Affine:
def __init__(self, W, b):
self.W, self.b = W, b
def forward(self, x):
self.x = x
return x @ self.W + self.b
def backward(self, dout):
# TODO: dx, self.dW, self.db 를 위 식대로 계산하세요.
dx = None
self.dW = None
self.db = None
return dx
softmax 와 교차 엔트로피¶
softmax 는 점수를 확률로 바꿔요. 지수가 너무 커지지 않게 각 행의 최댓값을 먼저 빼요(결과는 같아요). softmax 와 교차 엔트로피를 한 층으로 묶으면 역전파가 놀랄 만큼 단순해져요: \(\frac{\partial L}{\partial s} = \frac{p - t}{N}\) (p: softmax 출력, t: 정답 one-hot).
def softmax(s):
# TODO: 행마다 최댓값을 빼고 exp, 합으로 나누기. (N, C) -> (N, C)
return None
class SoftmaxWithLoss:
def forward(self, s, t):
self.p = softmax(s)
self.t = t # 정답 번호 (N,)
n = len(t)
# TODO: 정답 칸 확률의 -log 평균. log(0) 방지로 1e-12 를 더하세요.
return None
def backward(self, dout=1.0):
n = len(self.t)
dp = self.p.copy()
# TODO: 정답 칸에서만 1 을 빼고, 마지막에 n 으로 나눈 값을 돌려주세요.
return None
s = np.array([[1.0, 2.0, 3.0], [1000.0, 1001.0, 1002.0]])
print(softmax(s))
assert np.allclose(softmax(s).sum(axis=1), 1) and np.isfinite(softmax(s)).all()
4. 신경망 조립¶
784 → 은닉 50 → 10. 가중치는 작은 난수로 시작해요(He 초기화: 입력 수로 정한 크기).
class MLP:
def __init__(self, n_in=784, n_hidden=50, n_out=10):
self.l1 = Affine(rng.normal(0, np.sqrt(2 / n_in), (n_in, n_hidden)), np.zeros(n_hidden))
self.act = ReLU()
self.l2 = Affine(rng.normal(0, np.sqrt(2 / n_hidden), (n_hidden, n_out)), np.zeros(n_out))
self.loss_layer = SoftmaxWithLoss()
def scores(self, x):
# TODO: l1 -> act -> l2 순서로 순전파해서 점수 (N, 10) 을 돌려주세요.
return None
def loss(self, x, t):
return self.loss_layer.forward(self.scores(x), t)
def gradients(self, x, t):
self.loss(x, t)
# TODO: 순전파의 반대 순서로 backward 를 이어 붙이세요. loss_layer -> l2 -> act -> l1
pass
return {"W1": self.l1.dW, "b1": self.l1.db, "W2": self.l2.dW, "b2": self.l2.db}
def accuracy(self, x, t):
return np.mean(self.scores(x).argmax(axis=1) == t)
5. 기울기 확인 (gradient check)¶
역전파가 맞는지 2주차의 수치 미분과 비교해요. 작은 데이터 3장, 은닉 5개짜리 작은 망이면 충분해요. 차이가 \(10^{-6}\) 보다 작으면 통과예요.
def check(model, x, t, name, arr, n_check=5, h=1e-5):
# 가중치 몇 개만 골라 수치 미분과 역전파 값을 비교
grads = model.gradients(x, t)
idx = rng.choice(arr.size, n_check, replace=False)
worst = 0.0
for i in idx:
flat = arr.reshape(-1)
old = flat[i]
flat[i] = old + h; up = model.loss(x, t)
flat[i] = old - h; down = model.loss(x, t)
flat[i] = old
num = (up - down) / (2 * h)
worst = max(worst, abs(num - grads[name].reshape(-1)[i]))
return worst
small = MLP(784, 5, 10)
xs, ts = X_train[:3], T_train[:3]
for name, arr in [("W1", small.l1.W), ("b1", small.l1.b), ("W2", small.l2.W), ("b2", small.l2.b)]:
diff = check(small, xs, ts, name, arr)
print(name, diff)
assert diff < 1e-6, f"{name} 의 역전파가 수치 미분과 달라요"
6. 학습¶
미니배치(한 번에 100장)로 기울기를 구하고, 2주차처럼 가중치 -= 학습률 * 기울기 를 해요. 에폭(epoch) = 학습 데이터를 한 바퀴 다 쓰는 것.
model = MLP()
lr, batch, epochs = 0.1, 100, 5
log = []
t0 = time.time()
for epoch in range(epochs):
order = rng.permutation(N_TRAIN)
for i in range(0, N_TRAIN, batch):
ids = order[i:i + batch]
g = model.gradients(X_train[ids], T_train[ids])
# TODO: 4개 매개변수(W1,b1,W2,b2)를 lr 만큼 기울기 반대로 갱신하세요.
pass
tr_acc = model.accuracy(X_train, T_train)
te_acc = model.accuracy(X_test, T_test)
log.append((model.loss(X_train, T_train), tr_acc, te_acc))
print(f"epoch {epoch+1}: loss={log[-1][0]:.3f} 학습정확도={tr_acc:.3f} 시험정확도={te_acc:.3f}")
print("걸린 시간(초):", round(time.time() - t0, 1))
assert log[-1][2] > 0.90
fig, ax = plt.subplots(1, 2, figsize=(9, 3))
ax[0].plot([l[0] for l in log]); ax[0].set_title("손실"); ax[0].set_xlabel("에폭")
ax[1].plot([l[1] for l in log], label="학습"); ax[1].plot([l[2] for l in log], label="시험")
ax[1].set_title("정확도"); ax[1].set_xlabel("에폭"); ax[1].legend()
plt.show()
7. 틀린 그림 살펴보기¶
모델이 틀린 그림을 몇 장 봐요. 사람이 봐도 헷갈리는 것이 있는지 확인해 보세요.
pred = model.scores(X_test).argmax(axis=1)
wrong = np.where(pred != T_test)[0][:8]
fig, axes = plt.subplots(1, 8, figsize=(11, 2))
for ax, i in zip(axes, wrong):
ax.imshow(x_test[i], cmap="gray")
ax.set_title(f"정답{T_test[i]}/예측{pred[i]}", fontsize=8)
ax.axis("off")
plt.show()
정리 질문¶
- 은닉 노드를 50 → 10, 200 으로 바꾸면 시험 정확도와 시간이 어떻게 달라지나요?
- 학습률을 0.01 과 1.0 으로 바꿔 보세요. 2주차에서 본 현상과 같은가요?
- 도전:
N_TRAIN을 60000 으로 늘리면 정확도가 얼마나 오르나요? 시간은요?