训练cifar10,输出Accuracy (ACC), Precision, Recall, F1 Score (F1),AUC,并画 ROC曲线pytorch代码
时间: 2024-02-12 18:02:25 浏览: 104
在pytorch 中计算精度、回归率、F1 score等指标的实例
好的,我会尽力回答你的问题。首先,我们需要先加载并预处理CIFAR10数据集:
```python
import torch
import torchvision
import torchvision.transforms as transforms
# Define transforms for training and testing data
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
# Load CIFAR10 dataset
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=4)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=4)
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
```
接下来,我们可以定义模型并进行训练:
```python
import torch.nn as nn
import torch.optim as optim
# Define the model
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 3, padding=1)
self.bn1 = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(32, 64, 3, padding=1)
self.bn2 = nn.BatchNorm2d(64)
self.conv3 = nn.Conv2d(64, 128, 3, padding=1)
self.bn3 = nn.BatchNorm2d(128)
self.fc1 = nn.Linear(4*4*128, 512)
self.bn4 = nn.BatchNorm1d(512)
self.fc2 = nn.Linear(512, 10)
def forward(self, x):
x = nn.functional.relu(self.bn1(self.conv1(x)))
x = nn.functional.relu(self.bn2(self.conv2(x)))
x = nn.functional.relu(self.bn3(self.conv3(x)))
x = x.view(-1, 4*4*128)
x = nn.functional.relu(self.bn4(self.fc1(x)))
x = self.fc2(x)
return x
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)
# Train the model
for epoch in range(100):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print('[Epoch %d] Loss: %.3f' % (epoch + 1, running_loss / len(trainloader)))
```
训练完成后,我们可以计算模型的准确率、精度、召回率、F1值和AUC,并绘制ROC曲线:
```python
from sklearn.metrics import roc_curve, auc, accuracy_score, precision_score, recall_score, f1_score
# Test the model
net.eval()
y_true = []
y_scores = []
with torch.no_grad():
for data in testloader:
inputs, labels = data
outputs = net(inputs)
_, predicted = torch.max(outputs.data, 1)
y_true += labels.tolist()
y_scores += nn.functional.softmax(outputs, dim=1)[:, 1].tolist()
# Compute the metrics
acc = accuracy_score(y_true, [int(score >= 0.5) for score in y_scores])
precision = precision_score(y_true, [int(score >= 0.5) for score in y_scores])
recall = recall_score(y_true, [int(score >= 0.5) for score in y_scores])
f1 = f1_score(y_true, [int(score >= 0.5) for score in y_scores])
fpr, tpr, _ = roc_curve(y_true, y_scores)
auc_score = auc(fpr, tpr)
# Plot the ROC curve
import matplotlib.pyplot as plt
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (AUC = %0.2f)' % auc_score)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic')
plt.legend(loc="lower right")
plt.show()
```
希望这个代码对你有所帮助!
阅读全文