欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解使用python繪制混淆矩陣(confusion_matrix)

 更新時間:2019年07月14日 16:09:16   作者:ai-exception  
這篇文章主要介紹了詳解使用python繪制混淆矩陣(confusion_matrix),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

Summary

涉及到分類問題,我們經(jīng)常需要通過可視化混淆矩陣來分析實驗結(jié)果進而得出調(diào)參思路,本文介紹如何利用python繪制混淆矩陣(confusion_matrix),本文只提供代碼,給出必要注釋。

Code​

# -*-coding:utf-8-*-
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import numpy as np

#labels表示你不同類別的代號,比如這里的demo中有13個類別
labels = ['A', 'B', 'C', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']


'''
具體解釋一下re_label.txt和pr_label.txt這兩個文件,比如你有100個樣本
去做預測,這100個樣本中一共有10類,那么首先這100個樣本的真實label你一定
是知道的,一共有10個類別,用[0,9]表示,則re_label.txt文件中應該有100
個數(shù)字,第n個數(shù)字代表的是第n個樣本的真實label(100個樣本自然就有100個
數(shù)字)。
同理,pr_label.txt里面也應該有1--個數(shù)字,第n個數(shù)字代表的是第n個樣本經(jīng)過
你訓練好的網(wǎng)絡預測出來的預測label。
這樣,re_label.txt和pr_label.txt這兩個文件分別代表了你樣本的真實label和預測label,然后讀到y(tǒng)_true和y_pred這兩個變量中計算后面的混淆矩陣。當然,不一定非要使用這種txt格式的文件讀入的方式,只要你最后將你的真實
label和預測label分別保存到y(tǒng)_true和y_pred這兩個變量中即可。
'''
y_true = np.loadtxt('../Data/re_label.txt')
y_pred = np.loadtxt('../Data/pr_label.txt')

tick_marks = np.array(range(len(labels))) + 0.5

def plot_confusion_matrix(cm, title='Confusion Matrix', cmap=plt.cm.binary):
  plt.imshow(cm, interpolation='nearest', cmap=cmap)
  plt.title(title)
  plt.colorbar()
  xlocations = np.array(range(len(labels)))
  plt.xticks(xlocations, labels, rotation=90)
  plt.yticks(xlocations, labels)
  plt.ylabel('True label')
  plt.xlabel('Predicted label')
  cm = confusion_matrix(y_true, y_pred)
  np.set_printoptions(precision=2)
  
cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print cm_normalized
plt.figure(figsize=(12, 8), dpi=120)

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_normalized[y_val][x_val]
  if c > 0.01:
    plt.text(x_val, y_val, "%0.2f" % (c,), color='red', fontsize=7, va='center', ha='center')
# offset the tick
plt.gca().set_xticks(tick_marks, minor=True)
plt.gca().set_yticks(tick_marks, minor=True)
plt.gca().xaxis.set_ticks_position('none')
plt.gca().yaxis.set_ticks_position('none')
plt.grid(True, which='minor', linestyle='-')
plt.gcf().subplots_adjust(bottom=0.15)

plot_confusion_matrix(cm_normalized, title='Normalized confusion matrix')
# show confusion matrix
plt.savefig('../Data/confusion_matrix.png', format='png')
plt.show()

Result

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論