반응형
Dropout은 과적합(overfitting)을 방지하는 대표적인 정규화 기법으로, 학습 중 일부 뉴런을 무작위로 꺼서 모델이 특정 패턴에 과도하게 의존하지 않도록 도와줍니다.
기존 MNIST 분류 모델에 Dropout 레이어를 추가한 개선 버전 코드입니다.
(한글 주석 포함 / TensorFlow 기반)
# Dropout을 활용한 MNIST 숫자 분류 실습
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Dropout
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
import numpy as np
# 1. MNIST 데이터 불러오기
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 2. 데이터 전처리 (정규화, 원-핫 인코딩)
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. Dropout이 포함된 모델 구성
model = Sequential([
Flatten(input_shape=(28, 28)), # 입력: 28x28 이미지 → 1차원
Dense(128, activation='relu'), # 은닉층 1
Dropout(0.3), # 30% 드롭아웃
Dense(64, activation='relu'), # 은닉층 2
Dropout(0.3), # 30% 드롭아웃
Dense(10, activation='softmax') # 출력층 (10개 클래스)
])
# 4. 컴파일 (옵티마이저, 손실함수, 평가지표)
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 5. 모델 학습 (훈련 + 검증)
history = model.fit(x_train, y_train, epochs=10, validation_split=0.2)
# 6. 테스트셋으로 모델 평가
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"테스트 정확도: {test_acc:.4f}")
# 7. 예측 결과 시각화 (1개 이미지)
plt.imshow(x_test[0], cmap='gray')
pred_label = np.argmax(model.predict(x_test[:1]), axis=-1)[0]
true_label = np.argmax(y_test[0])
plt.title(f"predict: {pred_label}, answer: {true_label}")
plt.axis('off')
plt.show()
Dropout에 대해 더 알아보기
| 구성 | 요소 설명 |
| Dropout(0.3) | 학습 중 30% 뉴런을 랜덤으로 끄기 |
| Dropout 위치 | 보통 Dense 뒤에 넣음 |
| 과적합 방지 원리 | 일부 뉴런을 학습에서 제외시켜 다양한 패턴 학습 유도 |
변경 요약
| 변경 전 | 변경 후 |
| Dense 1개 | Dense + Dropout 2회 |
| Epochs 5회 | Epochs 10회 (더 일반화된 모델) |
실습 요약
- Dropout(0.3)을 두 번 추가하여 과적합 방지
- validation_split=0.2로 검증 성능도 함께 확인
- 학습은 10 에폭(Epoch)으로 충분히 진행
반응형
'AI 노트' 카테고리의 다른 글
| 영상 제작 - 시니어 타겟 (1) | 2025.09.09 |
|---|---|
| 영상 제작 - 주제 선정 (0) | 2025.09.09 |
| CNN 버전 MNIST 손글씨 숫자 분류 실습 Colab 코드 (2) | 2025.08.04 |
| MNIST 손글씨 숫자 분류 실습 Colab 코드 (0) | 2025.08.04 |
| 입문자용 AI 개발 (1) | 2025.08.04 |