"The important thing isn't can you read music, it's can you hear it.
Can you hear the music, Robert?
Classfication Model Evaluation Metric
- 정확도(Accuracy)
- 오차행렬(Confusion Matrix)
- 정밀도(Precision)
- 재현율(Recall)
- F1 스코어
- ROC AUC
> 위에 나열된 성능지표들은 대체로 이진분류에서 더 강조하는 지표들
Accuracy
"실제 데이터와 예측 데이터가 얼마나 같은가?" 를 표현한 하는 판단 지표
그러나 정확도는 데이터셋의 분포에 따라 왜곡을 발생시킬 수 도 있다.
특히 데이터 분포도가 균일하지 않은 경우 높은 수치가 나타날 수 있는 것이 정확도 평가 지표의 맹점이다.
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.base import BaseEstimator
from sklearn.metrics import accuracy_score
import numpy as np
import pandas as pd
#모두 0(False)로 예측하는 dummy classifier
class FakeClassifier(BaseEstimator):
def fit(self, X, y):
pass
def predict(self, X):
return np.zeros( (len(X), 1), dtype = bool)
digits = load_digits()
#digits에서 7만 True이고 이를 1로 변환, 나머지는 0
y = (digits.target == 7).astype(int)
X_train, X_test, y_train, y_test = train_test_split(digits.data, y, random_state =11)
clf = FakeClassifier()
clf.fit(X_train, y_train)
pred = clf.predict(X_test)
print(accuracy_score(y_test, pred))
>> 0.9
대부분의 데이터가 False이기 때문에, 0만 리턴하는 예측 모델의 정확도가 높게 나옴
(불균형한 데이터셋에서 정확도가 가지는 왜곡)
이처럼 정확도 평가 지표는 불균형한 레이블 데이터 세트에서는 성능 수치로 사용돼서는 안 된다.
오차행렬/혼동행렬(Confusion Matrix)
sklearn.metrics의 confusion_matrix를 통해서 호출 할 수 있다.
from sklearn.metrics import confusion_matrix
#앞에서 만든 예측 모델에 대한 혼동 행렬을 출력
confusion_matrix(y_test, pred)
array([[405, 0],
[ 45, 0]])
정밀도와 재현율(Precision & Recall)
▶ Positive로 정확하게 예측한 TP값에 초점을 맞춘 평가 지표!
정밀도 : Precision = TP / (FP + TP)
전체 Positive로 예측한 결과 중 TP의 비율
재현율 : Recall = TP / (FN + TP)
전체 Positive 데이터 중 TP의 비율
- Precision(정밀도)가 상대적으로 더 중요한 지표인 경우는 실제 Negative 음성인 데이터 예측을 Positive 양성으로 잘못 판단하게 되면 업무 상 큰 영향이 발생하는 경우 (금융사기 적발 모델)
- Recall(재현율)이 상대적으로 더 중요한 지표인 경우 실제 Positivie 양성인 데이터 예측을 Negativie로 잘못 판단하게 되면 업무 상 큰 영향이 발생하는 경우 (암 진단)
확실한 환자만 양성 나머지는 전부 음성으로 예측 -> 100%의 정밀도
모든 환자를 양성으로 예측 → 100%의 재현율
F1 스코어
▶ 정밀도와 재현율을 결합한 지표(정밀도와 재현률의 조화 평균이다)
조화평균(Harmonic mean) : 조화 평균(調和平均)은 주어진 수들의 역수의 산술 평균의 역수를 말한다. 평균적인 변화율을 구할 때에 주로 사용된다.https://en.wikipedia.org/wiki/Harmonic_mean
Harmonic mean - Wikipedia
From Wikipedia, the free encyclopedia Inverse of the average of the inverses of a set of numbers In mathematics, the harmonic mean is one of several kinds of average, and in particular, one of the Pythagorean means. It is sometimes appropriate for situatio
en.wikipedia.org
★ Test Set은 마지막에 모델을 출시하기 직전에 사용하기 위한 데이터 셋이다.
모델의 성능 검증을 위한 용도에서는 부적절함
▶ 모델을 조정하는 과정에서는 "모델이 훈련하는 동안 보지 못했던 데이터에 대한 예측, 깨끗한 예측"을 이용하는 것이 중요하다
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import confusion_matrix
#cross_val_predict으로 k-Fold cross valuation를 시행 후, 그 예측 값을 반환
y_train_pred = cross_val_predict(sgd_clf, X_train, y_train, cv =3)
confusion_matrix(y_train, y_train_pred)
https://medium.com/all-about-ml/evaluation-metrics-in-classification-algorithms-79c036a131cb
'Datascience' 카테고리의 다른 글
Ensemble 2: AdaBoosting과 GradientBoosting (0) | 2024.01.06 |
---|---|
Ensemble 1: 앙상블 학습과 랜덤 포레스트 (0) | 2024.01.03 |
Trading Off Precision and Recall(정밀도와 재현률 트레이드 오프) (1) | 2024.01.01 |
Data Preprocessing : Label Encoding * One hot Encoding (0) | 2023.12.29 |
Skit- Learn의 기반 프레임워크 익히기 (0) | 2023.12.29 |