ML
혼동 행렬(Confusion matrix)
Haribo-
2022. 11. 24. 20:30
혼동 행렬(Confusion matrix)
혼동 행렬(Confusion matrix)은 분류 문제에서 모델을 학습시킨 뒤, 모델에서 데이터의 X값을 집어넣어 얻은 예상되는 y값과, 실제 데이터의 y값을 비교하여 정확히 분류 되었는지 확인하는 메트릭(metric)이라고 할 수 있습니다.

위 표가 바로 혼동 행렬이며, 각 표에 속한 값은 다음을 의미합니다.
- True Positive (TP) : 실제 값은 Positive, 예측된 값도 Positive.
- False Positive (FP) : 실제 값은 Negative, 예측된 값은 Positive.
- False Negative (FN) : 실제 값은 Positive, 예측된 값은 Negative.
- True Negative (TN) : 실제 값은 Negative, 예측된 값도 Negative.
sklearn 안에는 위 4개 평가 값을 얻기 위해 사용할 수 있는 기능이 정의되어 있습니다.
이번 실습에서는 2개의 클래스를 가진 분류 데이터를 이용하여 혼동 행렬을 직접 출력해보고,확인해보도록 하겠습니다.
혼동 행렬을 위한 사이킷런 함수/라이브러리
- confusion_matrix(y_true, y_pred)
: Confusion matrix의 값을 np.ndarray로 반환해줍니다.
데이터 정보
load_breast_cancer 유방암 유무 판별 데이터를 불러오는 함수
- X(Feature 데이터) : 30개의 환자 데이터
- Y(Label 데이터) : 0 음성(악성), 1 양성(정상)
지시사항
- confusion_matrix를 사용하여 test_Y에 대한 confusion matrix를 계산하여 cm에 저장해봅시다.
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from elice_utils import EliceUtils
elice_utils = EliceUtils()
# sklearn에 저장된 데이터를 불러 옵니다.
X, Y = load_breast_cancer(return_X_y = True)
X = np.array(X)
Y = np.array(Y)
# 데이터 정보를 출력합니다
print('전체 샘플 개수: ',len(X))
print('X의 feature 개수: ',len(X[0]))
# 학습용 평가용 데이터로 분리합니다
train_X, test_X, train_Y, test_Y = train_test_split(X, Y, test_size=0.2, random_state = 42)
# 분리된 평가용 데이터 정보를 출력합니다
print('평가용 샘플 개수: ',len(test_Y))
print('클래스 0인 평가용 샘플 개수: ',len(test_Y)-sum(test_Y))
print('클래스 1인 평가용 샘플 개수: ',sum(test_Y),'\n')
# DTmodel에 의사결정나무 모델을 초기화 하고 학습합니다
DTmodel = DecisionTreeClassifier()
DTmodel.fit(train_X, train_Y)
# test_X을 바탕으로 예측한 값을 저장합니다
y_pred = DTmodel.predict(test_X)
"""
1. 혼동 행렬을 계산합니다
"""
cm = confusion_matrix(test_Y, y_pred) # confusion_matrix() 를 활용하여 혼동행렬을 계산합니다.
print('Confusion Matrix : \n {}'.format(cm))
# 혼동 행렬을 출력합니다
fig = plt.figure(figsize=(5,5))
ax = sns.heatmap(cm, annot=True)
ax.set(title='Confusion Matrix',
ylabel='True label',
xlabel='Predicted label')
fig.savefig("decistion_tree.png")
elice_utils.send_image("decistion_tree.png")
전체 샘플 개수: 569
X의 feature 개수: 30
평가용 샘플 개수: 114
클래스 0인 평가용 샘플 개수: 43
클래스 1인 평가용 샘플 개수: 71
Confusion Matrix :
[[39 4]
[ 4 67]]