for data in testloader: images, labels = data images = images.view(len(images), 1, 121).float() inputs, labels = images.to(device), labels.to(device) outputs = cnn(inputs) _, predicted = torch.max(outputs, 1) true_labels.append(labels.cpu().numpy()) predicted_labels.append(predicted.cpu().numpy()) true_labels = np.concatenate(true_labels) predicted_labels = np.concatenate(predicted_labels) cm = confusion_matrix(true_labels, predicted_labels, labels=[0, 1, 2, 3, 4]) print(cm)上述代码加入混淆矩阵可视化代码
时间: 2023-12-15 18:04:27 浏览: 78
你可以使用Matplotlib库中的函数来可视化混淆矩阵。以下是代码示例:
```python
import matplotlib.pyplot as plt
import itertools
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# 在计算混淆矩阵后,调用以下代码进行可视化
plot_confusion_matrix(cm, classes=['class0', 'class1', 'class2', 'class3', 'class4'])
plt.show()
```
其中,`cm`是混淆矩阵,`classes`是类别标签,可以根据实际情况进行修改。如果需要归一化混淆矩阵,可以将`normalize`参数设置为`True`。
阅读全文