(dataloader, model, loss_fn)
| 168 | |
| 169 | |
| 170 | def test_loop(dataloader, model, loss_fn): |
| 171 | # Set the model to evaluation mode - important for batch normalization and dropout layers |
| 172 | # Unnecessary in this situation but added for best practices |
| 173 | model.eval() |
| 174 | size = len(dataloader.dataset) |
| 175 | num_batches = len(dataloader) |
| 176 | test_loss, correct = 0, 0 |
| 177 | |
| 178 | # Evaluating the model with torch.no_grad() ensures that no gradients are computed during test mode |
| 179 | # also serves to reduce unnecessary gradient computations and memory usage for tensors with requires_grad=True |
| 180 | with torch.no_grad(): |
| 181 | for X, y in dataloader: |
| 182 | pred = model(X) |
| 183 | test_loss += loss_fn(pred, y).item() |
| 184 | correct += (pred.argmax(1) == y).type(torch.float).sum().item() |
| 185 | |
| 186 | test_loss /= num_batches |
| 187 | correct /= size |
| 188 | print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n") |
| 189 | |
| 190 | |
| 191 | ######################################## |
no test coverage detected