Beginner’s Guide to PyTorch: Hands-On Deep Learning Tutorial using Python

Posted by


PyTorch is a popular deep learning framework developed by Facebook’s AI Research Lab. It is known for its flexibility, ease of use, and great support for dynamic computational graphs. In this tutorial, I will guide you through a practical deep learning tutorial using PyTorch, especially designed for beginners.

1. Installation:
First, you need to install PyTorch. You can do this by following the instructions on the official PyTorch website (https://pytorch.org/).

Make sure you have Python installed on your machine as well. You can use Anaconda to easily manage your Python packages.

2. Getting started:
Once you have PyTorch installed, you can start by importing the necessary modules in your Python script:

import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F

3. Creating a simple neural network:
To create a simple neural network using PyTorch, you need to define a class that inherits from nn.Module. This class will represent your neural network architecture. Here is an example of a simple neural network with one hidden layer:

class SimpleNN(nn.Module):
    def __init__(self):
        super(SimpleNN, self).__init__()
        self.fc1 = nn.Linear(784, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

In this example, we define a neural network with one hidden layer (128 units) and an output layer (10 units). The forward method defines the forward pass of the neural network.

4. Loading and preprocessing data:
Next, you need to load and preprocess your data. PyTorch provides convenient utilities for loading common datasets like MNIST, CIFAR-10, etc. You can also create custom datasets using the Dataset and DataLoader classes.

from torchvision import datasets, transforms

transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])

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

In this example, we load the MNIST dataset and apply some preprocessing steps like converting images to tensors and normalizing pixel values.

5. Training your neural network:
Now it’s time to train your neural network. You can define a loss function, an optimizer, and then run the training loop.

model = SimpleNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)

for epoch in range(10):
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        inputs, labels = data
        optimizer.zero_grad()

        outputs = model(inputs.view(-1, 784))
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if i % 100 == 99:
            print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 100))
            running_loss = 0.0

In this training loop, we iterate over the data loader, compute the output of the neural network, calculate the loss, perform backpropagation, and update the weights using the optimizer.

6. Testing your model:
After training, you can evaluate your model on a test dataset to see how well it performs.

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

correct = 0
total = 0
with torch.no_grad():
    for data in testloader:
        inputs, labels = data
        outputs = model(inputs.view(-1, 784))
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

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

In this code snippet, we evaluate the model on the test set and calculate the accuracy.

7. Conclusion:
In this tutorial, we have covered the basics of deep learning using PyTorch. We created a simple neural network, loaded and preprocessed the data, trained the model, and evaluated its performance. I hope this tutorial has helped you get started with PyTorch and deep learning. Happy coding!

0 0 votes
Article Rating

Leave a Reply

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@onurdatascience
7 days ago

Thanks for watching! I hope you enjoyed the video. For more Data content you can subscribe to my channel, I share new videos every week.

You can join to the Data Science discord server of the channel for ask questions, contribute to the discussions and get help from the text channels: https://discord.gg/BaVm6Rt4h8

For those looking to expand their skills, check out my Data Science courses on Udemy:

Data Science Projects: https://www.udemy.com/course/data-science-projects-3/?referralCode=AEC736448BA104C3EC3F
Data Analysis Interview: https://www.udemy.com/course/data-analysis-interview/?referralCode=3270B750A08BE82F7994
Python for Data Analytics: https://www.udemy.com/course/python-for-data-analytics/?referralCode=0782B89299FFF7561184
Machine Learning with Python: https://www.udemy.com/course/python-machine-learning-course/?referralCode=09455A4817E14D6B83D8
Python Programming: https://www.udemy.com/course/python-basics-i/?referralCode=3C8A77721CCEA802B372
Time Series Analysis: https://www.udemy.com/course/python-for-time-series/?referralCode=439816EE7E65C91F1B55
Natural Language Processing (NLP): https://www.udemy.com/course/python-natural-language-processing/?referralCode=AFFEAA30617CA01E6819

Happy learning!

@ДмитрийКолышницын-с2л
7 days ago

It's unreal!!!!!

@AlukoOoreoluwa-i5u
7 days ago

Nice

@MyChusko
7 days ago

Hi Onur! What's the difference between Pytorch and Sci-kit Learn? I'm currently focused on Machine Learning and have heard about Pytorch and Keras, but so far I have only used sklearn.

@faturismee
7 days ago

Lets goo this is what im looking for. btw thanks for the video onur. Do you have a recommended resource to learn maths for machine learning ? maybe like books or yt channel or smth. Thanks again 😀

5
0
Would love your thoughts, please comment.x
()
x