Matplotlib 혼동 행렬 그리 기

기계 학습 의 다 분류 모델 에 대해 말하자면 그 평가 지 표 는 정밀 도 를 제외 하고 자주 사용 하 는 혼동 행렬 과 분류 보고서 도 있다.다음은 혼동 행렬 을 어떻게 그 리 는 지 보 여 준다.이것 은 논문 에서 자주 사용 된다.
코드 는 다음 과 같 습 니 다:

import itertools
import matplotlib.pyplot as plt
import numpy as np
#       
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
    """
    - cm :           
    - classes :                
    - normalize : True:     , False:    
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("     :")
        np.set_printoptions(formatter={'float': '{: 0.2f}'.format})
        print(cm)
    else:
        print('      :')
        print(cm)
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)
    # matplotlib    ,          ,                ,     matplotlib        ,       
    plt.ylim(len(classes) - 0.5, -0.5)
    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show()
테스트 데이터:

cnf_matrix = np.array([[8707, 64, 731, 164, 45],
                      [1821, 5530, 79, 0, 28],
                      [266, 167, 1982, 4, 2],
                      [691, 0, 107, 1930, 26],
                      [30, 0, 111, 17, 42]])
attack_types = ['Normal', 'DoS', 'Probe', 'R2L', 'U2R']
첫 번 째 상황:백분율 표시

plot_confusion_matrix(cnf_matrix, classes=attack_types, normalize=True, title='Normalized confusion matrix')
효과:
在这里插入图片描述
在这里插入图片描述
두 번 째 상황:숫자 표시

plot_confusion_matrix(cnf_matrix, classes=attack_types, normalize=False, title='Normalized confusion matrix')
효과:
在这里插入图片描述
在这里插入图片描述
여기 서 Matplotlib 가 헷 갈 리 는 행렬 을 그 리 는 실현 에 관 한 글 은 여기까지 소개 되 었 습 니 다.더 많은 관련 Matplotlib 헷 갈 리 는 행렬 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 부 탁 드 리 겠 습 니 다!

좋은 웹페이지 즐겨찾기