给出gpu上训练 CIFAR10 ,计算ACC PRECISION F1 RECALL AUC 及每一类ROC曲线的 pytorch 代码
时间: 2024-02-12 19:05:03 浏览: 156
python实现二分类和多分类的ROC曲线教程
好的,以下是给出GPU上训练CIFAR10并计算指标的PyTorch代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_curve, auc
# 定义网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(32, 64, 5)
self.fc1 = nn.Linear(64 * 5 * 5, 256)
self.fc2 = nn.Linear(256, 10)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = x.view(-1, 64 * 5 * 5)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return x
# 加载数据集并进行数据增强
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))
])
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=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=128, shuffle=False, num_workers=2)
# 定义损失函数和优化器
net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 将模型移动到GPU上进行训练
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net.to(device)
# 训练模型
for epoch in range(20):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99:
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 100))
running_loss = 0.0
# 在测试集上进行预测并计算各项指标
y_true = []
y_pred = []
y_score = []
net.eval()
with torch.no_grad():
for data in testloader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
y_true += labels.cpu().numpy().tolist()
y_pred += predicted.cpu().numpy().tolist()
y_score += nn.functional.softmax(outputs, dim=1).cpu().numpy().tolist()
acc = 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')
fpr = {}
tpr = {}
roc_auc = {}
for i in range(10):
fpr[i], tpr[i], _ = roc_curve([1 if j == i else 0 for j in y_true], [score[i] for score in y_score])
roc_auc[i] = auc(fpr[i], tpr[i])
print("Accuracy:", acc)
print("Precision:", precision)
print("Recall:", recall)
print("F1 score:", f1)
for i in range(10):
print("ROC AUC of class", i, ":", roc_auc[i])
```
这段代码会输出ACC PRECISION F1 RECALL AUC以及每一类ROC曲线的值。
阅读全文