[python] scikit-learn을 사용한 ROC 곡선 그리기

scikit-learn은 파이썬에서 머신러닝 모델을 만들고 평가하는 데 사용되는 인기있는 라이브러리입니다. 이 라이브러리를 사용하여 ROC 곡선(Receiver Operating Characteristic curve)을 그릴 수 있습니다.

ROC 곡선은 이진 분류 모델의 성능을 평가하는 데 사용됩니다. 이 곡선은 거짓 양성 비율(FPR)에 대한 진짜 양성 비율(TPR)의 그래프입니다. FPR은 실제로는 음성인데 모델이 양성으로 예측한 비율이며, TPR은 실제로 양성인데 모델이 정확하게 양성으로 예측한 비율입니다.

다음은 scikit-learn을 사용하여 ROC 곡선을 그리는 예제 코드입니다:

import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, roc_auc_score

# 데이터 생성
X, y = make_classification(n_samples=1000, n_features=10, random_state=42)

# 훈련 및 테스트 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 로지스틱 회귀 모델 생성 및 학습
model = LogisticRegression()
model.fit(X_train, y_train)

# 테스트 데이터에 대한 예측 확률 구하기
y_pred_proba = model.predict_proba(X_test)[:, 1]

# ROC 곡선을 그리기 위해 FPR, TPR, 임계값 계산
fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba)

# ROC 곡선 그리기
plt.plot(fpr, tpr)
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve')
plt.grid(True)
plt.show()

# AUC(Area Under the Curve) 출력
auc_score = roc_auc_score(y_test, y_pred_proba)
print('AUC:', auc_score)

위 코드에서는 먼저 make_classification 함수를 사용하여 가상의 분류 데이터를 생성합니다. 그런 다음 생성된 데이터를 훈련 세트와 테스트 세트로 분할하고, 로지스틱 회귀 모델을 생성하고 학습시킵니다.

학습된 모델을 사용하여 테스트 데이터에 대한 예측 확률을 구하고, roc_curve 함수를 사용하여 FPR, TPR, 그리고 해당 임계값을 계산합니다. 이를 바탕으로 ROC 곡선을 그리고 AUC 값을 계산하여 출력합니다.

이와 같이 scikit-learn을 사용하여 ROC 곡선을 그릴 수 있습니다. 이 곡선은 모델의 성능을 시각화하여 비교하는 데 유용하며, 모델의 임계값 설정에도 도움이 됩니다.

코드 예제 출처: https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html