Physics-informed neural networks

Teach a neural network the laws of physics, not just the data — and it can solve differential equations, even ones with unknown coefficients.

⏱ 35 minNeeds: Chapters 2, 5, 7, 11–13A PINN that trains in your browser
In plain words

An ordinary neural network learns from examples: "at these points, the answer is this". A physics-informed neural network also gets told the rule: "and everywhere, the answer must satisfy this differential equation". We measure how badly the network breaks the rule — the residual — at many points, and train the network to make that small. No grid, no mesh: just a network, a loss, and gradient descent.

Companion chapters

How the derivatives are computed: Chapter 14. A PINN shrunk to one neuron and two points, every number shown: Chapter 17. Does it converge? Chapter 21. Where PINNs are used, live latest papers and project ideas: Chapter 22.

You will learn
Level 1 · basicWhy plain networks fail; the PINN idea Level 2 · standardA worked example; inverse problems Level 3 · advancedWhen training is hard, and remedies
Simplest example first · a "network" with two parameters

Solve $u'(x) = 1$ on $[0, 1]$ with $u(0) = 0$ (answer: $u = x$). Use the simplest possible model, a straight line $u_\theta(x) = a + b\,x$ with parameters $\theta = (a, b)$. Its derivative is $u_\theta' = b$, so the residual at every point is $r = b - 1$, and the boundary error is $u_\theta(0) - 0 = a$. The PINN loss is $$\mathcal L(a, b) = \underbrace{(b - 1)^2}_{\text{equation}} + \underbrace{a^2}_{\text{boundary}}.$$ It is zero exactly at $a = 0$, $b = 1$: the true solution. Gradient descent finds it. A real PINN replaces the straight line by a neural network and the simple ODE (Ordinary Differential Equation) by a PDE (Partial Differential Equation) — but the loss is built in exactly this way.

From neural networks to PINNs: why plain networks are not enough

Animation: a neuron, then a network, then a data loss, then a physics loss, combining into a PINN.
Watch: From one neuron to a PINN in four steps.

Chapters 12 and 13 showed that a neural network can fit almost any data. So why not simply train a network on measurements of a physical system? Because data-only networks have weaknesses that matter a great deal in science:

A data-only neural network…A physics-informed neural network (PINN)…
needs many data points, which experiments rarely provideuses the equation at thousands of free collocation points, so a few measurements suffice
fits the data but can do anything between and beyond the points (no extrapolation)is forced to obey the physics everywhere in the domain, including where there is no data
may violate boundary conditions and physical lawshas boundary/initial conditions and the equation in its loss (or built in exactly)
overfits noisy measurementsthe equation acts as a regulariser, smoothing out noise (Chapter 9, Section 3)
gives derivatives ($u'$, $u''$) with no guarantee of quality, even if values look righttrains the derivatives directly, because they appear in the residual
is a black box: its weights have no physical meaningcan include unknown physical parameters (diffusivity, permeability) as trainable, interpretable numbers

For this to work, the network must approximate not only the solution but also its derivatives. The classical universal approximation theorem (Chapter 13) is about function values only; a stronger version covers derivatives too.

Theorem · Universal approximation of a function and its derivatives

Let the activation $\sigma$ be $k$ times continuously differentiable and not a polynomial. Then for every $k$-times continuously differentiable function $u$ on a compact set $K\subset\mathbb R^d$ and every $\varepsilon > 0$ there is a one-hidden-layer network $u_\theta$ such that $$\max_{|\alpha| \le k}\ \sup_{x\in K}\ \big|\partial^\alpha u(x) - \partial^\alpha u_\theta(x)\big| < \varepsilon,$$ i.e. the network approximates $u$ and all its derivatives up to order $k$ simultaneously. (Similar results hold in Sobolev norms.)

Hornik, Stinchcombe & White, "Universal approximation of an unknown mapping and its derivatives using multilayer feedforward networks", Neural Networks 3(5) (1990) 551–560; Pinkus, "Approximation theory of the MLP model in neural networks", Acta Numerica 8 (1999) 143–195.

Two practical consequences: the activation must be smooth enough for the order of the equation — for a second-order equation, $\tanh$ or $\sin$ work, the Rectified Linear Unit (ReLU) does not, since its second derivative is zero almost everywhere — and the network needs enough neurons. Existence, as always, does not guarantee that training will find the weights; Section 4 discusses when it fails.

Data-only network vs PINN on a damped oscillatoru″ + 2ζω u′ + ω² u = 0, u(0) = 1, u′(0) = 0 · data only for t ≤ 0.38
exact solutiondata-only networkPINN (data + equation)10 noisy measurements
Press ▶ Train. Both networks have the same architecture (1 input, 24 tanh neurons, 1 output), the same data and the same optimiser (Adam: Adaptive Moment Estimation); only the loss differs.
The data-only network fits the ten points and then does whatever it likes beyond them. The PINN sees the same ten points, plus the equation at 60 collocation points across $[0, 1]$ and the two initial conditions — and follows the oscillation through the region with no data. The same idea, on harder problems, is why PINNs are used.

1. The idea in one formula

Animation: a data-only network and a PINN trained on the same ten early pendulum measurements; only the PINN keeps following the exact swing.
Watch: Same network, same 10 measurements. Adding the equation at collocation points (violet ticks) is what lets the PINN predict beyond the data. Try it in the pendulum lab.

Take a differential equation on a domain $\Omega$ with boundary $\partial\Omega$: $$\mathcal N[u](x) = f(x)\ \ \text{in } \Omega, \qquad \mathcal B[u](x) = g(x)\ \ \text{on } \partial\Omega,$$ where $\mathcal N$ is a differential operator (for example $\mathcal N[u] = -u''$) and $\mathcal B$ gives the boundary or initial conditions. Replace the unknown $u$ by a neural network $u_\theta$ (Chapter 12) and define the residual $r_\theta(x) = \mathcal N[u_\theta](x) - f(x)$. Then minimise

Definition · PINN loss

$$\mathcal L(\theta) = \underbrace{\frac{1}{N_r}\sum_{i=1}^{N_r} \big|r_\theta(x_i)\big|^2}_{\text{physics: PDE residual}} \;+\; \lambda_b\,\underbrace{\frac{1}{N_b}\sum_{j=1}^{N_b}\big|\mathcal B[u_\theta](x^b_j) - g(x^b_j)\big|^2}_{\text{boundary / initial conditions}} \;+\; \lambda_d\,\underbrace{\frac{1}{N_d}\sum_{k=1}^{N_d}\big|u_\theta(x^d_k) - d_k\big|^2}_{\text{measurements (optional)}}$$ The points $x_i$ are collocation points in $\Omega$; $\lambda_b, \lambda_d$ are weights. The derivatives inside $\mathcal N[u_\theta]$ are computed exactly by automatic differentiation.

Raissi, Perdikaris & Karniadakis, "Physics-informed neural networks: A deep learning framework for solving forward and inverse problems involving nonlinear partial differential equations", J. Comput. Phys. 378 (2019) 686–707. Precursor: Lagaris, Likas & Fotiadis, "Artificial neural networks for solving ordinary and partial differential equations", IEEE Trans. Neural Networks 9(5) (1998) 987–1000.
Network$u_\theta(x)$: an MLP with smooth activation (tanh).
Differentiateautodiff gives $u_\theta'$, $u_\theta''$, … exactly at any point.
Residualplug into the equation: $r_\theta = \mathcal N[u_\theta] - f$ at collocation points.
Trainminimise residual + boundary (+ data) loss with Adam, then L-BFGS.
Anatomy of a PINNheat equation u_t = α u_xx; click a stage

Recall from Chapter 3: the residual sum is a Monte Carlo (or rectangle-rule) estimate of $\int_\Omega r_\theta^2\,dx$. If the loss is zero and the problem is well-posed, $u_\theta$ is the solution.

2. A worked example, by hand

Problem: $-u''(x) = \pi^2\sin(\pi x)$ on $(0,1)$, $u(0) = u(1) = 0$. Exact solution $u = \sin(\pi x)$. Network with one hidden layer of $n$ tanh neurons: $$u_\theta(x) = \sum_{j=1}^n v_j \tanh(w_j x + b_j) + c.$$ With $s_j = \tanh(w_jx + b_j)$ and $\tanh' = 1 - \tanh^2$, the chain rule gives $$u_\theta'(x) = \sum_j v_j w_j (1 - s_j^2), \qquad u_\theta''(x) = \sum_j v_j w_j^2\,\big(-2 s_j (1 - s_j^2)\big).$$ So the residual $r_\theta(x) = -u_\theta''(x) - \pi^2\sin(\pi x)$ is an explicit function of the parameters, and the loss is $$\mathcal L(\theta) = \frac1N\sum_{i=1}^N r_\theta(x_i)^2 + \lambda\big(u_\theta(0)^2 + u_\theta(1)^2\big).$$ Differentiating once more with respect to $v_j, w_j, b_j, c$ gives $\nabla_\theta\mathcal L$, and Adam does the rest. That is exactly what the simulation below does — about 60 lines of JavaScript, no libraries.

A PINN training in your browsertanh network, Adam, loss = residual + boundary (+ data)
exact solutionPINN u_θ(x)collocation points (residual measured here)boundary / data points
Press ▶ Train.
No solution values are given inside the domain — only the equation and the boundary conditions. Experiments: (1) use only 3 collocation points — the network satisfies the equation there but not between them; (2) set λ very small — the equation is satisfied but the boundary is ignored, and the solution drifts; (3) try the high-frequency problem with 4 neurons — spectral bias makes it hard; (4) the inverse problem learns $k$ and $u$ together.
Loss historylog scale; total, residual and boundary/data parts
total lossresidual partboundary + data part

3. Inverse problems: where PINNs shine

Suppose a quantity decays as $u' = -k u$ but the rate $k$ is unknown, and we have a few noisy measurements $d_1, \dots, d_6$. Make $k$ a trainable parameter alongside the network weights and minimise $$\mathcal L(\theta, k) = \frac1N\sum_i \big(u_\theta'(x_i) + k\,u_\theta(x_i)\big)^2 + \lambda\,\frac16\sum_{m=1}^{6}\big(u_\theta(x_m) - d_m\big)^2.$$ The physics fills the gaps between the measurements, and the measurements pin down $k$. Choose "Inverse" above. The same principle estimates diffusivity in a heat problem, permeability in a reservoir from well pressures, or infection rates in an SIR model (Chapter 5) — tasks that are awkward for classical solvers because they require repeated forward solves inside an optimisation loop.

