본문 바로가기
AI 노트

CNN 버전 MNIST 손글씨 숫자 분류 실습 Colab 코드

by 리틀타미 2025. 8. 4.
반응형

MNIST 숫자 분류 모델을 Convolutional Neural Network (CNN) 으로 확장해보겠습니다.
CNN은 이미지 데이터를 다룰 때 더욱 뛰어난 성능을 발휘합니다.

 

 

# CNN 기반 MNIST 숫자 분류 모델

import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Input
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
import numpy as np

# 1. 데이터 로드
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# 2. 전처리: reshape + 정규화 + 원-핫 인코딩
x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255.0
x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255.0
y_train_cat = to_categorical(y_train)
y_test_cat = to_categorical(y_test)

# 3. CNN 모델 구성 (Input 객체 사용)
model = Sequential([
    Input(shape=(28, 28, 1)),
    Conv2D(32, (3,3), activation='relu'),
    MaxPooling2D(2,2),
    Dropout(0.25),

    Conv2D(64, (3,3), activation='relu'),
    MaxPooling2D(2,2),
    Dropout(0.25),

    Flatten(),
    Dense(128, activation='relu'),
    Dropout(0.5),
    Dense(10, activation='softmax')
])

# 4. 컴파일
model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

# 5. 학습
history = model.fit(x_train, y_train_cat, epochs=10, validation_split=0.2)

# 6. 평가
test_loss, test_acc = model.evaluate(x_test, y_test_cat)
print(f"테스트 정확도: {test_acc:.4f}")

# 7. 예측 + 시각화
sample = x_test[0:1]  # 고정된 shape: (1, 28, 28, 1)
pred_probs = model.predict(sample)
pred_class = np.argmax(pred_probs[0])
true_class = y_test[0]

plt.imshow(sample[0].reshape(28, 28), cmap='gray')
plt.title(f"predict: {pred_class}, answer: {true_class}")
plt.axis('off')
plt.show()

 

주요 변경 사항 요약

변경 전 (Dense 기반) 변경 후 (CNN 기반)
Flatten → Dense Conv2D → MaxPool → Flatten
입력 shape: (28, 28) 입력 shape: (28, 28, 1)
일반 fully connected 이미지 특징 추출 특화
Dropout 2회 Dropout 3회 (0.25, 0.25, 0.5)

 

CNN 실습의 핵심 포인트

  • Conv2D는 필터를 통해 이미지 특징 추출에 특화
  • MaxPooling2D는 이미지 크기를 줄이면서 특징 강조
  • Flatten 이후 Dense로 분류 진행

 

 

반응형