作者:mobiledu2502875483 | 来源:互联网 | 2024-10-23 17:23
在做分类的时候confusionmatrix,经常需要画混淆矩阵,下面我们使用python的matplotlib包,scikit-learning机器学习库也同样提供了例子, 但是这样的图并不能满足我
在做分类的时候confusionmatrix,经常需要画混淆矩阵,下面我们使用python的matplotlib包,scikit-learning机器学习库也同样提供了例子, 但是这样的图并不能满足我们的要求,
首先是刻度的来自显示是在方格的中间,这需360问答要隐藏刻度,其次是如何把每个label显示在每个方块的中间, 其次际自初身架是如何在每个方格中显示accuracy数值, 最后是如何在横坐标和纵坐标显示label的引烧功娘此水置调名字,在label name比较长的时候,如何处理显示问题confusionmatrix。
[python] view plain copy
'''''compute confusion matrix
labels.txt: con青衣量益把万政住换tain label name.
predict.txt: predict_la究第儿周bel true_label
from sklearn.metrics import con凯看第真委有关fusion_matrix
import matplotlib.pyplot as plt
import numpy as np
#load labels.
labels = []
f作试所印破刑支一官民ile = open('lab专万走热备培陆著装限夫els.txt', 'r')
lines = file.readlines()
for line in lines:
labels.append(line.strip())
file.close()
y_true = []
y_pred = []
#load true and predict labels.
file = open('predict.txt', 'r')
lines = file.re溶议adlines()
for line in lines:
y_true.a前术ppend(int(line.split(" ")[1].strip()))
y_pred.append(int(line.split(" ")[月0].strip()))
file.close()
tick_marks = np.array(range(len(labels))) + 0.5
def plot_confusion_matrix(cm, title='Confusion Matrix', cmap = plt.cm.binar原亚细为y):
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)
print cm
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)
#set the fontsize of label.
#for label in plt.gca().xaxis.get_ticklabels():
# label.set_若那粒婷况顺热慢氧fontsize(8)
#text portion
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_norm字如事特拉陆降向alized[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', line)
plt.gcf().subplots_adjust(bottom=0.15)
plot_confusion_matrix(cm_normalized, title='Normalized confusion matrix')
#show confusion matrix
***.show()
结果如下图所示: