python 混淆矩阵_绘制混沌矩阵
? ? ? ?python因為有各種庫的支持,所以功能格外強大。在可視化方面,目前用得較多的是matplotlib.在基于matplotlib.pyplot畫帶色標(colorbar)的圖時候,往往為了美觀和科研用途,需要對colorbar的Ticks(刻度) ,標簽(label)和fonddict(字體進行設置)。但是很多初學者都苦于這些東西的設置。
????涉及到分類問題,我們經常需要通過可視化混淆矩陣來分析實驗結果進而得出調參思路,本文介紹如何利用python繪制混淆矩陣(confusion_matrix),本文只提供代碼,給出必要注釋。今天使用了python matplotlib包,繪制混淆矩陣。heatmap的各個參數介紹可見如下鏈接:
http://seaborn.pydata.org/generated/seaborn.heatmap.html
https://blog.csdn.net/sunchengquan/article/details/78573244
https://blog.csdn.net/m0_38103546/article/details/79935671
? ? ?heatmap參數中,默認cbar=True,即默認畫出colorbar,其中cbarkws為一個字典, 可以用來設置colorbar的一些屬性,包括 thrink, orentation等 。其中:cm - 混淆矩陣的數值, 是一個二維numpy數組、labels- 各個類別的標簽(label)、title - 圖片標題、代碼如下:
#####導入需要用到的包######import numpy as npimport matplotlib.pyplot as pltimport?seaborn?as?snsfrom sklearn.metrics import confusion_matrix##### 各個類別的標簽labels = ['A', 'B', 'C', 'F', 'G']title='Normalized confusion matrix' #真實值y_true = [0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,4,4 ] #預測值??????????????????????????y_pred = [0,0,1,0,0,0,0,0,0,0, 1,1,1,1,1,1,2,1,1,1, 2,2,2,2,3,2,2,2,2,2, 3,3,3,3,3,3,2,3,3,3, 4,4,4,4,4,4,4,3,4,4 ] ######生成混沌矩陣cm = confusion_matrix(y_true, y_pred)#fig=plt.figure(figsize=(10,8)) ?####開始畫圖#######plt.figure(figsize=(10, 8), dpi=120) h=sns.heatmap(cm,linewidths=0.5,cbar=False) #設置不使用其默認自帶的colorbarcb=h.figure.colorbar(h.collections[0]) #顯示colorbarcb.ax.tick_params(labelsize=16) #設置colorbar刻度字體大小。#####添加小框里的數字#####ind_array = np.arange(len(labels))x, y = np.meshgrid(ind_array, ind_array)for x_val, y_val in zip(x.flatten(), y.flatten()): c = cm[y_val][x_val] if c > 0: plt.text(x_val+0.5, y_val+0.5, "%d" % (c,), color='red', fontsize=32, va='center', ha='center')??#添加標題plt.title(title,fontsize=16)xlocations = np.array(range(len(labels)))plt.xticks(xlocations+0.5,labels,fontsize=16)plt.yticks(xlocations+0.5, labels,fontsize=16)plt.ylabel('True label',fontsize=16)plt.xlabel('Predicted label',fontsize=16)plt.savefig('confusion_matrix_1.jpg', format='jpg')plt.show()最后,畫出來的效果如下:
完畢!!!!!!!!!!!!!
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
總結
以上是生活随笔為你收集整理的python 混淆矩阵_绘制混沌矩阵的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为 MatePad 11 英寸(202
- 下一篇: 全球首款 10.3 英寸 Kaleido