반응형
CIFAR-10 데이터셋을 활용한 개와 고양이 분류기 구현
1. 개요
딥러닝에서 이미지 분류는 가장 기본적인 응용 분야 중 하나입니다. 이번 포스팅에서는 CIFAR-10 데이터셋을 활용하여 개와 고양이를 분류하는 CNN(Convolutional Neural Network) 모델을 구현하는 방법을 알아보겠습니다.
CIFAR-10 데이터셋은 총 10개의 클래스(비행기, 자동차, 새, 고양이, 사슴, 개, 개구리, 말, 배, 트럭)로 구성되어 있으며, 각 클래스당 6,000개의 이미지가 포함되어 있습니다. 이 중에서 개와 고양이 클래스만 선택하여 이진 분류(Binary Classification) 모델을 학습하겠습니다.
2. 환경 설정
필요한 패키지를 설치하고 라이브러리를 불러옵니다.
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras import layers, models
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split
3. 데이터 로드 및 전처리
CIFAR-10 데이터셋을 로드한 후, 개와 고양이 데이터만 필터링하여 사용하겠습니다.
# CIFAR-10 데이터셋 로드
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
# 클래스 이름 정의
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
# 개와 고양이 클래스만 선택
cat_dog_indices = (y_train.flatten() == 3) | (y_train.flatten() == 5)
x_train, y_train = x_train[cat_dog_indices], y_train[cat_dog_indices]
cat_dog_indices_test = (y_test.flatten() == 3) | (y_test.flatten() == 5)
x_test, y_test = x_test[cat_dog_indices_test], y_test[cat_dog_indices_test]
# 라벨을 0과 1로 변환 (고양이: 0, 개: 1)
y_train = np.where(y_train == 3, 0, 1)
y_test = np.where(y_test == 3, 0, 1)
# 데이터 정규화 (0~1 범위)
x_train = x_train / 255.0
x_test = x_test / 255.0
# 데이터셋 확인
print("Training Data Shape:", x_train.shape)
print("Test Data Shape:", x_test.shape)
4. 모델 구성
CNN 모델을 정의하고, 합성곱 층과 풀링 층을 활용하여 특징을 추출하도록 설계합니다.
# CNN 모델 구성
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(1, activation='sigmoid')
])
# 모델 요약
model.summary()
5. 모델 컴파일 및 학습
손실 함수는 binary_crossentropy, 옵티마이저는 Adam을 사용하여 모델을 학습합니다.
# 모델 컴파일
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# 모델 학습
history = model.fit(x_train, y_train, epochs=20, batch_size=32, validation_data=(x_test, y_test))
6. 학습 결과 평가 및 시각화
모델의 성능을 평가하고 학습 과정에서의 손실 및 정확도 변화를 시각화합니다.
# 모델 평가
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f'테스트 정확도: {test_acc:.4f}')
# 학습 곡선 시각화
plt.figure(figsize=(12, 4))
# 정확도 그래프
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.title('Accuracy over epochs')
# 손실 그래프
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('Loss over epochs')
plt.show()
7. 모델 예측 및 결과 확인
훈련된 모델을 이용해 새로운 이미지를 예측하는 방법을 살펴보겠습니다.
# 임의의 샘플 선택
num_samples = 5
sample_images = x_test[:num_samples]
sample_labels = y_test[:num_samples]
# 예측 수행
predictions = model.predict(sample_images)
predictions = (predictions > 0.5).astype(int)
# 결과 시각화
plt.figure(figsize=(10, 5))
for i in range(num_samples):
plt.subplot(1, num_samples, i+1)
plt.imshow(sample_images[i])
plt.title(f'Pred: {"Dog" if predictions[i] == 1 else "Cat"}\nTrue: {"Dog" if sample_labels[i] == 1 else "Cat"}')
plt.axis('off')
plt.show()
8. 결론
이번 포스팅에서는 CIFAR-10 데이터셋을 활용하여 개와 고양이를 분류하는 CNN 모델을 구축하는 방법을 살펴보았습니다. 딥러닝 모델을 활용하여 이미지 분류 문제를 해결하는 과정에서 데이터 전처리, 모델 구성, 학습 및 평가 과정을 체계적으로 진행할 수 있었습니다.
반응형
'Python for AI, Embedded > Deep Learning: PyTorch & AI Modeling' 카테고리의 다른 글
| 얼굴 인식 모델 구현 (OpenCV 및 딥러닝 활용) (0) | 2026.01.06 |
|---|---|
| 감성 분석(Sentiment Analysis) 모델 구현 (영문 텍스트 분석) (0) | 2026.01.05 |
| MNIST 손글씨 데이터셋을 이용한 숫자 분류 모델 만들기 (0) | 2026.01.03 |
| BERT와 GPT의 차이점 및 기본 개념 (0) | 2026.01.02 |
| Transformer 모델의 개념 및 기초 구현 (0) | 2026.01.01 |