2024. 3. 27. 00:11ㆍDATA/BIGDATA
ROC(Receiver Operating Characteristic) 곡선은 이진 분류 모델의 성능을 평가하는 데 사용되는 그래픽 표현 방법 중 하나이다.
■ ROC 곡선은 다음과 같은 두 가지 주요 지표를 시각화하여 분류 모델의 성능을 평가한다:
민감도(Sensitivity) 또는 재현율(Recall): 실제 양성 중 모델이 양성으로 올바르게 예측한 비율을 나타낸다. 민감도는 \( \frac{TP}{TP + FN} \) 으로 계산된다.
특이도(Specificity): 실제 음성 중 모델이 음성으로 올바르게 예측한 비율을 나타낸다. 특이도는 \( \frac{TN}{TN + FP} \) 으로 계산된다.
ROC 곡선은 민감도(재현율)를 y축에, 1-특이도(거짓 양성 비율, False Positive Rate)를 x축에 표시하여 각각의 분류 임계값에서 모델의 성능을 시각화한다. 이 곡선 아래의 면적(Area Under the ROC Curve, AUC)이 클수록 모델의 성능이 더 우수하다.
ROC 곡선이 좌측 상단으로 치우칠수록 모델의 성능이 좋은 것으로 간주된다. 반대로, ROC 곡선이 대각선(y=x 선)에 가까울수록 모델의 성능이 무작위 추측과 다름없음을 의미한다. AUC 값이 1에 가까울수록 완벽한 분류 성능을 나타내고, 0.5에 가까울수록 분류 모델이 무작위로 예측하는 것과 동일한 성능을 나타내며 AUC 값은 0.5 이상이어야 유의미한 분류 성능을 갖는 것으로 평가된다.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
# 타이타닉 데이터셋 불러오기
url = "https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/stuff/titanic.csv"
titanic = pd.read_csv(url)
# 데이터 확인 - 처음 5개의 행 출력
print(titanic.head())
# 데이터 전처리
titanic['Age'].fillna(titanic['Age'].median(), inplace=True)
# 범주형 변수 처리 (원핫 인코딩)
titanic = pd.get_dummies(titanic, columns=['Sex'], drop_first=True)
# Feature 선택
X = titanic[['Pclass', 'Age', 'Siblings/Spouses Aboard', 'Parents/Children Aboard', 'Fare', 'Sex_male']]
y = titanic['Survived']
# 데이터셋 분리
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 모델 학습
model = LogisticRegression()
model.fit(X_train, y_train)
# 테스트 데이터에 대한 예측 확률 계산
y_pred_prob = model.predict_proba(X_test)[:, 1]
# ROC 곡선 계산
fpr, tpr, thresholds = roc_curve(y_test, y_pred_prob)
roc_auc = auc(fpr, tpr)
# ROC 곡선 그리기
plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr, color='blue', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='red', lw=2, linestyle='--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic (ROC) Curve')
plt.legend(loc='lower right')
plt.grid(True)
plt.show()
'DATA > BIGDATA' 카테고리의 다른 글
Jaccard Distance (0) | 2024.03.28 |
---|---|
t 통계량과 F 통계량을 분석함으로써 알고자하는 결과 (0) | 2024.03.27 |
MSE, RMSE (0) | 2024.03.26 |
회귀분석모델과 결정계수 (0) | 2024.03.21 |
t-statistic , p-value (0) | 2024.03.20 |