Real-world applications reported in the literature

4. When training is hard — and what helps

PINNs are elegant but not a free lunch. Known difficulties, with representative remedies:

DifficultyWhat happensTypical fixes
Loss imbalanceresidual and boundary terms have very different sizes and gradients; one dominatesadaptive loss weights (Wang, Teng & Perdikaris, SIAM J. Sci. Comput. 43(5), 2021, A3055–A3081); hard constraints
Spectral biashigh-frequency or multi-scale solutions are learned slowlyFourier feature embeddings; more neurons; domain decomposition (XPINNs, Jagtap & Karniadakis 2020)
Ill-conditioning / stiffnessloss landscape is a long narrow valley (Chapter 11); training stallsAdam then L-BFGS; curriculum training (Krishnapriyan et al., NeurIPS 2021)
Causality in timelater times are fitted before earlier ones are correctcausal weighting (Wang, Sankaran & Perdikaris, Comput. Methods Appl. Mech. Eng. 421, 2024, 116813)
Costfor a single forward problem in low dimension, classical solvers are usually much faster and more accurateuse PINNs where they add value: inverse problems, sparse data, high dimensions, irregular geometry
Hard constraints (Lagaris trial functions)

Instead of penalising boundary errors, build the boundary condition into the network output. For $u(0) = u(1) = 0$ use $$\tilde u_\theta(x) = x(1 - x)\,u_\theta(x),$$ which satisfies both conditions exactly for any $\theta$. For $u(0) = 1$ use $\tilde u_\theta(x) = 1 + x\,u_\theta(x)$. The loss then contains only the residual.

Lagaris, Likas & Fotiadis (1998); Lu, Pestourie, Yao, Wang, Verdugo & Johnson, "Physics-informed neural networks with hard constraints for inverse design", SIAM J. Sci. Comput. 43(6) (2021) B1105–B1132.
What theory says (in brief)

Error estimates for PINNs bound the error of $u_\theta$ by the training loss plus a quadrature (sampling) error, provided the PDE is stable in a suitable sense: small residuals must imply small errors. This is exactly the well-posedness of Chapter 7 — physics-informed learning inherits the mathematics of the PDE.

Mishra & Molinaro, "Estimates on the generalization error of physics-informed neural networks for approximating PDEs", IMA J. Numer. Anal. 43(1) (2023) 1–43; Shin, Darbon & Karniadakis, "On the convergence of PINNs for linear second-order elliptic and parabolic type PDEs", Commun. Comput. Phys. 28(5) (2020) 2042–2074.

5. Code you can run

5.1 A PINN with NumPy only (runs here in the browser)

The same maths as the simulation, written out in Python: the derivatives of the network with respect to $x$ and with respect to the parameters are coded by hand.

import numpy as np
import matplotlib.pyplot as plt

