使用 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]。