데이터분석/데이터분석

혼동행렬, ROC, AUC

이규승 2022. 5. 11. 21:36
728x90
  예측 값
실제 값   Y N
Y TP (True Positive) FN (False Negative)
N FP (False Positive) TN (True Negative)

 

출처 : https://cafe.daum.net/flowlife/SBU0/32

ROC와 AUC : https://bioinfoblog.tistory.com/221

 

[용어 설명] ROC curve와 AUC란?

ROC (Receiver Operating Characteristic) curve란 FPR (False positive rate)과 TPR (True Positive Rate)을 각각 x, y축으로 놓은 그래프이다. TPR과 FPR은 다음과 같이 정의된다. TPR (True Positive Rate): 1..

bioinfoblog.tistory.com

ROC(Receiver Operating Characteristic) curve는 다양한 threshold에 대한 이진분류기의 성능을 한번에 표시한 것이다.
이진 분류의 성능은 True Positive Rate와 False Positive Rate 두 가지를 이용해서 표현하게 된다.
ROC curve를 한 마디로 이야기하자면 ROC 커브는 좌상단에 붙어있는 커브가 더 좋은 분류기를 의미한다고 생각할 수 있다.

 

AUC (Area Under the ROC Curve)는 ROC curve의 밑면적을 말한다. 
즉, 성능 평가에 있어서 수치적인 기준이 될 수 있는 값으로, 1에 가까울수록 그래프가 좌상단에 근접하게 되므로 좋은 모델이라고 할 수 있다.

import numpy as np
import pandas as pd

# 분류 연습용 샘플 데이터 작성
from sklearn.datasets import make_classification
x, y = make_classification(100, n_features = 2, n_redundant=0, random_state = 123)

# 로지스틱 회귀모델
from sklearn.linear_model import LogisticRegression
model = LogisticRegression().fit(x,y)
y_hat = model.predict(x)

f_value = model.decision_function(x) # 결정함수(판별함수) : 불확실성 추정함수 - 판별 경계선 설정을 위함
df = pd.DataFrame(np.vstack([f_value, y_hat, y]).T, columns=['f','y_hat','y'])
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
f_value: [-0.28578195 -0.94087863 -4.23244981  2.80427449  0.06138614  2.88533064
 -2.10954403 -1.76264928 -0.93090557  2.98570924]
          f  y_hat    y
0 -0.285782    0.0  1.0
1 -0.940879    0.0  0.0
2 -4.232450    0.0  0.0

# 혼동행렬
from sklearn.metrics import confusion_matrix
print(confusion_matrix(y, y_hat))
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
[[44  4]
 [ 8 44]]
 
# 혼동행렬로 acc, recall 등 구하기
acc = (44 + 44)/ 100 # TP + TN / 전체수 정확도
recall = 44 / (44 + 4) # TP / TP + FN 재현율, 민감도 tpr
specificity = 44 / (44 + 8) # TN / FP + TN  특이도
fallout = 8 / (8 + 44) # FP / (FP + TN) 위양성률 fpr

# metrics로 구하기
from sklearn import metrics
ac_sco = metrics.accuracy_score(y, y_hat)
cl_rep = metrics.classification_report(y, y_hat)

# metrics로 roc curve 구하기
fpr, tpr, thresholds = metrics.roc_curve(y, model.decision_function(x))

# roc curve 시각화
import matplotlib.pyplot as plt
plt.plot(fpr, tpr, 'o-', label = 'LogisticRegression')
plt.plot([0,1],[0,1], 'k--', label = 'random classifier line(AUC:0.5)') #선
plt.plot([fallout],[recall],'r+',ms=20)#재현율, 위양성율
plt.xlabel('fpr')
plt.ylabel('tpr')
plt.title('ROC curve')
plt.legend()
plt.show()

# AUC구하기
print('AUC : ', metrics.auc(fpr, tpr))

 

728x90