일상에 필요한 정보들/컴퓨터, IT관련

파이썬으로 심층 CNN 모델 구현하기

불타는 신디 2025. 5. 18. 10:56
728x90
반응형

어느 맑은 토요일 아침, ‘지수’는 딥러닝의 첫걸음을 내디딘 뒤 커피 향을 맡으며 중얼거렸습니다.
“기초 신경망까진 해봤으니, 이제 이미지 인식의 강력한 무기인 CNN을 직접 만들어 볼까?”
이렇게 시작된 오늘의 여정, “파이썬으로 심층 CNN 모델 구현하기” 포스팅을 함께 따라가 보겠습니다.


출처 : 구글 이미지

🖼️ 1. CNN(합성곱 신경망)이란?

CNN(Convolutional Neural Network)은 이미지, 영상 같은 2D 데이터 처리에 탁월한 구조입니다.

  • 합성곱(Convolution) 레이어: 작은 필터(커널)를 이미지 전체에 적용해 특징 맵(feature map) 생성
  • 풀링(Pooling) 레이어: 특징 맵을 다운샘플링해 주요 정보만 남기고 계산량·과적합 감소
  • 완전연결(Dense) 레이어: 최종 추출된 특징을 바탕으로 분류·회귀 수행

지수의 깨달음
“CNN은 마치 사진을 작은 창으로 훑으며 중요한 패턴을 뽑아내는 ‘시각 탐정’ 같아요.”


⚙️ 2. 개발 환경 준비

pip install tensorflow pandas matplotlib
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt

plt.rc('font', family='Malgun Gothic')  # 한글 폰트 설정
print("TensorFlow 버전:", tf.__version__)

🏷️ 3. 데이터셋: CIFAR-10 불러오기

CIFAR-10은 10가지 클래스(비행기, 자동차, 새 등)로 구성된 컬러 이미지 60,000장(32×32 픽셀) 데이터셋입니다.

from tensorflow.keras.datasets import cifar10

(X_train, y_train), (X_test, y_test) = cifar10.load_data()
# 픽셀 정규화 (0~1)
X_train, X_test = X_train/255.0, X_test/255.0

print("학습 샘플:", X_train.shape, "테스트 샘플:", X_test.shape)

🏗️ 4. 심층 CNN 모델 설계

다음 구조로 모델을 쌓아 보겠습니다.

  1. Convolution(32, 3×3) → ReLU → MaxPooling(2×2)
  2. Convolution(64, 3×3) → ReLU → MaxPooling(2×2)
  3. Convolution(128, 3×3) → ReLU → MaxPooling(2×2)
  4. Flatten → Dense(128, ReLU) → Dropout(0.5) → Dense(10, Softmax)
model = models.Sequential([
    layers.Conv2D(32, (3,3), activation='relu', input_shape=(32,32,3)),
    layers.MaxPooling2D((2,2)),
    
    layers.Conv2D(64, (3,3), activation='relu'),
    layers.MaxPooling2D((2,2)),
    
    layers.Conv2D(128, (3,3), activation='relu'),
    layers.MaxPooling2D((2,2)),
    
    layers.Flatten(),
    layers.Dense(128, activation='relu'),
    layers.Dropout(0.5),
    layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.summary()

지수의 팁
“드롭아웃은 과적합을 막는 마법의 손길! 과도한 학습을 방지해 줍니다.”


🚂 5. 모델 학습(Training)

history = model.fit(
    X_train, y_train,
    epochs=20,
    batch_size=64,
    validation_split=0.2
)
  • epochs=20: 20회 데이터 순회
  • batch_size=64: 한 번에 64개 이미지 처리
  • validation_split=0.2: 학습 중 성능 검증용 20% 분리

📈 6. 학습 과정 시각화

epochs = range(1, len(history.history['loss'])+1)

plt.figure(figsize=(12,5))

# 손실 그래프
plt.subplot(1,2,1)
plt.plot(epochs, history.history['loss'], label='훈련 손실')
plt.plot(epochs, history.history['val_loss'], label='검증 손실')
plt.title('손실(Loss) 추이')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()

# 정확도 그래프
plt.subplot(1,2,2)
plt.plot(epochs, history.history['accuracy'], label='훈련 정확도')
plt.plot(epochs, history.history['val_accuracy'], label='검증 정확도')
plt.title('정확도(Accuracy) 추이')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()

plt.tight_layout()
plt.show()

해석 포인트

  • 검증 정확도가 훈련 정확도를 따라가지 못하면 과적합 신호입니다.
  • 필요 시 Dropout, 데이터 증강(Augmentation)을 적용해 보세요.

🔍 7. 모델 평가 및 예측

test_loss, test_acc = model.evaluate(X_test, y_test, verbose=2)
print(f"테스트 정확도: {test_acc:.4f}")

# 랜덤 샘플 확인
import numpy as np
indices = np.random.choice(len(X_test), 5)
for i in indices:
    img = X_test[i]
    true = y_test[i][0]
    pred = np.argmax(model.predict(img.reshape(1,32,32,3)))
    plt.imshow(img)
    plt.title(f"실제: {true}, 예측: {pred}")
    plt.axis('off')
    plt.show()

✨ 8. 심화 아이디어

  1. 데이터 증강(Augmentation)
    • ImageDataGenerator로 회전·뒤집기·확대 등 적용
  2. 전이 학습(Transfer Learning)
    • VGG16·ResNet50의 사전 학습된 가중치 활용
  3. 하이퍼파라미터 튜닝
    • learning_rate, batch_size, filter 수 조정
  4. 모델 경량화
    • MobileNet·Pruning으로 모바일 배포 최적화

어느덧 창밖에 해는 저물고, 지수는 완성된 CNN 모델을 바라보며 미소 지었습니다.
“심층 합성곱 신경망도 차근차근 쌓아 올리니, 누구나 강력한 이미지 인식기를 만들 수 있구나!”

다음 포스팅에서는 “파이썬으로 객체 검출(Object Detection) 구현하기”를 다룰 예정이니, 실제 이미지 속 물체를 찾아내는 흥미진진한 여정으로 다시 만나요! 🚀


728x90
반응형