defforward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x
correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item()
print(f'Accuracy of the network on the 10000 test images: {100 * correct / total:.2f}%')
6.2 各类别的准确率
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 获取所有类别的准确率 class_correct = list(0.for i inrange(10)) class_total = list(0.for i inrange(10))
with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) c = (predicted == labels).squeeze() for i inrange(4): # batch_size label = labels[i] class_correct[label] += c[i].item() class_total[label] += 1
for i inrange(10): print(f'Accuracy of {classes[i]:5s} : {100 * class_correct[i] / class_total[i]:2.2f} %')
num_epochs = 10 for epoch inrange(num_epochs): for images, targets in data_loader: images = [img.to(device) for img in images] targets = [{k: v.to(device) for k, v in t.items()} for t in targets]
loss_dict = model(images, targets) losses = sum(loss for loss in loss_dict.values())
训练后需要评估模型的表现,通常使用 mAP(mean Average Precision)作为评价指标。
4.1 评估函数
你可以使用 torchvision 提供的评估工具来计算 mAP。
1 2 3 4 5 6 7 8
from torchvision.models.detection import fasterrcnn_resnet50_fpn
model.eval() with torch.no_grad(): for images, targets in data_loader: images = [img.to(device) for img in images] predictions = model(images) # 计算 mAP