Skip to main content

1. Import libraries

  • torch → main PyTorch library
  • nn → neural-network layers
  • optim → optimizers like Adam
  • DataLoader → creates batches
  • datasets → provides MNIST
  • transforms → image preprocessing

2. Select device

  • Uses GPU if available.
  • Otherwise uses CPU.
moves the model to that device.

3. Transform images

Converts images into PyTorch tensors. MNIST pixel values are converted roughly from:

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 time
  • shuffle=True → randomly mix training data
  • Testing doesn’t need shuffling.

6. MNIST image

Each MNIST image is:
So total pixels:
Image tensor:
1 means grayscale channel.

7. Neural network

Creates a custom neural network.

First layer

Means:

Second layer

Means:
Why 10? Because MNIST has:

8. Forward pass

Flow:

9. Flatten

Converts:
into:
For a batch of 64:

10. ReLU

Formula:
Examples:
ReLU adds non-linearity, allowing the network to learn complex patterns.

11. Create model

Creates the neural network and moves it to CPU/GPU.

12. Loss function

Loss tells us:
How wrong is the prediction?
For MNIST classification, CrossEntropyLoss is commonly used.

13. Optimizer

Adam updates the model’s weights.

Learning rate

Controls how big each weight update is.

14. Epoch

One epoch means:
The model has seen the entire training dataset once.
So:

15. Training loop

The most important part:
Remember:

16. optimizer.zero_grad()

Clears old gradients before calculating new ones.

17. Forward pass

The images go through the neural network.

18. Calculate loss

Compares:

19. Backpropagation

Calculates gradients. Gradients tell the model how its weights should change to reduce the loss.

20. Update weights

Adam uses the gradients to update the weights. This is where the model learns.

21. Training vs Testing

Training

Used when learning. The model:

Testing

Used after training to measure performance. No weight updates happen.

22. torch.no_grad()

During testing, we don’t need gradients. Benefits:
  • Uses less memory
  • Faster computation
  • No training happens

23. Prediction

The model produces 10 scores. Example:
Highest score is class 3. Therefore:

24. Accuracy

Example:
Then:

25. Important correction

Your original code has:
This is incorrect. Use:
The f makes it an f-string, so Python replaces {accuracy} with its value.

Revision

Most important 5 lines:

In one sentence: The neural network takes a 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.