1. Import libraries
torch→ main PyTorch librarynn→ neural-network layersoptim→ optimizers like AdamDataLoader→ creates batchesdatasets→ provides MNISTtransforms→ image preprocessing
2. Select device
- Uses GPU if available.
- Otherwise uses CPU.
3. Transform images
4. Load MNIST
train=True→ training data- MNIST training set → 60,000 images
train=False→ testing data- MNIST test set → 10,000 images
5. Create DataLoader
batch_size=64→ process 64 images at a timeshuffle=True→ randomly mix training data
- Testing doesn’t need shuffling.
6. MNIST image
Each MNIST image is:1 means grayscale channel.
7. Neural network
First layer
Second layer
8. Forward pass
9. Flatten
10. ReLU
11. Create model
12. Loss function
How wrong is the prediction?For MNIST classification,
CrossEntropyLoss is commonly used.
13. Optimizer
Learning rate
14. Epoch
The model has seen the entire training dataset once.So:
15. Training loop
The most important part:16. optimizer.zero_grad()
17. Forward pass
18. Calculate loss
19. Backpropagation
20. Update weights
21. Training vs Testing
Training
Testing
22. torch.no_grad()
- Uses less memory
- Faster computation
- No training happens
23. Prediction
3.
Therefore:
24. Accuracy
25. Important correction
Your original code has:f makes it an f-string, so Python replaces {accuracy} with its value.
Revision
Most important 5 lines:
28×28 handwritten digit, converts it into 784 numbers, processes them through 128 neurons, produces 10 class scores, calculates the error, and repeatedly updates its weights until its predictions improve.