# PINN with NumPy only:  -u''(x) = pi^2 sin(pi x),  u(0) = u(1) = 0
# network u(x) = sum_j v_j tanh(w_j x + b_j) + c ; derivatives w.r.t. x by hand
rng = np.random.default_rng(1)
n = 12                                           # hidden neurons
P = {"w": rng.normal(0, 2, n), "b": rng.normal(0, 1, n), "v": rng.normal(0, .3, n), "c": np.zeros(1)}
x = np.linspace(0, 1, 30)                        # collocation points
xb, gb = np.array([0., 1.]), np.array([0., 0.])  # boundary points and values
f = np.pi**2 * np.sin(np.pi * x)
lam = 10.0                                       # weight of the boundary loss

def grads(P):
    w, b, v = P["w"], P["b"], P["v"]
    s = np.tanh(np.outer(x, w) + b); d = 1 - s**2; q = -2 * s * d; dq = -2 * d * (1 - 3 * s**2)
    uxx = (v * w**2 * q).sum(1)                  # u''(x)
    r = -uxx - f                                 # PDE residual
    sb = np.tanh(np.outer(xb, w) + b); ub = sb @ v + P["c"][0]; eb = ub - gb
    N = len(x)
    g = {"v": (2/N) * (r[:, None] * -(w**2 * q)).sum(0) + 2*lam * (eb[:, None] * sb).sum(0),
         "b": (2/N) * (r[:, None] * -(v * w**2 * dq)).sum(0) + 2*lam * (eb[:, None] * v * (1 - sb**2)).sum(0),
         "w": (2/N) * (r[:, None] * -(2*v*w*q + v*w**2*dq*x[:, None])).sum(0) + 2*lam * (eb[:, None] * v * (1 - sb**2) * xb[:, None]).sum(0),
         "c": np.array([2*lam * eb.sum()])}
    return g, np.mean(r**2) + lam * np.sum(eb**2)

m = {k: 0 * p for k, p in P.items()}; s2 = {k: 0 * p for k, p in P.items()}; hist = []
for t in range(1, 8001):                         # Adam
    g, L = grads(P); hist.append(L)
    for k in P:
        m[k] = .9 * m[k] + .1 * g[k]; s2[k] = .999 * s2[k] + .001 * g[k]**2
        P[k] -= 0.01 * (m[k] / (1 - .9**t)) / (np.sqrt(s2[k] / (1 - .999**t)) + 1e-8)

xx = np.linspace(0, 1, 200); u = np.tanh(np.outer(xx, P["w"]) + P["b"]) @ P["v"] + P["c"][0]
print("final loss %.2e   max error %.2e" % (hist[-1], np.abs(u - np.sin(np.pi * xx)).max()))
fig, ax = plt.subplots(1, 2, figsize=(9, 3.4))
ax[0].plot(xx, np.sin(np.pi * xx), "k--", label="exact"); ax[0].plot(xx, u, label="PINN"); ax[0].legend()
ax[1].semilogy(hist); ax[1].set_xlabel("iteration"); ax[1].set_ylabel("loss")
plt.tight_layout(); plt.show()

5.2 The same problem in PyTorch (automatic differentiation)

Here torch.autograd.grad computes $u'$ and $u''$ for us. Tested with PyTorch 2.x: it reaches a maximum error of about $10^{-3}$ in roughly 10 seconds on a laptop CPU.

# PINN for -u''(x) = pi^2 sin(pi x) on (0, 1), u(0) = u(1) = 0.  Exact solution: u = sin(pi x)
import torch, math
torch.manual_seed(0)

net = torch.nn.Sequential(                      # u_theta(x): 1 -> 20 -> 20 -> 1
    torch.nn.Linear(1, 20), torch.nn.Tanh(),
    torch.nn.Linear(20, 20), torch.nn.Tanh(),
    torch.nn.Linear(20, 1))

x_col = torch.rand(100, 1, requires_grad=True)  # collocation points inside (0, 1)
x_bc = torch.tensor([[0.0], [1.0]])             # boundary points
f = lambda x: math.pi**2 * torch.sin(math.pi * x)

def residual(x):
    u = net(x)
    u_x = torch.autograd.grad(u, x, torch.ones_like(u), create_graph=True)[0]
    u_xx = torch.autograd.grad(u_x, x, torch.ones_like(u_x), create_graph=True)[0]
    return -u_xx - f(x)                         # zero when the PDE holds

opt = torch.optim.Adam(net.parameters(), lr=1e-3)
for step in range(5001):
    loss_pde = residual(x_col).pow(2).mean()
    loss_bc = net(x_bc).pow(2).mean()
    loss = loss_pde + 10 * loss_bc
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 1000 == 0:
        print(f"step {step:5d}  loss_pde {loss_pde.item():.2e}  loss_bc {loss_bc.item():.2e}")

x = torch.linspace(0, 1, 201).reshape(-1, 1)
err = (net(x) - torch.sin(math.pi * x)).abs().max().item()
print(f"max error vs sin(pi x): {err:.2e}")

