🌌 Deep Learning/평가

Python으로 Multiclass sensitivity, specificity 계산하기

복만 2021. 10. 14. 21:04

Multiclass 문제의 경우 sensitivity(민감도)와 specificity(특이도)를 각 class마다 계산해야 한다.

 

sklearn.metrics.confusion_matrix를 이용해 각 class의 sensitivity와 specificity를 계산할 수 있다.

 

from sklearn.metrics import confusion_matrix

y = y.argmax(axis=-1)
y_pred = y_pred.argmax(axis=-1)

y_i = np.where(y==y_class, 1, 0)
y_pred_i = np.where(y_pred==y_class, 1, 0)
cfx = confusion_matrix(y_i, y_pred_i)

 

y_iy_pred_iy_class에 속하는 sample은 1로, 아닌 sample은 0으로 바꾸어 binary class로 바꾸어 준 것이다.

 

cfxy_iy_pred_i의 confusion matrix로, 2*2 matrix이다.

 

 

cfx를 이용해 다음과 같이 sensitivity와 specificity를 계산할 수 있다.

 

sensitivity = cfx[0,0]/(cfx[0,0]+cfx[0,1])
specificity = cfx[1,1]/(cfx[1,0]+cfx[1,1])

 


 

다음과 같이 각 class의 sensitivity와 specificity를 계산하여 출력할 수 있다.

 

from sklearn.metrics import confusion_matrix

def sensitivity_specificity_per_class(y, y_pred, y_class):
    y = y.argmax(axis=-1)
    y_pred = y_pred.argmax(axis=-1)
    y = np.where(y==y_class, 1, 0)
    y_pred = np.where(y_pred==y_class, 1, 0)
    cfx = confusion_matrix(y, y_pred)
    sensitivity = cfx[0,0]/(cfx[0,0]+cfx[0,1])
    specificity = cfx[1,1]/(cfx[1,0]+cfx[1,1])
    return sensitivity, specificity
    
for i in range(y.shape[-1]):
    sensitivity, specificity = sensitivity_specificity_per_class(y, y_pred, i)
    print('sensitivity:', sensitivity)
    print('specificity:', specificity)
반응형

'🌌 Deep Learning > 평가' 카테고리의 다른 글

T test 와 P value  (0) 2021.10.28
Nested cross validation  (2) 2021.10.01