Skip to content
VLASIFY™
TutorialScientific AI & machine learning

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 x∈[0,1]x \in [0, 1], t∈[0,0.5]t \in [0, 0.5], the heat equation with boundary values u(0,t)=u(1,t)=0u(0,t) = u(1,t) = 0 has the exact solution

u(x,t)=e−απ2tsin⁡(πx).u(x, t) = e^{-\alpha\pi^2 t}\sin(\pi x).

We generate 200 noisy “measurements” with αtrue=0.1\alpha_{true} = 0.1, hide α\alpha, and ask the PINN to recover both u(x,t)u(x,t) and α\alpha.

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_alpha is optimised together with the network weights; the PDE residual is what makes α\alpha 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 α\alpha should move from the initial 0.5 towards 0.1. Then:

  1. Compare the network prediction with exact(x, t) on a regular test grid and report the relative L2L^2 error.
  2. Repeat with three seeds and two noise levels (0.01 and 0.05). Report the mean and spread of the recovered α\alpha, not a single run.
  3. 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

  1. Raissi, Perdikaris & Karniadakis, Physics-informed neural networks, J. Comput. Phys. 378, 686 (2019) · Peer-reviewed article
  2. Karniadakis et al., Physics-informed machine learning, Nat. Rev. Phys. 3, 422 (2021) · Review article
  3. 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.

Related guides

How Vlasify can help

Get a Quote