본문 바로가기
PYTHON/빅데이터분석기사

ML_03 (classification s3-25 이항 분류 모델의 성능평가)

by 쿠룽지 2023. 11. 14.
728x90
반응형
728x90

 

 

이항/ 다항 분류 개념 참고 블로그

 

[고찰] 이항분류와 다항분류에 대하여 (tistory.com)

 

[고찰] 이항분류와 다항분류에 대하여

오늘은 이항분류와 다항분류에 대해 살펴보려고 한다. 먼저 이항분류 라고 하는 것을 살펴보자.데이터 집단에 선을 하나 쫘악~그어서, 그 선을 기준으로, 데이터의 종류를 나누게 되는데, 주로

mons1220.tistory.com

 

 

 

 

 

이항 분류 모델의 성능 평가

  • sklearn.metrics.accuracy_score(y_true, y_pred) = (TP/TN) / (TP+TN+FP+FN)
  • sklearn.metrics.precision_score(y_true, y_pred) = TP / (TP + FP)
  • sklearn.metrics.recall_score(y_true, y_pred) = TP / (TP + FN)
  • sklearn.metrics.f1_score(y_true, y_pred = 2 * (Precison * Recall) / (Precision + Recall)

 

예제

#성능 평가 관련 함수
from sklearn.metrics import confusion_matrix, precision_score, recall_score, accuracy_score, f1_score
import numpy as np

#실제값
y_true = np.array([0, 1, 0, 0])   # 0 : 3개, 1 : 1개, 불균형한 데이터인 경우
#예측값
y_pred = np.array([0, 1, 1, 0])

#표
cm = pd.DataFrame(confusion_matrix(y_true, y_pred))
print(cm)


# accuracy: 전체에서 맞춘 것의 비율 3/4
print('accuracy  : %.2f' % accuracy_score(y_true, y_pred))
# precision: positive로 예측한 것 중 맞춘 것 1/2
print('precision : %.2f' % precision_score(y_true, y_pred))
# recall: 실제 positive(1) 중 맞춘 것 1/2
print('recall   : %.2f' % recall_score(y_true, y_pred))
# f1: precision, recall의 조화 평균
print('f1_score : %.2f' % f1_score(y_true, y_pred))

 

 

 

#2회 기출 데이터 사용한 성능 출력 함수 만들기
def get_other_scores(model, xtest, ytest):
  ##중요 내용!
  #네가지 값을 구하기 위해서는 predict값 필요 (예측/실제 값으로 구하니까)
  y_pred = model.predict(xtest)
  
  accuracy = accuracy_score(ytest, y_pred)
  precision = precision_score(ytest, y_pred)
  recall = recall_score(ytest, y_pred)
  f1 = f1_score(ytest, y_pred)
  
  print(f'accuracy  : {accuracy:7.4f}')
  print(f'precision : {precision:7.4f}')
  print(f'recall    : {recall:7.4f}')
  print(f'f1        : {f1:7.4f}')
  
  
  
#DecisionTreeClassifier - max_depth를 5로 했을 경우
model = DecisionTreeClassifier(max_depth=5, random_state=0).fit(xtrain1, ytrain1)
print('final model', get_scores(model, xtrain1, xtest1, ytrain1, ytest1))
get_other_scores(model, xtest1, ytest1)


#DecisionTreeClassifier - max_depth를 4로 했을 경우
model = DecisionTreeClassifier(max_depth=4, random_state=0).fit(xtrain1, ytrain1)
print('final model', get_scores(model, xtrain1, xtest1, ytrain1, ytest1))
get_other_scores(model, xtest1, ytest1)

 

 

728x90
반응형