Physics-informed neural networks tutorial: theory, code and pitfalls
Updated · Scientifically reviewed by Dinkar Mishra, PhD on
Short answer
A physics-informed neural network (PINN) is a neural network u_θ(x, t) trained so that it satisfies a differential equation and its boundary conditions: the loss adds the squared PDE residual, computed with automatic differentiation at sampled points, to the squared boundary and data errors. PINNs need no mesh and can combine sparse data with physics, but they train slowly, can fail on stiff, multi-scale or high-frequency problems, and are rarely faster than classical solvers for a single forward problem.
Who this is for
Physicists, engineers and data scientists who want to understand and try physics-informed neural networks, and judge when they are worth using.
Software
Python ≥ 3.9PyTorch ≥ 2.0
Prerequisites
- Python 3.9+ and PyTorch 2.x (
pip install torch). A CPU is enough for this example. - Basic calculus and differential equations, and familiarity with training a neural network (loss, optimiser).
Step 1: the idea
For a PDE on a domain with boundary condition , a PINN approximates with a network and minimises
Derivatives of with respect to its inputs come from automatic differentiation, so no mesh is needed: the residual is evaluated at “collocation points” sampled in the domain.
Step 2: a complete example
We solve the 1D Poisson problem on with , whose exact solution is . Knowing the exact answer lets us verify the PINN.
import math
import torch
torch.manual_seed(0)
# Problem: u''(x) = -pi^2 sin(pi x) on [0, 1], u(0) = u(1) = 0. Exact: u = sin(pi x).
net = torch.nn.Sequential(
torch.nn.Linear(1, 32), torch.nn.Tanh(),
torch.nn.Linear(32, 32), torch.nn.Tanh(),
torch.nn.Linear(32, 1),
)
opt = torch.optim.Adam(net.parameters(), lr=1e-3)
x_col = torch.linspace(0.0, 1.0, 101).reshape(-1, 1).requires_grad_(True) # collocation points
x_bc = torch.tensor([[0.0], [1.0]]) # boundary points
def residual(x):
u = net(x)
du = torch.autograd.grad(u, x, torch.ones_like(u), create_graph=True)[0]
d2u = torch.autograd.grad(du, x, torch.ones_like(du), create_graph=True)[0]
return d2u + math.pi**2 * torch.sin(math.pi * x)
for step in range(5000):
opt.zero_grad()
loss_pde = residual(x_col).pow(2).mean()
loss_bc = net(x_bc).pow(2).mean()
loss = loss_pde + 10.0 * loss_bc # weight boundary conditions more strongly
loss.backward()
opt.step()
if step % 1000 == 0:
print(f"step {step:5d} loss {loss.item():.3e}")
x_test = torch.linspace(0.0, 1.0, 201).reshape(-1, 1)
with torch.no_grad():
err = (net(x_test) - torch.sin(math.pi * x_test)).abs().max().item()
print(f"max |u_pinn - u_exact| = {err:.2e}")
Step 3: what each part does
- Network. Smooth activations (
tanh) are used because second derivatives of ReLU networks are zero almost everywhere. - Residual. Two calls to
torch.autograd.gradwithcreate_graph=Truegive while keeping the graph for back-propagation. - Loss weighting. The factor 10 on the boundary term prevents the optimiser from satisfying the PDE while ignoring the boundary conditions, a common failure.
Verify
Run the script (python pinn_poisson.py). The loss should fall by several orders of magnitude, and the final maximum error should be small compared with the solution amplitude of 1. Then check:
- Different seeds. Repeat with
torch.manual_seed(1)and2. The error should stay similar; large variation signals an unreliable setup. - Fewer collocation points (for example 11 instead of 101). The error between collocation points grows. PINNs do not guarantee accuracy away from sampled points.
- Harder solution. Replace with (and the forcing accordingly). Training becomes much harder because of spectral bias. This is the classic PINN failure mode.
Troubleshooting
- The loss plateaus early: lower the learning rate after the plateau, or finish with L-BFGS (
torch.optim.LBFGS), which often reaches much lower losses on small PINNs. - Boundary conditions not satisfied: raise their weight, or build them into the network as a hard constraint, for example , which satisfies automatically.
- Training is very slow in higher dimensions: the cost of residuals and higher derivatives grows quickly. Consider a classical solver, or a neural operator if you need many solutions. Compare approaches in PINN vs finite element method.
Assumptions and limitations
- The example is deliberately simple. Real problems need input and output scaling, adaptive sampling of collocation points and careful loss balancing.
- A low training loss does not guarantee an accurate solution. Always compare against an exact solution or a trusted numerical solver, the same discipline as in simulation verification.
- Errors depend on random initialisation, hardware and library versions, so report results over several seeds.
Frequently asked questions
Are PINNs faster than finite-element or finite-difference solvers?+
For a single forward problem with known parameters, usually not: a well-tuned classical solver is typically faster and more accurate. PINNs are more attractive for inverse problems (inferring parameters from sparse data), irregular data, or when the same trained network is queried many times.
Why does my PINN converge to a wrong or trivial solution?+
Common causes are badly balanced loss terms (boundary conditions ignored), the network's spectral bias against high-frequency solutions, stiff or multi-scale PDEs, poor input scaling, and too few collocation points. Remedies include loss weighting, input normalisation, curriculum or causal training, and hard-coded boundary conditions.
What is the difference between a PINN and a neural operator?+
A PINN usually represents one solution of one problem instance. A neural operator (such as a Fourier neural operator or DeepONet) learns a mapping from inputs such as initial conditions or coefficients to solutions, so a trained model can solve many instances quickly.
Can PINNs be used for plasma physics?+
They have been explored for problems such as equilibrium reconstruction and inferring transport coefficients from data. Kinetic plasma problems are high-dimensional and multi-scale, which is challenging for PINNs. Results should always be checked against established solvers.
References
- Raissi, Perdikaris & Karniadakis, Physics-informed neural networks, J. Comput. Phys. 378, 686 (2019) · Peer-reviewed article
- Karniadakis et al., Physics-informed machine learning, Nat. Rev. Phys. 3, 422 (2021) · Review article
- Wang, Teng & Perdikaris, Understanding and mitigating gradient flow pathologies in PINNs, SIAM J. Sci. Comput. 43, A3055 (2021) · Peer-reviewed article
- Krishnapriyan et al., Characterizing possible failure modes in physics-informed neural networks (NeurIPS 2021) · Conference paper (arXiv)
- PyTorch autograd documentation · PyTorch
Want this set up and verified for you?
We install, configure and validate scientific software on your workstation, cluster or cloud, and train your team to run it.
Services listed on this page are available today. Products marked “early access” or “in development” on our platform page are not yet generally available.
Spotted an error or an outdated command? Tell us. We correct verified issues promptly.