Python DeepLearning

딥러닝 모델의 성능 평가 및 시각화 기법

PyExplorer 2025. 4. 22. 14:44
728x90

딥러닝 모델의 성능 평가 및 시각화 기법

딥러닝 모델을 개발한 후, 해당 모델이 얼마나 잘 동작하는지 평가하는 과정은 매우 중요합니다. 성능 평가를 정확하게 수행해야 모델을 개선하고 최적화할 수 있습니다. 이 글에서는 딥러닝 모델의 성능 평가 방법과 시각화 기법에 대해 설명하고, Python과 TensorFlow/Keras를 활용한 예제 코드를 제공합니다.

1. 딥러닝 모델 성능 평가 지표

모델의 성능을 평가하는 방법은 문제의 유형(회귀 또는 분류)에 따라 다릅니다.

1.1 분류 모델의 성능 평가 지표

분류 문제에서는 주로 다음과 같은 지표를 활용합니다.

  • 정확도(Accuracy): 전체 샘플 중 올바르게 예측한 비율
  • 정밀도(Precision): 모델이 양성(Positive)이라고 예측한 것 중 실제 양성인 비율
  • 재현율(Recall, Sensitivity): 실제 양성 중에서 모델이 양성이라고 예측한 비율
  • F1-score: 정밀도와 재현율의 조화 평균
  • AUC-ROC (Area Under the Curve - Receiver Operating Characteristic Curve): 분류 모델의 성능을 시각적으로 평가하는 방법

1.2 회귀 모델의 성능 평가 지표

회귀 문제에서는 주로 다음과 같은 지표를 사용합니다.

  • 평균 제곱 오차(Mean Squared Error, MSE): 예측값과 실제값의 차이를 제곱하여 평균낸 값
  • 평균 절대 오차(Mean Absolute Error, MAE): 예측값과 실제값의 차이의 절대값을 평균낸 값
  • R^2 Score (결정 계수): 모델이 데이터를 얼마나 잘 설명하는지 나타내는 지표

2. 성능 평가를 위한 혼동 행렬(Confusion Matrix)

분류 모델의 평가를 위해 흔히 사용되는 혼동 행렬(confusion matrix)은 예측 결과와 실제 값을 비교하여 시각적으로 나타내는 방법입니다.

실제 양성(Positive) 실제 음성(Negative)
예측 양성(Positive) TP (True Positive) FP (False Positive)
예측 음성(Negative) FN (False Negative) TN (True Negative)

이를 활용하여 정밀도, 재현율, F1-score 등의 성능 지표를 계산할 수 있습니다.

2.1 Python 코드 예제 (Confusion Matrix 시각화)

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix, classification_report
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification

# 샘플 데이터 생성
X, y = make_classification(n_samples=1000, n_features=10, n_classes=2, random_state=42)
y = to_categorical(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 간단한 모델 생성
model = Sequential([
    Dense(32, activation='relu', input_shape=(10,)),
    Dense(16, activation='relu'),
    Dense(2, activation='softmax')
])

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=10, batch_size=16, verbose=0)

# 예측 수행
y_pred = np.argmax(model.predict(X_test), axis=1)
y_true = np.argmax(y_test, axis=1)

# 혼동 행렬 계산 및 시각화
cm = confusion_matrix(y_true, y_pred)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.title("Confusion Matrix")
plt.show()

위 코드에서는 seaborn을 활용하여 혼동 행렬을 시각적으로 표현하였습니다.

3. ROC 곡선과 AUC 값 계산 및 시각화

ROC(Receiver Operating Characteristic) 곡선은 모델의 분류 성능을 평가하는 중요한 시각화 도구입니다. AUC(Area Under Curve) 값이 높을수록 모델의 성능이 우수하다고 볼 수 있습니다.

3.1 Python 코드 예제 (ROC Curve 및 AUC 시각화)

from sklearn.metrics import roc_curve, auc

# 예측 확률값 가져오기
y_probs = model.predict(X_test)[:, 1]

# ROC 커브 계산
fpr, tpr, _ = roc_curve(y_true, y_probs)
roc_auc = auc(fpr, tpr)

# ROC 커브 시각화
plt.plot(fpr, tpr, label=f'AUC = {roc_auc:.2f}')
plt.plot([0, 1], [0, 1], 'k--')
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("ROC Curve")
plt.legend()
plt.show()

위 코드를 실행하면, ROC 커브와 함께 AUC 값이 출력됩니다.

4. 학습 과정 시각화 (Loss 및 Accuracy 그래프)

모델 학습 과정에서 손실(loss)과 정확도(accuracy)의 변화를 시각화하면, 과적합 여부를 확인할 수 있습니다.

4.1 Python 코드 예제 (Loss 및 Accuracy 그래프)

history = model.fit(X_train, y_train, epochs=50, batch_size=16, validation_data=(X_test, y_test), verbose=0)

# 학습 곡선 시각화
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.title("Loss Graph")
plt.show()

plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.title("Accuracy Graph")
plt.show()

위 코드를 실행하면, 학습 과정에서 손실 및 정확도 변화가 그래프로 나타납니다.

5. 결론

딥러닝 모델의 성능을 평가하는 것은 모델 최적화와 개선을 위해 필수적인 과정입니다. 본 글에서는 주요 성능 지표와 시각화 기법을 살펴보았으며, Python 코드 예제를 통해 실습할 수 있도록 구성하였습니다. 이를 활용하여 자신이 개발한 딥러닝 모델을 효과적으로 분석하고 개선해 나갈 수 있기를 바랍니다.

728x90