AlexNet은 2012년 ImageNet 대회에서 혁신적인 성능을 보인 최초의 심층 컨볼루션 신경망 중 하나로, GPU 기반 훈련과 ReLU 활성화 함수, 드롭아웃, 데이터 증강 등 현대 딥러닝의 핵심 기법을 처음으로 체계적으로 도입했습니다. 본 문서에서는 TensorFlow 2.x 환경에서 Keras API를 활용해 CIFAR-10 데이터셋에 맞게 조정된 AlexNet 아키텍처를 구현하고 평가합니다.
먼저 필요한 라이브러리를 임포트합니다:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, models, optimizers
import numpy as np
import matplotlib.pyplot as plt
import cv2
CIFAR-10 데이터셋을 로드하고 전처리합니다. 원본 이미지 크기(32×32)는 AlexNet의 입력 요구사항(224×224)과 불일치하므로, 리사이징을 수행합니다:
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
# 레이블 원-핫 인코딩
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
# 입력 크기 확장: 32×32 → 224×224
def upscale_batch(images, target_size=(224, 224)):
batch_resized = np.zeros((images.shape[0], *target_size, 3), dtype=images.dtype)
for idx, img in enumerate(images):
batch_resized[idx] = cv2.resize(img, target_size, interpolation=cv2.INTER_CUBIC)
return batch_resized
x_train_224 = upscale_batch(x_train)
x_test_224 = upscale_batch(x_test)
print(f"훈련 데이터 형태: {x_train_224.shape}, 테스트 데이터 형태: {x_test_224.shape}")
print(f"레이블 형태: {y_train.shape}, {y_test.shape}")
다음으로, CIFAR-10 특성에 맞게 조정된 AlexNet 모델을 정의합니다. 원본 논문의 파라미터를 기반으로 하되, 출력 계층을 10클래스에 맞추고, 배치 정규화와 드롭아웃을 전략적으로 배치하여 일반화 성능을 강화했습니다:
def build_alexnet_classifier(input_shape=(224, 224, 3), num_classes=10):
inputs = layers.Input(shape=input_shape)
# Conv Block 1
x = layers.Conv2D(96, kernel_size=11, strides=4, activation='relu', padding='valid')(inputs)
x = layers.BatchNormalization()(x)
x = layers.MaxPooling2D(pool_size=3, strides=2)(x)
# Conv Block 2
x = layers.Conv2D(256, kernel_size=5, activation='relu', padding='same')(x)
x = layers.BatchNormalization()(x)
x = layers.MaxPooling2D(pool_size=3, strides=2)(x)
# Conv Block 3–5
x = layers.Conv2D(384, kernel_size=3, activation='relu', padding='same')(x)
x = layers.Conv2D(384, kernel_size=3, activation='relu', padding='same')(x)
x = layers.Conv2D(256, kernel_size=3, activation='relu', padding='same')(x)
x = layers.MaxPooling2D(pool_size=3, strides=2)(x)
# Fully Connected Layers
x = layers.Flatten()(x)
x = layers.Dense(4096, activation='relu')(x)
x = layers.Dropout(0.5)(x)
x = layers.Dense(4096, activation='relu')(x)
x = layers.Dropout(0.5)(x)
outputs = layers.Dense(num_classes, activation='softmax')(x)
model = models.Model(inputs, outputs)
optimizer = optimizers.Adam(learning_rate=1e-3)
model.compile(
optimizer=optimizer,
loss='categorical_crossentropy',
metrics=['accuracy']
)
return model
alexnet_model = build_alexnet_classifier()
alexnet_model.summary()
데이터 증강 없이 순수한 훈련을 위해 ImageDataGenerator를 사용하지 않고, 직접 배치 생성기를 구성할 수도 있습니다. 그러나 효율성을 위해 tf.data.Dataset API를 활용하는 방식을 권장합니다:
train_dataset = tf.data.Dataset.from_tensor_slices((x_train_224, y_train))
train_dataset = train_dataset.shuffle(buffer_size=10000).batch(32).prefetch(tf.data.AUTOTUNE)
test_dataset = tf.data.Dataset.from_tensor_slices((x_test_224, y_test))
test_dataset = test_dataset.batch(32).prefetch(tf.data.AUTOTUNE)
모델 훈련을 시작합니다. 과적합 방지를 위해 조기 종료(EarlyStopping)와 모델 체크포인트를 포함한 콜백을 추가합니다:
callbacks = [
keras.callbacks.EarlyStopping(patience=3, restore_best_weights=True),
keras.callbacks.ReduceLROnPlateau(factor=0.5, patience=2)
]
history = alexnet_model.fit(
train_dataset,
epochs=15,
validation_data=test_dataset,
callbacks=callbacks,
verbose=1
)
훈련 완료 후, 테스트 세트에서 최종 성능을 평가합니다:
test_loss, test_acc = alexnet_model.evaluate(test_dataset, verbose=0)
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='Val Accuracy')
plt.title('Model Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Val Loss')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.tight_layout()
plt.show()