Tree Based Model(3) - Evaluation Metrics for Classification
2021. 3. 7. 15:38ㆍ[AI]/Machine Learning
Learned Stuff
Key Points
- Confusion Matrix
- Evaluation Metrics
- Accuracy
- Precision
- Recall
- ROC Curve & AUC Score
New Stuff
[Confusion Matrix]
- 만든 Model의 예측값과 실제값간의 관계를 보여주는 Matrix 형태의 그림이라고 볼 수 있습니다.
- True Positive : 예측 = 1 / 실제 = 1
- True Negative : 예측 = 0 / 실제 = 0
- False Positive : 예측 = 1 / 실제 = 0 (Type 1 Error)
- False Negative : 예측 = 0 / 실제 = 1 (Type 2 Error)
Diagram
Code
from sklearn.metrics import plot_confusion_matrix
# pipeline으로 만든 'model' 이 있다고 가정
# X_validation을 model에 돌린 예측값 & y_validation의 실제값과 비교
fig, ax = plt.subplots()
pcm = plot_confusion_matrix(model, X_validation, y_validation,
cmap=plt.cm.Blues,
ax=ax,
values_format='d');
plt.title(f'Confusion matrix, n = {len(y_validation)}', fontsize=13);
# 아래와 같이 뜬다
[Evaluation Metrics]
Accuracy
- $\frac{TP + TN}{TP + TN + FP + FN}$
- 예측한 것 중 실제값과 일치하는 비율
Precision
- $\frac{TP}{TP + FP}$
- 1 이라고 예측한 것 중 올바르게 1로 맞춘 비율
Recall
- $\frac{TP}{TP + FN}$
- 실제로 1 인 것 중 올바르게 1로 맞춘 비율
Code
from sklearn.metrics import classification_report
# y_validation(실제값) / model로 도출해낸 y_validation_predicted(예측값)이 있다고 가정
print(classification_report(y_validation, y_validation_predicted))
# 아래와 같이 뜬다
Explanation
-
윗 부분
- 각 class (0 / 1) 별 지표가 나옵니다.
-
F1-score : $2\times \frac{Precision \times Recall}{Precision + Recall}$
- Recall & Precision 의 harmonic mean
- Support : 실제값의 갯수를 의미
-
아랫 부분
-
macro avg : class (0 / 1) 별 지표의 평균을 의미
- ex) macro average of Precision
- $0.5 \times 0.8508 + 0.5 \times 0.7207 = 0.7858$
- ex) macro average of Precision
-
weighted avg : weight impurity 와 비슷한 개념 (각 class의 비중을 고려한다)
- ex) weighted average of Precision
- $\frac{6395}{6395+1975} \times 0.8508 + \frac{1975}{6395+1975} \times 0.7207 = 0.8201$
- ex) weighted average of Precision
-
[ROC Curve & AUC Score]
- ROC (Receiver Operating Characteristic) Curve : TPR & FPR의 관계를 나타내는 그래프
- AUC (Area Under Curve) Score : ROC Curve의 아래 면적을 의미
- Classification 문제에 threshold값을 조정해 model의 성능을 개선할 수 있습니다.
- Recall : True Positive Rate (TPR) = $\frac{TP}{TP + FN}$
- Fall-Out : False Positive Rate (FPR) = $\frac{FP}{FP + TN}$
- TPR 은 최대가 되고 FPR은 최소로 만드는 threshold 값이 최적 threshold 값입니다.
- 분류가 잘 안 된 data set 일 경우 유용합니다.
Cases
- Case 1. 분류가 잘 된 경우 (TP & TN 만 존재) - 가장 ideal 한 model
- Class 1 이 나올 확률이 0.5 보다 이상이면 Class 1로 predict
- Class 0 이 나올 확률이 0.5 보다 이하이면 Class 0로 predict
Confusion Matrix
Visualization
Diagram | ROC Curve & AUC Score |
---|---|
![]() |
![]() |
- Case 2. 분류가 어느 정도 된 경우 (TP & TN & FP & FN 존재)
- threshold 조정 해주어야 함
Visualization
Diagram | ROC Curve & AUC Score |
---|---|
![]() |
![]() |
- Case 3. 분류가 아예 안되는 경우 - worse case
Visualization
Diagram | ROC Curve & AUC Score |
---|---|
![]() |
![]() |
Example
- class 1 이 나올 확률에 관한 histogram
- 확률이 오를수록 counts 가 낮아지는 것을 알 수 있습니다.
- 이 뜻은 대부분의 예측값이 0 이라는 의미이기도 합니다.
- 확률이 0.3~0.5 구간의 counts 를 보면 확률이 0.5 이상인 구간의 counts와 차이가 크지 않습니다.
- 따라서 threshold를 낮춰주어 보다 분류를 잘 할 수 있도록 만들어주어야 합니다.
Code
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score
# best model 은 pipeline을 통해 만든 fit한 model
# X_validation data / y_validation data 가 있다고 가정
# fpr / tpr / threshold 담기
# class 1 에 대한 확률 예측값 담기
y_validation_proba = best_model.predict_proba(X_validation)[:,1]
fpr, tpr, thresholds = roc_curve(y_true = y_validation, y_score = y_validation_proba)
# auc score 값 반환 (1에 가까울수록 분류가 잘 된 model)
roc_auc_score(y_true = y_validation,y_score = y_validation_proba)
# optimal threshold 찾기
# tpr - fpr 중 가장 큰 값의 index 반환
optimal_idx = np.argmax(tpr - fpr)
# 최적 threshold 반환
optimal_threshold = thresholds[optimal_idx]
# optimum threshold을 반영한 validation data의 predicted array 구하기
# optimal_threshold 보다 높으면 True / 낲으면 False
y_validation_optimal_T_or_F = y_validation_proba >= optimal_threshold
# True면 1 / False면 0 반환
y_validation_pred = np.array(y_validation_optimal_T_or_F).astype(int)
# 위 prediction을 가지고 y_validation(실제값) 과 비교해보고 성능의 개선이 있다면 test data 에도 optimal_threshold 적용
728x90
'[AI] > Machine Learning' 카테고리의 다른 글
Tree Based Model(1) - Decision Trees (0) | 2021.03.07 |
---|---|
Tree Based Model(2) - Random Forests (0) | 2021.03.07 |
Tree Based Model(4) - Model Selection (0) | 2021.03.07 |
Applied Predictive Modeling(1) - Choosing ML Problems (0) | 2021.03.07 |
Applied Predictive Modeling(2) - Data Wrangling (0) | 2021.03.07 |