温馨提示×

如何在PyTorch中进行模型评估

小樊
105
2024-03-05 18:53:57
栏目: 编程语言

在PyTorch中进行模型评估通常需要以下步骤:

  1. 导入所需的库和模型:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
from torchvision import transforms, datasets
  1. 加载测试数据集:
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)
  1. 加载模型:
model = YourModel()
model.load_state_dict(torch.load('model.pth'))
model.eval()
  1. 定义评估函数:
def evaluate_model(model, test_loader):
    correct = 0
    total = 0
    with torch.no_grad():
        for images, labels in test_loader:
            outputs = model(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    accuracy = correct / total
    print('Accuracy of the model on the test set: {:.2f}%'.format(accuracy * 100))
  1. 调用评估函数:
evaluate_model(model, test_loader)

这样你就可以在PyTorch中对模型进行评估了。

0