5.3 The heat equation in space and time (PyTorch)

Now the network takes two inputs $(x, t)$. The loss has three parts: PDE residual inside, initial condition at $t = 0$, boundary conditions at $x = 0, 1$. Tested: maximum error about $5\times10^{-3}$ after 4000 Adam steps (about 20 s on a CPU).

# PINN for the heat equation u_t = alpha u_xx on (0,1) x (0,0.5],
# u(x,0) = sin(pi x), u(0,t) = u(1,t) = 0.  Exact: u = exp(-alpha pi^2 t) sin(pi x)
import torch, math
torch.manual_seed(0)
alpha = 0.1
net = torch.nn.Sequential(torch.nn.Linear(2, 32), torch.nn.Tanh(),
                          torch.nn.Linear(32, 32), torch.nn.Tanh(),
                          torch.nn.Linear(32, 32), torch.nn.Tanh(),
                          torch.nn.Linear(32, 1))
u = lambda x, t: net(torch.cat([x, t], dim=1))
d = lambda y, x: torch.autograd.grad(y, x, torch.ones_like(y), create_graph=True)[0]

N = 2000
x_r = torch.rand(N, 1, requires_grad=True); t_r = (0.5 * torch.rand(N, 1)).requires_grad_()   # interior
x_i = torch.rand(200, 1); t_i = torch.zeros(200, 1)                                           # t = 0
t_b = 0.5 * torch.rand(200, 1); x_b = torch.randint(0, 2, (200, 1)).float()                  # x = 0 or 1

opt = torch.optim.Adam(net.parameters(), lr=1e-3)
for step in range(4001):
    U = u(x_r, t_r)
    res = d(U, t_r) - alpha * d(d(U, x_r), x_r)
    loss = res.pow(2).mean() + (u(x_i, t_i) - torch.sin(math.pi * x_i)).pow(2).mean() + u(x_b, t_b).pow(2).mean()
    opt.zero_grad(); loss.backward(); opt.step()
    if step % 1000 == 0: print(f"step {step:5d}  loss {loss.item():.2e}")

xs = torch.linspace(0, 1, 101).reshape(-1, 1)
for T in [0.0, 0.25, 0.5]:
    ts = torch.full_like(xs, T)
    exact = torch.exp(torch.tensor(-alpha * math.pi**2 * T)) * torch.sin(math.pi * xs)
    print(f"t = {T}:  max error {(u(xs, ts) - exact).abs().max().item():.2e}")

Libraries that automate all of this: DeepXDE (Lu, Meng, Mao & Karniadakis, SIAM Review 63(1), 2021, 208–228), NVIDIA PhysicsNeMo (formerly Modulus), and NeuralPDE.jl in Julia.

In a PINN for $-u'' = f$, where are the derivatives $u_\theta''$ computed?

Right: the network is a known composition of smooth functions, so autodiff gives exact derivatives at any point — no grid and no step size $h$.

The residual loss is nearly zero but the PINN solution is wrong everywhere by a constant shift. The most likely cause?

Right: the PDE alone has many solutions (e.g. $u + C$ for $-u'' = f$). The boundary term picks the right one; if its weight is too small it is ignored. Increase $\lambda$ or use a hard constraint.

PINNs: frequently asked questions

What is a physics-informed neural network (PINN)? A neural network $u_\theta(x,t)$ trained so that it satisfies a differential equation, its initial and boundary conditions and any available measurements. The equation enters the loss function through its residual, computed with automatic differentiation.

What do I need to know before learning PINNs? Derivatives and the chain rule (Chapter 2), differential equations (Chapters 5 and 7), gradient descent (Chapter 11) and neural networks with backpropagation (Chapters 12–13). This book builds all of them from the beginning.

Why do PINNs work at all? Smooth neural networks can approximate a function together with its derivatives (the theorem above), and automatic differentiation computes those derivatives exactly; minimising the residual then drives the network towards the solution of a well-posed problem.

Are PINNs better than finite element or finite difference methods? Not for a single, standard forward problem in one to three dimensions, where classical solvers are usually faster and more accurate. PINNs are most useful for inverse problems, sparse or noisy data, unknown parameters and some high-dimensional problems (Chapter 9).

Which activation function should a PINN use? A smooth one such as $\tanh$ or $\sin$; the Rectified Linear Unit (ReLU) has zero second derivative and fails for second-order equations.

Can I run PINN code without installing anything? Yes — the simulations on this page train PINNs in your browser, and the PyTorch code in Section 5 runs in Google Colab.

Key takeaways

Further reading