PyTorch is a popular open-source machine learning framework developed by Facebook AI Research. It’s widely adopted in research and production for developing deep learning models due to its ease of use, flexibility, and powerful GPU support.
To install PyTorch using pip:
pip install torch torchvision torchaudio
Using conda:
conda install pytorch torchvision torchaudio -c pytorch
Refer to the official guide for platform-specific instructions: pytorch.org/get-started
Feature | PyTorch | TensorFlow |
---|---|---|
Computation Graph | Dynamic (eager) | Static (default) |
Syntax | Pythonic | Graph-oriented |
Debugging | Intuitive (Python tools) | More complex |
Learning Curve | Beginner friendly | Moderate |
import torch
# Create tensors
a = torch.tensor([2.0, 3.0])
b = torch.tensor([4.0, 5.0])
# Add tensors
c = a + b
print("Sum:", c)
# Check GPU availability and move tensors
if torch.cuda.is_available():
a = a.to('cuda')
b = b.to('cuda')
print("Tensors moved to GPU")
import torch
# Create a 2D tensor
matrix = torch.tensor([[1, 2], [3, 4]])
# Reshape into 1D
flattened = matrix.view(-1)
# Reshape into 2x2 again
reshaped = flattened.view(2, 2)
print("Original Matrix:", matrix)
print("Flattened:", flattened)
print("Reshaped:", reshaped)
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(2, 2)
def forward(self, x):
x = torch.relu(self.fc1(x))
return x
model = Net()
input_tensor = torch.tensor([[1.0, 2.0]])
output = model(input_tensor)
print(output)
import torch.optim as optim
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
target = torch.tensor([[0.0, 1.0]])
loss = criterion(output, target)
print("Loss:", loss.item())
loss.backward()
optimizer.step()
for epoch in range(5):
optimizer.zero_grad()
output = model(input_tensor)
loss = criterion(output, target)
loss.backward()
optimizer.step()
print("Epoch", epoch, "Loss:", loss.item())
Epoch 0 Loss: 0.8562
Epoch 1 Loss: 0.7037
Epoch 2 Loss: 0.5891
Epoch 3 Loss: 0.5035
Epoch 4 Loss: 0.4397
# Sample binary classification
class BinaryClassifier(nn.Module):
def __init__(self):
super().__init__()
self.layer = nn.Linear(2, 1)
def forward(self, x):
return torch.sigmoid(self.layer(x))
model = BinaryClassifier()
data = torch.tensor([[0.5, 0.8]])
prediction = model(data)
print("Predicted value:", prediction.item())
The Titanic dataset is one of the most popular introductory datasets for learning classification tasks in AI and machine learning. Using features like age, gender, and class, the goal is to predict whether a passenger survived. It's widely used with PyTorch to demonstrate model training, evaluation, and improvement techniques.
Run the PyTorch Code at Colab ( or download from Github )The Iris dataset is a classic in machine learning, featuring measurements of three types of iris flowers. It’s ideal for beginners learning how to train and test classification models with PyTorch, thanks to its simplicity and well-separated classes.
Run the Iris Classifier at Colab ( or download from Github )PyTorch offers a great starting point for learning deep learning due to its simplicity and flexibility. With strong community support and rich libraries, it’s a go-to tool for modern AI development.