DEV Community

Cover image for PyTorch Tutorial – A Beginner’s Guide to Deep Learning
Rishabh parmar
Rishabh parmar

Posted on

PyTorch Tutorial – A Beginner’s Guide to Deep Learning

Artificial Intelligence and Deep Learning are no longer buzzwords reserved for research labs—they’re shaping industries from healthcare to finance, entertainment to self-driving cars. At the heart of these innovations lies the power of deep learning frameworks that simplify building, training, and deploying neural networks. Among the most popular frameworks is PyTorch, an open-source machine learning library developed by Facebook’s AI Research team. In this blog, we’ll take you through a PyTorch tutorial designed especially for beginners, so you can understand what PyTorch is, why it’s used, and how you can start building your first deep learning models.

What is PyTorch?

PyTorch is a deep learning framework built on top of Python. It provides powerful tools for creating neural networks and training models with ease. Its popularity comes from its dynamic computation graph, which makes it more flexible and intuitive compared to other frameworks like TensorFlow.

Some key highlights of PyTorch include:

Pythonic Nature – PyTorch feels like regular Python, making it easy for developers and researchers to adopt.

Dynamic Graphs – You can define and change computation graphs on the fly, which is great for experiments and debugging.

GPU Acceleration – It supports CUDA, enabling fast computations on GPUs.

Active Community – With strong contributions from developers and researchers, resources and tutorials are abundant.

Why Learn PyTorch?

If you are stepping into the world of deep learning, PyTorch is one of the best frameworks to start with. Here’s why:

Beginner-Friendly – Its syntax is simple, clear, and very similar to NumPy.

Research-Oriented – Many cutting-edge research papers and projects rely on PyTorch.

Production-Ready – With TorchScript, PyTorch models can be deployed at scale in real-world applications.

Rich Ecosystem – Libraries like TorchVision, TorchText, and PyTorch Lightning extend its capabilities.

Whether you want to build a small neural network for image recognition or work on natural language processing tasks, PyTorch gives you all the tools you need.

Setting Up PyTorch

Before we dive into coding, let’s get PyTorch installed.

Install Python – Make sure you have Python 3.7 or later installed.

Install PyTorch – The easiest way is through pip or conda.

For pip:

pip install torch torchvision torchaudio

For conda:

conda install pytorch torchvision torchaudio cpuonly -c pytorch

If you have a GPU, you can install the GPU-enabled version by selecting the right CUDA toolkit on the PyTorch official website
.

Basics of PyTorch

Once installed, let’s go over the building blocks of PyTorch.

  1. Tensors

Tensors are the core data structure in PyTorch, similar to NumPy arrays but with GPU acceleration support.

Example:

import torch

Create a tensor

x = torch.tensor([[1, 2], [3, 4]])
print(x)

Perform operations

y = torch.rand(2, 2)
print(x + y)

  1. Autograd

PyTorch’s autograd system automatically calculates gradients, which are essential for training neural networks.

Example:

Requires gradient tracking

a = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(3.0, requires_grad=True)

c = a * b
c.backward() # Computes dc/da and dc/db

print(a.grad) # Output: 3.0
print(b.grad) # Output: 2.0

  1. Neural Networks with torch.nn

PyTorch provides the torch.nn module for building neural networks easily.

Building a Simple Neural Network

Let’s create a simple neural network to classify handwritten digits from the MNIST dataset.

Step 1: Import Libraries
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms

Step 2: Load Dataset
transform = transforms.ToTensor()

trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)

testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False)

Step 3: Define the Neural Network
class SimpleNN(nn.Module):
def init(self):
super(SimpleNN, self).init()
self.fc1 = nn.Linear(28*28, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 10)

def forward(self, x):
    x = x.view(-1, 28*28)  # Flatten the image
    x = torch.relu(self.fc1(x))
    x = torch.relu(self.fc2(x))
    x = self.fc3(x)
    return x
Enter fullscreen mode Exit fullscreen mode

model = SimpleNN()

Step 4: Define Loss and Optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

Step 5: Train the Model
for epoch in range(5): # 5 epochs
for images, labels in trainloader:
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
print(f'Epoch [{epoch+1}/5], Loss: {loss.item():.4f}')

Step 6: Evaluate the Model
correct = 0
total = 0
with torch.no_grad():
for images, labels in testloader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()

print(f'Accuracy on test set: {100 * correct / total:.2f}%')

Advantages of PyTorch

Ease of Use – Feels like writing normal Python code.

Debug-Friendly – Errors are easier to trace compared to static graph frameworks.

Strong Ecosystem – Libraries like Hugging Face Transformers are built on PyTorch.

Community Support – Extensive tutorials, forums, and GitHub repositories make learning faster.

Real-World Applications of PyTorch

PyTorch is used in many real-world projects and industries, such as:

Computer Vision – Image classification, object detection, and facial recognition.

Natural Language Processing (NLP) – Sentiment analysis, chatbots, and language translation.

Healthcare – Medical image analysis and predictive diagnostics.

Autonomous Vehicles – Object tracking and decision-making for self-driving cars.

Conclusion

PyTorch has emerged as one of the most powerful and beginner-friendly frameworks for deep learning. Its simplicity, flexibility, and strong community support make it an excellent choice for developers, researchers, and students. In this beginner’s guide, we explored what PyTorch is, why it matters, and even built a simple neural network from scratch.

If you are serious about learning deep learning, starting with the PyTorch Tutorial will give you a strong foundation to move toward advanced projects in AI and machine learning. With continuous practice and exploration, you can go from building simple models to contributing to cutting-edge AI applications.

Top comments (0)