#!/usr/bin/env python3


불확실성 고려


confusion matrix와 classifier report는 예측 결과를 자세히 분석할 수 있도록 도와줍니다.

하지만 예측값은 model에 담긴 많은 정보가 이미 손실된 상태입니다.

대부분의 classifier는 확신을 가늠하기 위한 decision_function이나 predict_proba 메소드를 제공합니다.

예측을 만들어내는 것은 decision_function, predict_proba 출력의 critical value를 검증하는 것입니다.


binary search에서 decision_function은 0, predict_proba는 0.5를 critical value로 사용합니다.


다음 예는 음성 클래스 데이터 포인트 400개와 양성 클래스 데이터 포인트 50개로 이뤄진 불균형 데이터셋의 classifier report입니다.

from mglearn.plots import plot_decision_threshold

import matplotlib.pyplot as plt


plot_decision_threshold()

plt.show()

decision function의 heatmap과 critical value 변화에 따른 영향



classification_report 함수를 사용해서 두 클래스의 정밀도와 재현율을 평가해보겠습니다.

from mglearn.datasets import make_blobs

from sklearn.model_selection import train_test_split

from sklearn.svm import SVC

from sklearn.metrics import classification_report


x, y = make_blobs(n_samples=(400, 50), centers=2, cluster_std=[7, 2], random_state=22)

x_train, x_test, y_train, y_test = train_test_split(x, y, stratify=y, random_state=22)

svc = SVC(gamma=0.5) # degree=3, C=1, gamma='auto', kernel='rbf'

svc.fit(x_train, y_train)


rpt_result = classification_report(y_test, svc.predict(x_test))

print('{}'.format(rpt_result))

#              precision    recall  f1-score   support


#           0       0.92      0.91      0.91       100

#           1       0.36      0.38      0.37        13


# avg / total       0.85      0.85      0.85       113

클래스 1에 대해 36%, 재현율은 38%입니다. class 0의 샘플이 매우 많으므로 classifier는 class 0에 초점을 맞추고 있습니다.


만약 class 1의 재현율을 높이는게 중요하다고 가정하면

class 1로 잘못분류된 FP(False Positive)보다 TP(True Positive)를늘려야 한다는 뜻입니다.

svc.predict로 만든 예측은 이 조건을 만족하지 못했지만 critical value를 조정하여 class 1의 재현율을 높이도록 예측을 조정할 수 있습니다.


기본적으로 decision_function의 값이 0보다 크면 class 1로 분류 됩니다. 더 많은 데이터 포인트가 class 1로 분류되려면 critical value를 낮춰야 합니다.

y_pred_lower_threshold = svc.decision_function(x_test) > -0.8

rpt_result_adj = classification_report(y_test, y_pred_lower_threshold)

print('{}'.format(rpt_result_adj))

#              precision    recall  f1-score   support


#           0       0.94      0.87      0.90       100

#           1       0.35      0.54      0.42        13


# avg / total       0.87      0.83      0.85       113

class 1의 정밀도는 낮아졌지만 재현율은 높아졌습니다.


간단한 예제를 위해 test set의 결과를 바탕으로 critical value를 선택했습니다.

실제로는 test set를 사용하면 안되며, 다른 parameter처럼 test set에서 decision critical value를 선택하면 과도하게 낙관적인 결과가 나옵니다. 대신에 검증세트나 교차 검증을 사용해야 합니다.



참고 자료: 

[1]Introduction to Machine Learning with Python, Sarah Guido

+ Recent posts