Python绘图制作混淆矩阵图--简易版(改矩阵参数就能运行)

混淆矩阵详解:SVM分类实例与不同颜色映射
本文介绍如何使用SVM算法进行分类,并通过混淆矩阵展示了预测结果。通过实例,演示了如何调整颜色映射,以帮助理解分类性能。特别关注类别为'Rice'和'Others'的混淆情况。
#confusion_matrix
import numpy as np
import matplotlib.pyplot as plt
# classes = ['A','B','C','D','E']
# confusion_matrix = np.array([(9,1,3,4,0),(2,13,1,3,4),(1,4,10,0,13),(3,1,1,17,0),(0,0,0,1,14)],dtype=np.float64)


# 标签
classes=['Rice','Others']

classNamber=2 #类别数量

# 混淆矩阵
confusion_matrix = np.array([
    (67,24),
    (20,89)
    ],dtype=np.float64)

plt.imshow(confusion_matrix, interpolation='nearest', cmap=plt.cm.Blues)  #按照像素显示出矩阵
plt.title('confusion_matrix-SVM')#改图名
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=-45)
plt.yticks(tick_marks, classes)

thresh = confusion_matrix.max() / 2.
#iters = [[i,j] for i in range(len(classes)) for j in range((classes))]
#ij配对,遍历矩阵迭代器
iters = np.reshape([[[i,j] for j in range(classNamber)] for i in range(classNamber)],(confusion_matrix.size,2))
for i, j in iters:
    plt.text(j, i, format(confusion_matrix[i, j]),va='center',ha='center')   #显示对应的数字

plt.ylabel('Ture')
plt.xlabel('Pre
使用 Python 绘制混淆矩阵图可以借助不同库,以下是几种常见的实现方法: ### 使用`matplotlib`和`sklearn`绘制 ```python from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt y_pred = [] # 例如 ['2','2','3','1','4'] y_true = [] # 例如 ['0','1','2','3','4'] # 对上面进行赋值 C = confusion_matrix(y_true, y_pred, labels=['0','1','2','3','4']) # 可将'1'等替换成自己的类别,如'cat' plt.matshow(C, cmap=plt.cm.Reds) # 根据需求更颜色 # plt.colorbar() for i in range(len(C)): for j in range(len(C)): plt.annotate(C[j, i], xy=(i, j), horizontalalignment='center', verticalalignment='center') # plt.tick_params(labelsize=15) # 设置左边和上面的label类别如0,1,2,3,4的字体大小 plt.ylabel('True label') plt.xlabel('Predicted label') # plt.ylabel('True label', fontdict={'family': 'Times New Roman', 'size': 20}) # 设置字体大小 # plt.xlabel('Predicted label', fontdict={'family': 'Times New Roman', 'size': 20}) # plt.xticks(range(0,5), labels=['a','b','c','d','e']) # 将x轴或y轴坐标,刻度 替换为文字/字符 # plt.yticks(range(0,5), labels=['a','b','c','d','e']) plt.show() ``` 此方法利用`sklearn`的`confusion_matrix`计算混淆矩阵,再用`matplotlib`进行可视化,通过`plt.matshow`展示矩阵,并可自定义颜色、添加注释等 [^2]。 ### 使用`seaborn`绘制混淆矩阵热力图 ```python import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import confusion_matrix # 示例混淆矩阵数据(实际应用中需替换为自己的数据) y_true = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] y_pred = [0, 1, 0, 0, 1, 0, 1, 0, 1, 1] # 计算混淆矩阵 cm = confusion_matrix(y_true, y_pred) # 绘制热力图 plt.figure(figsize=(8, 6)) sns.heatmap(cm, annot=True, cmap='Blues', fmt='d', xticklabels=['预测0', '预测1'], yticklabels=['真实0', '真实1']) plt.xlabel('预测标签') plt.ylabel('真实标签') plt.title('混淆矩阵热力图') plt.show() ``` 该方法结合`seaborn`的`heatmap`函数和`sklearn`的`confusion_matrix`,`seaborn`可绘制出更美观的热力图,通过`annot`参数添加注释,`cmap`指定颜色 [^3]。 ### 另一个`seaborn`绘制示例 ```python import seaborn as sns import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix # 生成示例的真实标签和预测结果 true_labels = [0, 1, 0, 1, 1, 0, 0, 1, 1, 1] predicted_labels = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] # 计算混淆矩阵 cm = confusion_matrix(true_labels, predicted_labels) # 使用seaborn绘制热图表示混淆矩阵 plt.figure(figsize=(8, 6)) sns.heatmap(cm, annot=True, cmap='Blues', fmt='g', xticklabels=['Predicted 0', 'Predicted 1'], yticklabels=['Actual 0', 'Actual 1']) plt.xlabel('Predicted label') plt.ylabel('True label') plt.title('Confusion Matrix') plt.show() ``` 此示例也是使用`seaborn`和`sklearn`,不过标签和格式略有不同 [^4]。 ### 自定义标签和数据的`seaborn`绘制 ```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`绘制,并对标签显示进行优化 [^5]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值