교차 검증의 정확도를 알 수 있는 함수의 종류는 다음과 같다.
분류 모델의 예측 결과와 실제값을 비교하여 행렬 형태로 나타낸 것을 Confusion Matrix(혼동 행렬)이라고 한다. 이는 분류 모델의 성능 평가 지표가 되며 최적화에 중요한 역할을 한다.
Confusion Matrix는 다음과 같이 4개의 값으로 구성된다.
Confusion Matrix를 바탕으로 다양한 분류 성능 평가 지표를 계산할 수 있다. 그 중에서 가장 많이 사용되는 평가 지표는 정확도, 정밀도, 재현율, F1 score, AUC, ROC curve 등이 있다.
from sklearn.metrics import accuracy_score
accuracy = accuraycy_score(y_true, y_pred)
print('Accuracy:', accuracy)
from sklearn.metrics import precision_score
precision = precision_score(y_true, y_pred)
print('Precision:', precision)
from sklearn.metrics import recall_score
recall = recall_score(y_true, y_pred)
print('Recall:', recall)
참고) Binarizer
sklearn.preprocessing.Binarizer(*, threshold=0.0, copy=True)
- 데이터를 0 또는 1로 이진화할 시에 Binarize()함수는 임계값 보다 큰 값은 1, 작은 값은 0에 mapping된다.
- threshold parameter를 통해 임계값을 지정하며 0.0이 default이다.
- copy parameter는 True가 default이다. 만약 False로 지정한다면 원본 데이터(array)자체가 이항변수화 변환 후의 값으로 교체되어버린다.
binarizer = Binarizer(threshold=2.0) In[9]: x = array([[10,-10,1], [5.0.2], [0,10,3]]) In[10]: binaizer.transform(X)
- 코드 실행 시 threshold가 default값인 0.0에서 2.0으로 지정되었으므로 결과는 다음과 같이 된다. ```python out[10]: array([[1,0,0], [1.0.0], [0,1,1]])
from sklearn.metrics import f1_score
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
# 모델 예측 결과와 실제 결과가 있는 리스트를 생성
y_pred = [0.1, 0.3, 0.5, 0.2, 0.7, 0.8, 0.4, 0.9, 0.6, 0.7]
y_true = [0, 1, 1, 0, 1, 1, 0, 1, 0, 1]
# fpr, tpr, thresholds 계산
fpr, tpr, thresholds = roc_curve(y_true, y_pred)
# AUC 계산
roc_auc = auc(fpr, tpr)
# ROC Curve 그리기
plt.figure(figsize=(8,8))
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic Curve')
plt.legend(loc="lower right")
plt.show()