使用字符串数据框在Python中绘制混淆矩阵
我正在做一个10倍的验证,我需要看看每个类的准确性是如何变化的。我成功地创建了如下数据帧: 片段:使用字符串数据框在Python中绘制混淆矩阵,python,pandas,matplotlib,heatmap,confusion-matrix,Python,Pandas,Matplotlib,Heatmap,Confusion Matrix,我正在做一个10倍的验证,我需要看看每个类的准确性是如何变化的。我成功地创建了如下数据帧: 片段: chars=[] 对于范围(0,int(类)+1)内的i: 行=[] 对于范围(0,int(类)+1)内的j: 追加(str(round(表示[i,j],3])+“+/-”+str(round(stds[i,j],3))) 附加字符(行) con\u mat\u df=pd.DataFrame(字符,索引=类列表,列=类列表) 现在,我只想能够像下面的例子那样绘制它。我想知道怎么做。如果我使用s
chars=[]
对于范围(0,int(类)+1)内的i:
行=[]
对于范围(0,int(类)+1)内的j:
追加(str(round(表示[i,j],3])+“+/-”+str(round(stds[i,j],3)))
附加字符(行)
con\u mat\u df=pd.DataFrame(字符,索引=类列表,列=类列表)
现在,我只想能够像下面的例子那样绘制它。我想知道怎么做。如果我使用sns.heatmap
它将抛出一个错误(TypeError:ufunc'isnan'不支持输入类型…
)。有什么想法吗?谢谢
所以我找到的最简单的方法是(cm是平均值数组,cms是标准偏差数组):
Seaborn heatmap需要绘制数字,但您有字符串。我知道,这就是为什么我说我不能使用heatmap,因为它会抛出错误。我特意创建了一个字符串数组(实际上是一个数据帧),我想知道如何打印它,如图所示。使用数字绘制热图(使用
seaborn.heatmap
,或ax.imshow
);然后把文本标签放在你喜欢的上面;示例如所示,但我需要包括标准偏差,而不仅仅是数字。我多次使用热图来绘制一个只有浮点值的混淆矩阵。我并不是说我想用热图来做这个,我只是说“我怎样才能画出我所展示的图中的东西”,我告诉你你需要使用数字才能画出彩色编码的像素。
0 1 ... 14 15
0 100.0 +/- 0.0 0.0 +/- 0.0 ... 0.0 +/- 0.0 0.0 +/- 0.0
1 0.49 +/- 0.703 98.53 +/- 1.416 ... 0.0 +/- 0.0 0.0 +/- 0.0
2 0.0 +/- 0.0 0.12 +/- 0.36 ... 0.0 +/- 0.0 0.0 +/- 0.0
3 0.0 +/- 0.0 0.0 +/- 0.0 ... 0.0 +/- 0.0 0.0 +/- 0.0
4 0.0 +/- 0.0 0.0 +/- 0.0 ... 0.0 +/- 0.0 0.0 +/- 0.0
5 0.55 +/- 0.905 0.14 +/- 0.42 ... 0.0 +/- 0.0 0.0 +/- 0.0
6 0.0 +/- 0.0 0.0 +/- 0.0 ... 0.0 +/- 0.0 0.0 +/- 0.0
7 0.0 +/- 0.0 0.0 +/- 0.0 ... 0.0 +/- 0.0 0.0 +/- 0.0
8 0.0 +/- 0.0 0.0 +/- 0.0 ... 0.0 +/- 0.0 0.0 +/- 0.0
9 0.62 +/- 1.318 0.2 +/- 0.6 ... 0.0 +/- 0.0 0.0 +/- 0.0
10 0.65 +/- 0.927 0.24 +/- 0.265 ... 0.0 +/- 0.0 0.0 +/- 0.0
11 1.02 +/- 1.558 0.0 +/- 0.0 ... 0.0 +/- 0.0 1.36 +/- 1.482
12 0.0 +/- 0.0 0.0 +/- 0.0 ... 0.0 +/- 0.0 0.0 +/- 0.0
13 0.32 +/- 0.96 0.0 +/- 0.0 ... 0.0 +/- 0.0 0.0 +/- 0.0
14 0.78 +/- 1.191 0.0 +/- 0.0 ... 98.96 +/- 1.274 0.0 +/- 0.0
15 0.0 +/- 0.0 0.0 +/- 0.0 ... 0.0 +/- 0.0 94.78 +/- 6.884
[16 rows x 16 columns]
def plot_confusion_matrix(cm, cms, classes,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
plt.text(j, i, '{0:.2f}'.format(cm[i, j]) + '\n$\pm$' + '{0:.2f}'.format(cms[i, j]),
horizontalalignment="center",
verticalalignment="center", fontsize=7,
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(means, stds, classes=classes_list)