You will build, train and test a small neural network in PyTorch that recognises handwritten digits from the MNIST dataset. It suits Python users who know basic loops and functions but are new to deep learning. You need Python installed and a few lines of pip to get PyTorch.
YouTube video: PyTorch Tutorial for Beginners | Build a Neural Network from Scratch (MNIST Project)
YouTube’s video details do not confirm captions. Check CC in the player for available tracks.
- Video length
- 11 min 29 s
- Time to do it
- 1 hour
- Difficulty
- Medium
- Steps
- 8
What you need
Steps
Install PyTorch and torchvision with pip, then import torch, torch.nn and torchvision in a new Python file or notebook cell.
Load MNIST with torchvision.datasets.MNIST, apply transforms.ToTensor() to both sets, and wrap them in DataLoader with a batch_size of 64.
Define the model by subclassing nn.Module. Use nn.Sequential with a flatten layer, two hidden layers of 128 and 64 units with ReLU, and a 10-unit output layer.
Pick the loss and optimizer: nn.CrossEntropyLoss() for the loss and torch.optim.Adam(model.parameters(), lr=0.001) for the optimizer.
Write the training loop. For each epoch, loop over batches, call optimizer.zero_grad(), run the forward pass, compute the loss, call loss.backward(), then optimizer.step().
Evaluate the model by calling model.eval(), wrapping the test loop in torch.no_grad(), and comparing argmax of the output with the true labels.
Try inference on one image: take a test sample, add a batch dimension with unsqueeze(0), run it through the model, and read the predicted digit with argmax.
Save the trained weights with torch.save(model.state_dict(), "mnist_model.pth") so you can reload them later without retraining.
Tips and common mistakes
Flatten each 28x28 image to 784 values before the first linear layer, or the matrix shapes will not match.
Call optimizer.zero_grad() on every batch, otherwise gradients pile up and training drifts.
Use model.eval() and torch.no_grad() when testing so layers behave consistently and memory stays low.
CrossEntropyLoss expects raw logits, so do not add a softmax layer at the end of the network.
Questions
Do I need a graphics card for this?
No. This small network trains on a normal CPU in a couple of minutes per epoch. A GPU only speeds things up and is optional here.
What accuracy should I expect?
Around 97 to 98 percent on the MNIST test set after three to five epochs with this simple setup. Much lower means a bug in the training loop.
What exactly is a tensor?
A tensor is PyTorch's array type. It works like a NumPy array but can run on a GPU and track gradients for backpropagation.
The notes are drafted automatically from video details and general task knowledge. How the guide was prepared
Report a correction


