2.2.3_Evaluation_Metrics _for_Classification

chang·2021년 2월 13일
0

부트캠프

목록 보기
22/28

[키워드]

  • Confusion Matrix
  • Precision, Recall, F1-score
  • Threshold
  • ROC curve, AUC

[학습내용]

  • Confusion Matrix와 여러 지표
"O""X"
OTPFN
XFPTN

O / X : 실제
"O" / "X" : O라 예측 / X라 예측

  • 정확도(Accuracy) : TP+TNTotal\frac{TP + TN}{Total}
  • 정밀도(Precision) : TPTP+FP\frac{TP}{TP + FP}
    "O" -> O <맞다고 예측했을 때 진짜 맞을 확률>
  • 재현율, 민감도(Recall, Sensitivity) : TPTP+FN\frac{TP}{TP + FN}
    O -> "O"<맞은 것들 중 맞다 예측된 확률>
  • 특이도(Specificity) = X -> "X" <아닌 것들 중 아니라 예측된 확률>
  • F1 score : 2\cdotprecisionrecallprecision+recall\frac{precision\cdot recall}{precision + recall}
# 파이프라인 이용한 모델의 confusion matrix
from sklearn.metrics import plot_confusion_matrix
import matplotlib.pyplot as plt
pcm = plot_confusion_matrix(pipe, # train set 이용 모델의 pipeline
                            X_val, y_val, # validation set 
                            values_format='d'); # e notaion 삭제

# plot_confusion_matrix 에서 테이블 데이터만 가져와 사용
pcm.confusion_matrix

# 정밀도, 재현율, f1-score 바로 구하기
from sklearn.metrics import classification_report
classification_report(y_val, y_pred)
  • ROC 커브
    x축 : False Positive Rate(FPR) = Falll-Out(위양성률)
    FPR=FPN=FPFP+TN=1TNR(Specificity){\displaystyle \mathrm {FPR} ={\frac {\mathrm {FP} }{\mathrm {N} }}={\frac {\mathrm {FP} }{\mathrm {FP} +\mathrm {TN} }}=1-\mathrm {TNR(Specificity)}}
    Specificity = X -> "X"이므로
    FPR = X ->"O"<아닌 것들 중 맞다 예측된 확률>
    y축 : Recall(재현율) = Sensitivity(민감도)
    TPR=TPP=TPTP+FN=1FNR{\displaystyle \mathrm {TPR} ={\frac {\mathrm {TP} }{\mathrm {P} }}={\frac {\mathrm {TP} }{\mathrm {TP} +\mathrm {FN} }}=1-\mathrm {FNR} }
    TPR = O -> "O"<맞는 것들 중 맞다 예측된 확률>

  • AUC : ROC curve의 아래 면적

  • Threshold : 재현율 최대화 & 위양성률 최소화

# ROC 커브 그리기
from sklearn.metrics import roc_curve

# pipe를 이용한 모형의 각 클래스에 대한 확률 by pipe.predict_proba
y_pred_proba = pipe.predict_proba(X_val)[:, 1]

# roc_curve(타겟값, prob of 1)
fpr, tpr, thresholds = roc_curve(y_val, y_pred_proba)

roc = pd.DataFrame({
    'FPR(Fall-out)': fpr, 
    'TPRate(Recall)': tpr, 
    'Threshold': thresholds
})
roc # FRP, TPR, Threshold값들

# ROC 커브 그리기 
plt.scatter(fpr, tpr)
plt.title('ROC curve')
plt.xlabel('FPR(Fall-out)')
plt.ylabel('TPR(Recall)');

# threshold 최대값의 인덱스 by np.argmax()
optimal_idx = np.argmax(tpr - fpr)
optimal_threshold = thresholds[optimal_idx]

print('idx:', optimal_idx, ', threshold:', optimal_threshold)

# optimal threshold 적용한 재예측값
y_pred_optimal = y_pred_proba >= optimal_threshold
print(classification_report(y_val, y_pred_optimal))

# AUC 구하기
from sklearn.metrics import roc_auc_score
auc_score = roc_auc_score(y_val, y_pred_proba)
auc_score

[찾아볼 내용]👀

  • ROC커브에서의 threshold 최적값의 의미
  • 위의 최적값과 precision/recall/f1-score와의 관계

0개의 댓글