在PyTorch中,可以使用以下步驟來實現模型驗證:
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
eval()
方法調用。model.eval()
torch.no_grad()
上下文管理器來關閉梯度計算,以節省內存和加快推理速度。with torch.no_grad():
for inputs, labels in val_loader:
# 進行模型推斷
correct = 0
total = 0
loss = 0
for inputs, labels in val_loader:
outputs = model(inputs)
_, predicted = torch.max(outputs, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
loss += criterion(outputs, labels).item()
accuracy = correct / total
average_loss = loss / len(val_loader)
print(f'Validation Accuracy: {accuracy}, Validation Loss: {average_loss}')
以上就是在PyTorch中實現模型驗證的步驟。通過以上步驟,可以評估模型在驗證數據集上的性能,并據此調整模型的超參數和結構。