在pytorch中,培训主要通过循环完成,因此您必须通过每个步骤定义,有torchmetrics之类的包,您可以运行每个度量,以下是一个示例:
import torchmetrics
for step, (test_image, test_labels) in tqdm(enumerate(test_dataloader), total=len(test_dataloader)):
test_batch_image = test_image.to('cuda')
test_batch_label = test_labels.to('cuda')
targets.append(test_labels)
with torch.no_grad():
logits = model(test_batch_image)
loss = criterion(logits, test_batch_label)
test_loss += loss.item()
preds.append(logits.detach().cpu().numpy().argmax(axis=1))
preds = torch.tensor(np.concatenate(preds))
targets = torch.tensor(np.concatenate(targets))
print('[Epoch %d] Test loss: %.3f' %(epoch + 1, test_loss/ len(test_dataloader)))
print('Accuracy: {}%'.format(round(torchmetrics.functional.accuracy(target=targets, preds=preds).item() * 100), 2))