Tensors and automatic differentiation

BeginnerDeep learning and building neural networksBasics

Goal: Understanding how PyTorch computes derivatives automatically.

Python — example.py
import torch

x = torch.tensor(2.0, requires_grad=True)
y = x ** 2 + 3 * x
y.backward()
print("y =", y.item())
print("dy/dx =", x.grad.item())

a = torch.arange(6, dtype=torch.float32).reshape(2, 3)
print("Tensor shape:", tuple(a.shape), "| sum:", a.sum().item())
print("Available device:", "cuda" if torch.cuda.is_available() else "cpu")

Code explanation

With requires_grad=True PyTorch records operations in a computation graph, and after backward() the derivative is in .grad. Here y = x² + 3x, so the derivative is 2x + 3, which equals 7 at x=2.

Requirements

Shell
pip install torch

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

y = 10.0
dy/dx = 7.0
Tensor shape: (2, 3) | sum: 15.0
Available device: cpu

This example was actually run and tested on 21 November 2026 on a CPU — torch 2.15.0, python 3.13.18

Libraries used

Related examples

ResearchPyTorchRun and tested

A capsule layer with dynamic routing

Implementing the squash function and the routing-by-agreement algorithm between capsules as in the paper by Sabour et al. (2017).

Convolutional networks · Scientific research