Tuesday, August 26, 2025

thumbnail

Building a Neural Network with PyTorch: A Beginner’s Guide

 🔧 Building a Neural Network with PyTorch: A Beginner’s Guide

🧠 What is PyTorch?


PyTorch is an open-source deep learning framework developed by Facebook’s AI Research Lab (FAIR). It’s known for being:


Easy to use and debug


Pythonic and dynamic (you can change things on the fly)


Great for research and production


✅ Step-by-Step Guide

📦 Step 1: Install PyTorch


Use the command suitable for your system from https://pytorch.org

, or use pip:


pip install torch torchvision


🧾 Step 2: Import Libraries

import torch

import torch.nn as nn

import torch.optim as optim

from torchvision import datasets, transforms

from torch.utils.data import DataLoader


📊 Step 3: Load and Prepare Data

# Download and normalize the MNIST dataset

transform = transforms.ToTensor()


train_dataset = datasets.MNIST(root='data', train=True, transform=transform, download=True)

test_dataset = datasets.MNIST(root='data', train=False, transform=transform)


train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)

test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)


🧱 Step 4: Define the Neural Network

class SimpleNN(nn.Module):

    def __init__(self):

        super(SimpleNN, self).__init__()

        self.flatten = nn.Flatten()

        self.fc1 = nn.Linear(28*28, 128)

        self.relu = nn.ReLU()

        self.fc2 = nn.Linear(128, 10)


    def forward(self, x):

        x = self.flatten(x)

        x = self.relu(self.fc1(x))

        x = self.fc2(x)

        return x


⚙️ Step 5: Initialize Model, Loss Function, Optimizer

model = SimpleNN()


criterion = nn.CrossEntropyLoss()             # Loss function

optimizer = optim.Adam(model.parameters(), lr=0.001)  # Optimizer


🏋️ Step 6: Train the Model

for epoch in range(5):  # 5 epochs

    for images, labels in train_loader:

        outputs = model(images)

        loss = criterion(outputs, labels)


        optimizer.zero_grad()

        loss.backward()

        optimizer.step()


    print(f"Epoch [{epoch+1}/5], Loss: {loss.item():.4f}")


📈 Step 7: Evaluate the Model

correct = 0

total = 0

with torch.no_grad():

    for images, labels in test_loader:

        outputs = model(images)

        _, predicted = torch.max(outputs.data, 1)

        total += labels.size(0)

        correct += (predicted == labels).sum().item()


print(f"Test Accuracy: {100 * correct / total:.2f}%")


🎯 Summary

Step What You Do

Install PyTorch pip install torch torchvision

Load Data Use torchvision.datasets and DataLoader

Build Model Use nn.Module to define a network

Train Use loss and optimizer to learn from data

Evaluate Test performance on unseen data

✅ Tips for Beginners


Use Google Colab if you don’t have a GPU.


Wrap training in functions for clarity.


Explore advanced models like CNNs or RNNs as your next step.

Learn AI ML Course in Hyderabad

Read More

How to Use TensorFlow for Deep Learning Projects

The Role of Backpropagation in Neural Networks

Understanding Recurrent Neural Networks (RNNs) and Their Use Cases

Building a Convolutional Neural Network (CNN) from Scratch

Visit Our Quality Thought Training Institute in Hyderabad

Get Directions

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive