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

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

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

Summary

涉及到分類問題,我們經(jīng)常需要通過可視化混淆矩陣來分析實(shí)驗(yàn)結(jié)果進(jìn)而得出調(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表示你不同類別的代號(hào),比如這里的demo中有13個(gè)類別
labels = ['A', 'B', 'C', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']


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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論