PINN Python example: inferring a diffusion coefficient from noisy data
Updated · Scientifically reviewed by Dinkar Mishra, PhD on
Short answer
This example trains a PINN on the 1D heat equation u_t = α u_xx while treating α as an unknown trainable parameter. The loss combines the PDE residual at random collocation points with the misfit to 200 noisy measurements. After training, the network approximates the full solution field and the learned α can be compared with the true value used to generate the data, which is the verification step.
Who this is for
Researchers who know the basics of PINNs and want a worked example of the use case where PINNs are most compelling: inverse problems with sparse data.
Software
Python ≥ 3.9PyTorch ≥ 2.0
Prerequisites
- Python 3.9+ and PyTorch 2.x (
pip install torch). A CPU is enough. - The ideas from our PINN tutorial: residual loss, collocation points and automatic differentiation.
Step 1: the problem
On , , the heat equation with boundary values has the exact solution
We generate 200 noisy “measurements” with , hide , and ask the PINN to recover both and .
Step 2: the code
import math
import torch
torch.manual_seed(0)
alpha_true = 0.1
def exact(x, t):
return torch.exp(-alpha_true * math.pi**2 * t) * torch.sin(math.pi * x)
# Sparse noisy measurements
x_d, t_d = torch.rand(200, 1), 0.5 * torch.rand(200, 1)
u_d = exact(x_d, t_d) + 0.01 * torch.randn(200, 1)
net = torch.nn.Sequential(
torch.nn.Linear(2, 64), torch.nn.Tanh(),
torch.nn.Linear(64, 64), torch.nn.Tanh(),
torch.nn.Linear(64, 1),
)
log_alpha = torch.nn.Parameter(torch.tensor(math.log(0.5))) # deliberately poor initial guess
opt = torch.optim.Adam(list(net.parameters()) + [log_alpha], lr=1e-3)
def u_net(x, t):
return net(torch.cat([x, t], dim=1))
for step in range(8000):
# Fresh random collocation points each step (x in [0,1], t in [0,0.5])
x_c = torch.rand(1000, 1, requires_grad=True)
t_c = (0.5 * torch.rand(1000, 1)).requires_grad_(True)
u = u_net(x_c, t_c)
u_t = torch.autograd.grad(u, t_c, torch.ones_like(u), create_graph=True)[0]
u_x = torch.autograd.grad(u, x_c, torch.ones_like(u), create_graph=True)[0]
u_xx = torch.autograd.grad(u_x, x_c, torch.ones_like(u_x), create_graph=True)[0]
residual = u_t - torch.exp(log_alpha) * u_xx
t_b = 0.5 * torch.rand(100, 1)
boundary = torch.cat([u_net(torch.zeros_like(t_b), t_b), u_net(torch.ones_like(t_b), t_b)])
loss = residual.pow(2).mean() + (u_net(x_d, t_d) - u_d).pow(2).mean() + boundary.pow(2).mean()
opt.zero_grad()
loss.backward()
opt.step()
if step % 2000 == 0:
print(f"step {step:5d} loss {loss.item():.2e} alpha {torch.exp(log_alpha).item():.4f}")
print(f"recovered alpha = {torch.exp(log_alpha).item():.4f} (true {alpha_true})")
Step 3: what to notice
- Unknown parameter in the loss.
log_alphais optimised together with the network weights; the PDE residual is what makes identifiable from the data. - Resampled collocation points. Drawing fresh points every step covers the domain better than a fixed set.
- No initial condition is given explicitly. The data provide that information. With fewer data you would add an initial-condition loss term.
Moving to real measurements
With experimental data, scale inputs and outputs to order one, express measurement uncertainty by weighting the data term (for example by 1/σ²), and include every physical process that affects the data. A missing process, such as a heat source or radiation loss, will be absorbed into a biased parameter estimate, and the PINN will not warn you. Compare the fitted model’s predictions with measurements you did not use for training.
Verify
Run python pinn_inverse_heat.py. The printed should move from the initial 0.5 towards 0.1. Then:
- Compare the network prediction with
exact(x, t)on a regular test grid and report the relative error. - Repeat with three seeds and two noise levels (0.01 and 0.05). Report the mean and spread of the recovered , not a single run.
- Reduce the data to 20 points and see how the uncertainty grows.
Troubleshooting
- α gets stuck or drifts: balance the loss terms (scale the data term), lower the learning rate, or finish with L-BFGS.
- Good data fit, wrong α: too few or uninformative data (for example, all at very early times), so the problem is weakly identifiable. Collect data where the parameter has an effect.
- Training is slow: reduce the collocation batch, or move to a GPU (
net.cuda()and tensors on the device).
Assumptions and limitations
- A synthetic problem with a known answer, chosen so that the result can be verified. Real data add model error, which a PINN cannot detect by itself.
- PINN parameter estimates have no built-in uncertainty quantification. Repeated runs, Bayesian variants or classical methods are needed for credible intervals.
- For forward problems where everything is known, classical solvers are usually faster and more accurate; see PINN vs finite element method.
Frequently asked questions
Why are inverse problems a good fit for PINNs?+
Classical inverse methods need a forward solver inside an optimisation loop plus adjoints or many evaluations. A PINN solves for the field and the unknown parameters at the same time, and naturally uses scattered, noisy data without a mesh.
Why train log(α) instead of α?+
Diffusivities must be positive and may span orders of magnitude. Optimising log α keeps α positive and makes the optimisation better conditioned.
How do I know the recovered parameter is reliable?+
Test identifiability: repeat with different seeds, noise realisations and data sizes, and check that the estimates cluster around the same value. Where possible, compare with a classical estimate from a fitted analytical or numerical solution.
What if my data are on a few sensors only?+
Fewer data make the problem more dependent on the physics term and on good collocation sampling. With very sparse or uninformative data, several parameter values may explain the data equally well; that is a property of the problem, not just the method.
References
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.