본문 바로가기
AI 노트

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

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

Python과 TensorFlow를 사용하며, 주석은 모두 한글로 설명되어 있습니다.

 

 

# MNIST 숫자 이미지 분류 실습 (TensorFlow/Keras)

import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt

# 1. 데이터 불러오기
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# 2. 데이터 전처리
# 픽셀 값 정규화 (0~255 → 0~1 사이 값)
x_train = x_train / 255.0
x_test = x_test / 255.0

# 라벨을 원-핫 인코딩
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

# 3. 모델 만들기
model = Sequential([
    Flatten(input_shape=(28, 28)),      # 28x28 이미지를 1차원으로 펴기
    Dense(128, activation='relu'),     # 은닉층 (ReLU)
    Dense(10, activation='softmax')    # 출력층 (10개 클래스)
])

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

# 5. 모델 학습
history = model.fit(x_train, y_train, epochs=5, validation_split=0.2)

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

# 7. 예측 예제 보기
plt.imshow(x_test[0], cmap='gray')
plt.title(f"model predict: {model.predict(x_test[:1]).argmax()}, answer: {y_test[0].argmax()}")
plt.show()

 

 

이 실습으로 배우는 핵심 개념

  • 데이터셋 구조 이해 (28x28 이미지, 0~9 레이블)
  • 인공 신경망(ANN)의 기본 구조
  • 훈련과 검증의 차이
  • 모델 평가 방법 (evaluate, predict)
  • 정규화와 원-핫 인코딩 개념

 

 

반응형