Tensors and automatic differentiation
Understanding how PyTorch computes derivatives automatically.
Goal: Writing the training and evaluation loop by hand on synthetic data.
import torch
from torch import nn
torch.manual_seed(0)
X = torch.rand(1200, 2) * 2 - 1
y = ((X ** 2).sum(1) < 0.5).long()
X_tr, y_tr, X_te, y_te = X[:1000], y[:1000], X[1000:], y[1000:]
model = nn.Sequential(nn.Linear(2, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, 2))
opt = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(1, 201):
model.train()
loss = loss_fn(model(X_tr), y_tr)
opt.zero_grad(); loss.backward(); opt.step()
if epoch % 50 == 0:
model.eval()
with torch.no_grad():
acc = (model(X_te).argmax(1) == y_te).float().mean().item()
print(f"epoch {epoch:3d} loss={loss.item():.4f} test_acc={acc:.3f}")
We generate data with a non-linear rule (points inside a circle), build a network with two hidden layers, then repeat: forward pass, loss computation, zeroing gradients, backward, optimizer step. torch.no_grad() during evaluation saves memory.
epoch 50 loss=0.1008 test_acc=1.000 epoch 100 loss=0.0197 test_acc=0.995 epoch 150 loss=0.0111 test_acc=0.995 epoch 200 loss=0.0077 test_acc=0.995
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.
Building a data pipeline in the standard PyTorch style and training a convolutional network.
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.