-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
53 lines (41 loc) · 1.75 KB
/
Copy pathtest.py
File metadata and controls
53 lines (41 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import enum
import torch
from model import Mnist
def test(args, test_data, device):
"""
Evaluates a trained MNIST model on the provided test dataset.
Args:
args: An object containing configuration parameters such as batch_size, data_dir, and save_model_path.
test_data: The dataset to be used for testing (should be compatible with torch.utils.data.DataLoader).
device: The device (e.g., 'cpu' or 'cuda') on which to perform computations.
Behavior:
- Loads the MNIST model and its trained weights from the specified path.
- Iterates over the test dataset in batches.
- Computes and prints the accuracy for each test batch.
- Prints summary information about the testing process.
"""
print(
f"\
================= Testing the Minist Model =================\n \
Batch Size: {args.batch_size}\n \
Data Directory: {args.data_dir}\n \
Load Model Path: {args.save_model_path}\n \
------------------------------------------------------------\n \
"
)
test_loader = torch.utils.data.DataLoader(
test_data, batch_size=args.batch_size, shuffle=True, num_workers=4
)
model = Mnist().to(device)
model.load_state_dict(torch.load(args.save_model_path))
model.eval()
with torch.no_grad():
for test_batch_idx, (data, target) in enumerate(test_loader):
data, target = data.to(device), target.to(device)
output = model(data)
pred = output.argmax(dim=1)
correct = pred.eq(target).sum().item()
print(
f"Test Batch: {test_batch_idx}\tAccuracy: {100. * correct / len(data):.2f}%"
)
print("Testing completed.")