Python中生成并绘制混淆矩阵(confusion matrix)

本文详细介绍了如何使用Python和Sklearn库绘制混淆矩阵,通过一个具体的例子展示了混淆矩阵的生成过程及其在机器学习结果分析中的作用。文章还提供了绘制混淆矩阵热图的代码,并对生成的图像进行了深入分析。

在机器学习中经常会用到混淆矩阵(confusion matrix),不了解的同学请参考这篇博文:

ML01 机器学习后利用混淆矩阵Confusion matrix 进行结果分析


本文参考:使用python绘制混淆矩阵(confusion_matrix)


首先import一些必要的库:

from sklearn.metrics import confusion_matrix    # 生成混淆矩阵函数
import matplotlib.pyplot as plt    # 绘图库
import numpy as np
import tensorflow as tf

 

然后定义绘制混淆矩阵函数:

def plot_confusion_matrix(cm, labels_name, title):
    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]    # 归一化
    plt.imshow(cm, interpolation='nearest')    # 在特定的窗口上显示图像
    plt.title(title)    # 图像标题
    plt.colorbar()
    num_local = np.array(range(len(labels_name)))    
    plt.xticks(num_local, labels_name, rotation=90)    # 将标签印在x轴坐标上
    plt.yticks(num_local, labels_name)    # 将标签印在y轴坐标上
    plt.ylabel('True label')    
    plt.xlabel('Predicted label')

生成混淆矩阵:

其中pred_y为预测值,y_为网络输出预测值,test_x为测试输入值,test_y为测试真实值。

(本程序中标签为one-hot形式,故使用tf.argmax(y_, 1)和tf.argmax(test_y, 1),若标签为普通列表形式,请直接使用y_和test_y)

pred_y = session.run(tf.argmax(y_, 1), feed_dict={X: test_x})
cm = confusion_matrix(np.argmax(test_y, 1), pred_y,)
print(cm)
# [[100   1   0   1   6   0   0]
#  [  2 111   3   0   2   1  24]
#  [  0   2  68   5   4   3   2]
#  [  2   0   1 120   7  26   0]
#  [  2   5   3   2 120  11  14]
#  [  2   0   2  12   8 115   1]
#  [  2  25   0   1  14   4 302]]

绘制混淆矩阵热图并显示:

plot_confusion_matrix(cm, labels_name, "HAR Confusion Matrix")
# plt.savefig('/HAR_cm.png', format='png')
plt.show()

结合生成的图像对混淆矩阵进行分析:

24代表:有24个Climb_stairs动作被神经网络认为成了Walk。

Python 中,绘制混淆矩阵通常会用到 `seaborn` 和 `matplotlib` 库,同时会借助 `sklearn.metrics` 中的 `confusion_matrix` 函数来计算混淆矩阵。以下是几种常见的绘制方法: #### 方法一:使用 `seaborn` 的 `heatmap` 函数 ```python import seaborn as sns from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt sns.set() f, ax = plt.subplots() y_true = [0, 0, 1, 2, 1, 2, 0, 2, 2, 0, 1, 1] y_pred = [1, 0, 1, 2, 1, 0, 0, 2, 2, 0, 1, 1] C2 = confusion_matrix(y_true, y_pred, labels=[0, 1, 2]) print(C2) sns.heatmap(C2, annot=True, ax=ax) ax.set_title('confusion matrix') ax.set_xlabel('predict') ax.set_ylabel('true') plt.show() ``` 此方法先使用 `confusion_matrix` 函数计算混淆矩阵,再利用 `seaborn` 的 `heatmap` 函数将其绘制成热力图,最后通过 `matplotlib` 显示图形[^1]。 #### 方法二:自定义标签绘制混淆矩阵 ```python import numpy as np import matplotlib.pyplot as plt import seaborn as sns # 假设这是你的混淆矩阵数据 confusion_matrix = np.array([ [680, 18, 133, 95, 3], [22, 406, 25, 93, 11], [99, 24, 348, 217, 7], [45, 43, 83, 1149, 78], [5, 7, 8, 127, 406] ]) # 自定义的标签名称 labels = ['Class A', 'Class B', 'Class C', 'Class D', 'Class E'] # 设置绘图 plt.figure(figsize=(10, 7)) ax = sns.heatmap(confusion_matrix, annot=True, fmt='d', cmap='Blues', cbar_kws={'label': 'Scale'}, xticklabels=labels, yticklabels=labels) # 添加标题和轴标签 plt.title('Confusion Matrix') plt.xlabel('Predicted Label') plt.ylabel('True Label') # 优化标签显示 plt.xticks(rotation=45, ha='right') plt.yticks(rotation=0) # 显示图形 plt.show() ``` 该方法同样使用 `seaborn` 的 `heatmap` 函数绘制混淆矩阵,不同之处在于可以自定义标签名称,且能对图形的大小、颜色、标签显示等进行更多的设置[^2]。 #### 方法三:使用 `matplotlib` 的 `matshow` 函数 ```python import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import numpy as np def cm_plot(original_label, predict_label, pic=None): cm = confusion_matrix(original_label, predict_label) plt.figure() plt.matshow(cm, cmap=plt.cm.Blues) plt.colorbar() for x in range(len(cm)): for y in range(len(cm)): plt.annotate(cm[x, y], xy=(x, y), horizontalalignment='center', verticalalignment='center') plt.ylabel('True label') plt.xlabel('Predicted label') plt.title('confusion matrix') if pic is not None: plt.savefig(str(pic) + '.jpg') plt.show() ``` 此方法使用 `matplotlib` 的 `matshow` 函数绘制混淆矩阵,同时通过 `annotate` 函数在每个单元格中添加具体的数值,还可以将图形保存为图片[^3]。
评论 12
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值