🧠 Train a Simple AI Model using PyTorch in Jupyter Notebook

Step 1: Install Jupyter Notebook and PyTorch

Open your terminal or command prompt and run the following commands:

pip install notebook
pip install torch torchvision torchaudio
💡 Tip: Visit PyTorch's official install guide if you need specific commands based on your system.

Step 2: Launch Jupyter Notebook

Run this command in the terminal:

jupyter notebook

The Jupyter interface will open in your browser.

Step 3: Create a New Notebook

In the Jupyter interface, click on NewPython 3 to create a new notebook.

Step 4: Verify PyTorch Installation

import torch
print(torch.__version__)

You should see the version number without errors.

Step 5: Perform Basic Tensor Operations

x = torch.tensor([[1, 2], [3, 4]])
print(x)
y = x + 5
print(y)
print(torch.cuda.is_available())

Step 6: Train a Basic Neural Network

6.1 Import Libraries

import torch.nn as nn
import torch.optim as optim

6.2 Define the Model

class SimpleModel(nn.Module):
    def __init__(self):
        super(SimpleModel, self).__init__()
        self.layer = nn.Linear(2, 1)

    def forward(self, x):
        return self.layer(x)

6.3 Create Model Instance

model = SimpleModel()
print(model)

6.4 Define Data and Setup Training

inputs = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
targets = torch.tensor([[1.0], [2.0]])

loss_fn = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)

6.5 Train the Model

for epoch in range(100):
    optimizer.zero_grad()
    outputs = model(inputs)
    loss = loss_fn(outputs, targets)
    loss.backward()
    optimizer.step()

print("Training completed!")

✅ Simulation Complete

You've successfully trained a simple neural network using PyTorch inside Jupyter Notebook!