pytorch计算图像分类模型评价指标准确率、精确率、召回率、F1值、AUC的示例代码
时间: 2023-04-10 21:02:44 浏览: 250
在pytorch 中计算精度、回归率、F1 score等指标的实例
5星 · 资源好评率100%
以下是一个使用 PyTorch 计算图像分类模型评价指标的示例代码:
```python
import torch
import torch.nn.functional as F
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score
# 假设我们有一个模型和测试数据集
model = MyModel()
test_loader = DataLoader(test_dataset, batch_size=32)
# 评估模型
model.eval()
y_true = []
y_pred = []
with torch.no_grad():
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
y_true += labels.tolist()
y_pred += predicted.tolist()
# 计算各种评价指标
accuracy = accuracy_score(y_true, y_pred)
precision = precision_score(y_true, y_pred, average='macro')
recall = recall_score(y_true, y_pred, average='macro')
f1 = f1_score(y_true, y_pred, average='macro')
probas = F.softmax(outputs, dim=1)
auc = roc_auc_score(y_true, probas[:, 1])
# 打印结果
print(f"Accuracy: {accuracy:.4f}")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1 score: {f1:.4f}")
print(f"AUC: {auc:.4f}")
```
请注意,这只是一个示例代码,你需要根据你的具体情况进行修改。
阅读全文