How to evaluate a model in PyTorch

Model evaluation in PyTorch typically involves the following steps:

  1. Import the necessary libraries and models.
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
from torchvision import transforms, datasets
  1. Load the test dataset.
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. Load model:
model = YourModel()
model.load_state_dict(torch.load('model.pth'))
model.eval()
  1. Define evaluation function:
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. Call the evaluation function.
evaluate_model(model, test_loader)

This way, you can evaluate the model in PyTorch.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds