请在代码中加入准确率:with torch.no_grad(): class_accuary_List=[] true_labels = [] predicted_labels = [] 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) for i in range(cm.shape[0]): acc = cm[i, i] / np.sum(cm[i]) class_accuary_List.append(acc) print("Class", i, "Accuracy:", acc)
时间: 2024-02-22 08:56:03 浏览: 232
one hot编码:`torch.Tensor.scatter_()`函数用法详解
好的,下面是加入准确率的代码:
```
with torch.no_grad():
class_accuracy_list = []
true_labels = []
predicted_labels = []
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)
for i in range(cm.shape[0]):
acc = cm[i, i] / np.sum(cm[i])
class_accuracy_list.append(acc)
print("Class", i, "Accuracy:", acc)
overall_acc = np.sum(np.diag(cm)) / np.sum(cm)
print("Overall Accuracy:", overall_acc)
```
这里加入了一个 `overall_acc` 变量,用于计算整体准确率。同时,在循环中计算每个类别的准确率,并将其存储在 `class_accuracy_list` 列表中。最后输出整体准确率和每个类别的准确率。
阅读全文