PyTorch Guide With Code
PyTorch Guide With Code
Introduction to PyTorch
PyTorch is an open-source deep learning framework developed by Facebook AI Research. It is widely used
import torch
import torch.nn as nn
import torchvision
Tensors
Tensors are the fundamental data structures in PyTorch, similar to NumPy arrays but with GPU support.
# Tensors
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
c = a + b
print(c)
print(a.device)
# CUDA
torch.tensor([1.0, 2.0])
Tensor Operations
# Operations
t = torch.randn(3, 3)
PyTorch Guide with Code and Explanations
print(t[0])
print(t.view(-1))
# Autograd
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
out.backward()
print(x.grad)
# Neural Net
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.relu = nn.ReLU()
x = self.relu(self.fc1(x))
x = self.fc2(x)
return x
Loss Functions
# Loss
criterion = nn.CrossEntropyLoss()
Optimizers
# Optimizer
Training Loop
Training involves forward pass, loss calculation, backward pass, and optimizer step.
# Training Loop
optimizer.zero_grad()
output = model(data)
loss.backward()
optimizer.step()
PyTorch provides `Dataset` and `DataLoader` for loading and batching data.
# DataLoader
transform = transforms.ToTensor()
transform=transform)
# Save
torch.save(model.state_dict(), 'model.pth')
# Load
model.load_state_dict(torch.load('model.pth'))
model.eval()