在PyTorch中進行模型評估通常需要以下步驟:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
from torchvision import transforms, datasets
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)
model = YourModel()
model.load_state_dict(torch.load('model.pth'))
model.eval()
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))
evaluate_model(model, test_loader)
這樣你就可以在PyTorch中對模型進行評估了。