MCPcopy Index your code
hub / github.com/pytorch/tutorials / test_loop

Function test_loop

beginner_source/basics/optimization_tutorial.py:170–188  ·  view source on GitHub ↗
(dataloader, model, loss_fn)

Source from the content-addressed store, hash-verified

168
169
170def 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########################################

Callers 1

Calls 2

loss_fnFunction · 0.85
modelFunction · 0.50

Tested by

no test coverage detected