對于機器學(xué)習(xí)多分類模型來說,其評價指標(biāo)除了精度之外,常用的還有混淆矩陣和分類報告,下面來展示一下如何繪制混淆矩陣,這在論文中經(jīng)常會用到。
代碼如下:
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 : 混淆矩陣中每一行每一列對應(yīng)的列 - normalize : True:顯示百分比, False:顯示個數(shù) """ 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('顯示具體數(shù)字:') 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()
測試數(shù)據(jù):
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')
效果:
到此這篇關(guān)于Matplotlib繪制混淆矩陣的實現(xiàn)的文章就介紹到這了,更多相關(guān)Matplotlib 混淆矩陣內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:駐馬店 山東 成都 六盤水 宿遷 江蘇 常州 蘭州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Matplotlib繪制混淆矩陣的實現(xiàn)》,本文關(guān)鍵詞 Matplotlib,繪制,混淆,矩陣,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。