Tensors and automatic differentiation
Understanding how PyTorch computes derivatives automatically.
Goal: Building a data pipeline in the standard PyTorch style and training a convolutional network.
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
class Lines(Dataset):
def __init__(self, n, seed):
g = torch.Generator().manual_seed(seed)
self.y = torch.randint(0, 2, (n,), generator=g)
self.x = torch.rand(n, 1, 16, 16, generator=g) * 0.3
pos = torch.randint(2, 14, (n,), generator=g)
for i in range(n):
if self.y[i] == 0: self.x[i, 0, pos[i], :] += 1 # horizontal
else: self.x[i, 0, :, pos[i]] += 1 # vertical
def __len__(self): return len(self.y)
def __getitem__(self, i): return self.x[i], self.y[i]
torch.manual_seed(0)
train = DataLoader(Lines(800, 1), batch_size=32, shuffle=True)
test = DataLoader(Lines(200, 2), batch_size=100)
net = nn.Sequential(nn.Conv2d(1, 8, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(8, 16, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(1),
nn.Flatten(), nn.Linear(16, 2))
opt = torch.optim.Adam(net.parameters(), 1e-2)
for epoch in range(3):
for xb, yb in train:
loss = nn.functional.cross_entropy(net(xb), yb)
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
acc = sum((net(xb).argmax(1) == yb).sum().item() for xb, yb in test) / 200
print(f"epoch {epoch + 1}: loss={loss.item():.4f} test_acc={acc:.3f}")
print("Number of parameters:", sum(p.numel() for p in net.parameters()))
We define a Dataset that generates 16×16 images containing a horizontal or vertical line, and use a DataLoader for batching and shuffling. The network has two Conv2d layers with pooling, then a linear layer. The same structure is used with real images by changing __getitem__ only.
epoch 1: loss=0.3398 test_acc=1.000 epoch 2: loss=0.0026 test_acc=1.000 epoch 3: loss=0.0005 test_acc=1.000 Number of parameters: 1282
This example was actually run and tested on 21 November 2026 on a CPU — torch 2.15.0, python 3.13.18
Understanding how PyTorch computes derivatives automatically.
Writing the training and evaluation loop by hand on synthetic data.
Implementing the squash function and the routing-by-agreement algorithm between capsules as in the paper by Sabour et al. (2017).
Sections
No section has this name. Press “Search” to search all site content.
Favourites
My results & certificates
My academy progressMy quiz resultsKids’ progressAcademy certificatesQuiz certificatesStart any lesson or quiz and it will show up here so you can get back to it quickly.
Settings
I am the AI Frameworks & Libraries Assistant. Describe your project or ask me about a library, a comparison or a code example, and I will answer from the encyclopedia's database with links and sources.
Answers from the encyclopedia's database only, without a language model and without sending your question to any third party.
The assistant can make mistakes, so check the attached sources.