Scientific Machine Learning:
PINN: Limitations and Overcoming Strategies
Learning Objectives¶
After studying this lecture, you should be able to:
- explain why a PINN can minimize a correct loss to a wrong solution, and name the four failure modes that account for most such cases,
- describe how collocation-point placement affects the resolution of localized solution features,
- explain why high-frequency solutions, singular / sharp-gradient structures, and gradient discontinuities are difficult for a standard global PINN,
- describe how Fourier feature embedding, enrichment, and domain decomposition modify the representation of difficult solution structures,
- explain why full-domain transient training does not automatically enforce the physical order of information propagation,
- distinguish causal weighting from sequential time marching,
- explain why a decaying solution weights its own residual loss towards early times, and how dividing out the known decay removes that weighting, and
- interpret the demonstrations as examples of how PINN limitations can be mitigated through changes in sampling, representation, and training order.
Physics-informed neural networks (PINNs) incorporate governing equations, boundary conditions, initial conditions, and available observations into neural-network training. This construction is attractive because the network can be optimized without requiring a labeled solution at every point in the domain. However, encoding physics in the loss function does not by itself guarantee efficient or reliable learning.
Four recurring limitations account for most of what goes wrong: loss imbalance, sampling strategy, complex solution structures, and temporal causality. The first was treated in Regularization, MAP Estimation, and Loss Weighting, together with its remedies, adaptive weighting and hard constraints, and is only recalled here. This lecture takes up the remaining three. For complex solution structures, three representative cases are considered: high-frequency behavior, singularity / sharp gradients, and gradient discontinuity across an interface.
The corresponding extensions are introduced through compact demonstrations: focused collocation for localized resolution, Fourier feature embedding, enrichment, and domain decomposition for difficult solution structures, and causal PINNs and time marching for transient problems.
A PINN is attractive because it needs no mesh and no solution data. The equation itself supplies the training signal: sample points in the domain, evaluate the residual of the differential equation there by automatic differentiation, add the residual of each boundary and initial condition, and hand the sum to an optimizer. Where data are available they can be added as one more term. Nothing about the geometry has to be discretized, and the result is a closed-form function of the coordinates that can be evaluated anywhere.
That much is the promise. In practice a PINN trained on a problem that a classical solver handles without comment can return a solution that is smooth, plausible, and wrong, and the loss curve will not say so.
Write $N_\theta$ for the network and collect the conditions of the problem. A typical steady problem contributes two, and a transient one three:
$$ \mathcal{L}(\theta) = \mathcal{L}_{\mathrm{PDE}}(\theta) + \mathcal{L}_{\mathrm{BC}}(\theta) + \mathcal{L}_{\mathrm{IC}}(\theta) , $$
each term a mean squared residual over its own set of sample points,
$$ \mathcal{L}_{\mathrm{PDE}} = \frac{1}{N_f}\sum_{j=1}^{N_f}\bigl|\mathcal{N}[N_\theta](x_j)\bigr|^2 , \qquad \mathcal{L}_{\mathrm{BC}} = \frac{1}{N_b}\sum_{j=1}^{N_b}\bigl|N_\theta(x_j) - g(x_j)\bigr|^2 . $$
The optimizer sees one number. It does not know that the first term is a statement about the interior and the second a statement about the boundary, that one is exact physics and the other exact data, or that a solution satisfying the first but not the second is not a solution at all. It sees a scalar and descends.
Every failure mode of the next section is a consequence of that reduction, or of a choice that the reduction leaves unconstrained: where to sample, what function class to use, in what order to train.
Loss imbalance. The terms of the sum compete for the same parameters, and one of them can dominate the update so completely that another is never satisfied, while the total loss falls convincingly the whole time. Remedies: weights on the terms, adaptively chosen; or removing a condition from the loss entirely by building it into the output.
Sampling strategy. The residual is only ever evaluated where the collocation points are. A uniform sample spends its budget evenly over a domain whose difficulty is not even, and a feature confined to a small region is resolved by whatever few points happen to land in it. Remedy: put the points where the solution varies.
Complex solution structures. A plain network trained by gradient descent is biased towards smooth, low-frequency functions. Solutions that oscillate rapidly, that blow up at a point, or whose derivative jumps across an interface are all shapes it approaches slowly or not at all. Remedies differ by shape: Fourier features, an enrichment basis, a decomposition of the domain.
Time. A transient problem has an order, the initial condition determines what comes next, but nothing in the loss respects it. All time levels are trained at once, and the residual at late times can be driven down around a trajectory that never came from the right initial state. Remedies: weight the late residuals by how well the early ones are satisfied, or train the time interval in windows. Time defeats a PINN in a second and unrelated way as well. When the solution decays as it evolves, the loss is dominated by the times at which the solution is still large, and the end of the interval goes unconstrained whatever the order of training. The remedy there is to take the known decay out of what the network represents.
The four failure modes. Top left: gradients from different loss terms pulling the same parameter vector in different directions. Top right: collocation points spread uniformly over a domain with a localized stress concentration. Bottom left: three solution shapes that resist a smooth network — a high-frequency oscillation, a sharp peak, and a kink at an interface. Bottom right: a transient solution, whose information must travel from left to right in time.
One observation applies to all four. In each case the symptom is not a large loss but a small loss attached to a wrong solution, so the diagnosis never comes from the loss curve alone. It comes from comparing the terms against each other, from looking at where the error lives in the domain, and from knowing what shape the solution is supposed to have.
The first of the four, loss imbalance, was treated in full in Regularization, MAP Estimation, and Loss Weighting, where the weighting of the terms and the hard-constraint alternative are developed and demonstrated; it is not repeated here. The remaining three are the subject of this notebook, one to a chapter, each with the mechanism, the remedy, and a worked demonstration.
A PINN has no data. Its training set is the set of points at which the residual of the governing equation is evaluated, the collocation points, and the physics loss is an average over them. Two consequences follow, and both are easy to overlook because the equation itself holds everywhere. The residual is constrained only at the sampled points; between them the network is held only by the smoothness of its own function class. And the loss is an average, so a region that occupies a small fraction of the domain contributes a small fraction of the loss, however large the residual is there and however much the answer depends on getting that region right.
The default choice is a uniform sample. It requires knowing nothing about the solution, which is exactly its weakness, because the difficulty of a problem is rarely spread evenly over the domain. A stress concentration, a boundary layer, a crack tip, a shock: each confines the fast variation of the solution to a small region, and a uniform sample spends its points everywhere else. Computational fluid dynamics learned this fifty years ago and answers it with a graded mesh, fine where the gradients are and coarse where they are not. A collocation set is the PINN's counterpart of that mesh, and the same principle applies, at a lower price: the points carry no connectivity, so adding one costs one row in a tensor.
This chapter makes the point with one problem, one point budget, and two ways of spending it.
2.1.1. The Kirsch Problem¶
The test problem is the classical one for stress concentration. Take a large thin plate and pull it in one direction with a uniform stress $\sigma_0$, so that far from any disturbance every cross-section carries the same load. Now cut a circular hole of radius $a$ through it. The material that used to carry the load across the hole is gone, and the load must go around it; the stress is no longer uniform, and next to the hole it is larger than $\sigma_0$. How much larger, and over how wide a region, is the question Kirsch answered in closed form in 1898.
It helps to fix the geometry before writing the formulas. Place the centre of the hole at the origin, let the load act along the $x$-axis, and describe a point by its distance $r$ from the centre and its angle $\theta$ measured from the direction of the load. The plate is taken to be infinite, so that the only length in the problem is $a$, and every distance below is naturally measured in units of it. The stresses are described in polar components: $\sigma_{rr}$ is the normal stress acting on a surface that faces away from the hole, $\sigma_{\theta\theta}$ is the normal stress acting around the hole, the so-called hoop stress, and $\sigma_{r\theta}$ is the shear stress between the two. The Kirsch solution is
$$ \begin{align*} \frac{\sigma_{rr}}{\sigma_0} &= \frac{1}{2}\Bigl(1-\frac{a^2}{r^2}\Bigr) + \frac{1}{2}\Bigl(1 + 3\frac{a^4}{r^4} - 4\frac{a^2}{r^2}\Bigr)\cos 2\theta , \\[6pt] \frac{\sigma_{\theta\theta}}{\sigma_0} &= \frac{1}{2}\Bigl(1+\frac{a^2}{r^2}\Bigr) - \frac{1}{2}\Bigl(1 + 3\frac{a^4}{r^4}\Bigr)\cos 2\theta , \\[6pt] \frac{\sigma_{r\theta}}{\sigma_0} &= -\frac{1}{2}\Bigl(1 - 3\frac{a^4}{r^4} + 2\frac{a^2}{r^2}\Bigr)\sin 2\theta . \end{align*} $$
The formulas look heavy, and they need not be memorized; what matters is what they say in three places.
Far from the hole, $r \gg a$, every term carrying $a/r$ disappears, leaving $\sigma_{rr}/\sigma_0 = \tfrac12(1 + \cos 2\theta) = \cos^2\theta$, $\sigma_{\theta\theta}/\sigma_0 = \sin^2\theta$ and $\sigma_{r\theta}/\sigma_0 = -\sin\theta\cos\theta$. These are nothing but the uniform stress $\sigma_0$ along $x$, rewritten in polar components: the hole is not felt there, as it should not be.
At the edge of the hole, $r = a$, the first and third formulas give $\sigma_{rr} = 0$ and $\sigma_{r\theta} = 0$. This is the statement that the hole is empty: nothing inside it pushes or drags on the edge, so a surface facing the hole carries no normal stress and no shear stress. The condition is called traction free, and it is the boundary condition the PINN will have to impose there. The hoop stress, on the other hand, does not vanish at the edge; the second formula gives
$$ \frac{\sigma_{\theta\theta}}{\sigma_0}\Big|_{r=a} = 1 - 2\cos 2\theta . $$
At $\theta = 0$ and $\theta = \pi$, the two points of the edge that face the load, this is $-1$: the material there is in compression, even though the plate as a whole is being pulled. At $\theta = \pm\pi/2$, the top and bottom of the hole, it is $3$. The load that would have crossed the hole has been squeezed into the material beside it, and the stress there is three times the applied stress. That factor of three is the stress concentration factor of a circular hole, and it does not depend on the size of the hole or on the material; a small hole in a large plate triples the local stress just as a large one does.
Between the two, the disturbance dies away as $a^2/r^2$: at $r = 2a$ the extra stress has fallen to about a quarter of its value at the edge, and at $r = 3a$ to about a ninth. The region in which the hole matters is therefore an annulus about one radius wide around it, and everything outside is nearly uniform. This is the fact the whole lab turns on. The hard part of the solution is confined to a small fraction of the plate, and a sample of collocation points that does not know this will spend most of its points where nothing is happening.
A stress has three components, and to compare two solutions it is convenient to collapse them into one number. The usual choice is the von Mises stress,
$$ \sigma_{\mathrm{vM}} = \sqrt{\sigma_{rr}^2 - \sigma_{rr}\sigma_{\theta\theta} + \sigma_{\theta\theta}^2 + 3\sigma_{r\theta}^2} , $$
which is the scalar an engineer compares against the yield strength to decide whether the material will fail. Under the uniform far-field stress it equals $\sigma_0$; at the top and bottom of the hole it is close to $3\sigma_0$. Every figure of this lab shows this quantity.
The PINN cannot work on an infinite plate, so the problem is posed on the finite square $\Omega = \{(x,y)\in[-3a,3a]^2 : r \ge a\}$ with $a = 1$. Two boundary conditions make the finite problem equivalent to the infinite one. On the hole the traction-free condition $\sigma_{rr} = \sigma_{r\theta} = 0$ is imposed, as in the original problem. On the outer square the Kirsch stresses themselves are prescribed, so that the square carries exactly the stress the infinite plate would carry there. With these two conditions the exact solution of the finite problem is the Kirsch solution, and every error reported in this lab is measured against it.
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Device:', device)
The Kirsch stresses and the von Mises stress, with $a = 1$ and stresses in units of $\sigma_0$, serve three purposes in this lab: the ground truth, the outer boundary condition, and the error.
def kirsch(r, theta): # hole of radius 1, stresses in units of sigma_0
s_rr = 0.5*(1 - 1/r**2) + 0.5*(1 + 3/r**4 - 4/r**2)*torch.cos(2*theta)
s_tt = 0.5*(1 + 1/r**2) - 0.5*(1 + 3/r**4)*torch.cos(2*theta)
s_rt = -0.5*(1 - 3/r**4 + 2/r**2)*torch.sin(2*theta)
return s_rr, s_tt, s_rt
def von_mises(s_rr, s_tt, s_rt):
return torch.sqrt(s_rr**2 - s_rr*s_tt + s_tt**2 + 3*s_rt**2)
def column(v):
return torch.tensor(v, dtype = torch.float32, device = device).reshape(-1, 1)
All predictions are evaluated on the same $201\times201$ grid over the square, with the hole masked out.
x_grid = np.linspace(-3, 3, 201)
X, Y = np.meshgrid(x_grid, x_grid)
R = np.sqrt(X**2 + Y**2)
r_eval = column(np.maximum(R, 1))
theta_eval = column(np.arctan2(Y, X))
with torch.no_grad():
s_rr, s_tt, s_rt = kirsch(r_eval, theta_eval)
VM_true = von_mises(s_rr, s_tt, s_rt).cpu().numpy().reshape(201, 201)
VM_true[R < 1] = np.nan # the hole
plt.figure(figsize = (6, 5))
plt.contourf(X, Y, VM_true, levels = np.linspace(0, 3, 101), cmap = 'jet')
plt.colorbar()
plt.axis('equal')
plt.xlabel('$x/a$')
plt.ylabel('$y/a$')
plt.title('Ground Truth')
plt.show()
The von Mises stress is largest at the top and bottom of the hole, where the hoop stress is three times the applied load. The figure shows how localized the feature is: the red region hugs the hole, the blue low-stress lobes on its left and right are only slightly wider, and beyond about $r = 2a$ the field is the nearly uniform green of the far-field stress. A network has to represent the whole of this with one set of parameters, and the question is where it should be told to try hardest.
2.1.2. Two Ways to Spend 256 Points¶
Naive collocation. One Cartesian grid over the square, with the points that fall inside the hole removed. What remains is $256$ points spread evenly over the plate, so that the annulus $a<r\le2a$, which carries the whole stress concentration, receives fewer than a third of them.
Focused collocation. The same $256$ points redistributed: a fine grid inside the annulus $a<r\le2a$ and a coarse grid outside it, with the two chosen so that the counts add up to exactly $256$ and the point density inside the annulus is three times the density outside.
def grid(nx, ny): # cell centres of an nx by ny grid over the square
hx = 6/nx
hy = 6/ny
x = -3 + hx/2 + hx*np.arange(nx)
y = -3 + hy/2 + hy*np.arange(ny)
X, Y = np.meshgrid(x, y)
return X.ravel(), Y.ravel()
# naive: one 20 x 14 grid, the hole removed
x, y = grid(20, 14)
r = np.sqrt(x**2 + y**2)
x_naive = x[r >= 1]
y_naive = y[r >= 1]
# focused: a fine grid for 1 <= r <= 2, a coarse grid for r > 2
x, y = grid(23, 23)
r = np.sqrt(x**2 + y**2)
x_fine = x[(r >= 1) & (r <= 2)]
y_fine = y[(r >= 1) & (r <= 2)]
x, y = grid(14, 13)
r = np.sqrt(x**2 + y**2)
x_coarse = x[r > 2]
y_coarse = y[r > 2]
x_focused = np.concatenate([x_fine, x_coarse])
y_focused = np.concatenate([y_fine, y_coarse])
print('naive : %d points' % len(x_naive))
print('focused : %d points (%d near the hole + %d far away)' % (len(x_focused), len(x_fine), len(x_coarse)))
Both sets drawn over the exact von Mises field, so that the placement can be judged against the feature it is meant to resolve.
plt.figure(figsize = (6, 10))
plt.subplot(2, 1, 1)
plt.contourf(X, Y, VM_true, levels = np.linspace(0, 3, 101), cmap = 'jet')
plt.plot(x_naive, y_naive, 'k.')
plt.axis('equal')
plt.title('Naive Collocation')
plt.subplot(2, 1, 2)
plt.contourf(X, Y, VM_true, levels = np.linspace(0, 3, 101), cmap = 'jet')
plt.plot(x_focused, y_focused, 'k.')
plt.axis('equal')
plt.title('Focused Collocation')
plt.show()
The naive grid treats the plate as if every part of it were equally hard. The focused grid puts more than half of its points in the annulus and leaves the rest to the far field, where the solution is nearly constant and a handful of points is enough to pin it. Nothing else differs between the two sets: same number of points, same boundary points, same everything that follows.
2.1.3. The PINN¶
The network takes the position in polar form, $\bigl(r/3,\cos\theta,\sin\theta\bigr)$, and returns the three stress components $\bigl(\sigma_{rr},\sigma_{\theta\theta},\sigma_{r\theta}\bigr)/\sigma_0$ directly. Polar inputs suit the problem, because the solution is naturally a function of $r$ and $\theta$; dividing $r$ by $3$ keeps the input of order one, and feeding $\cos\theta$ and $\sin\theta$ instead of $\theta$ removes the artificial jump at $\theta=\pm\pi$. Both models start from the same weights.
def new_pinn():
torch.manual_seed(1) # both models start from the same weights
return nn.Sequential(nn.Linear(3, 64), nn.Tanh(),
nn.Linear(64, 64), nn.Tanh(),
nn.Linear(64, 64), nn.Tanh(),
nn.Linear(64, 64), nn.Tanh(),
nn.Linear(64, 3)).to(device)
def stresses(net, r, theta):
out = net(torch.cat([r/3, torch.cos(theta), torch.sin(theta)], dim = 1))
return out[:, 0:1], out[:, 1:2], out[:, 2:3]
def derivative(y, x):
return torch.autograd.grad(y, x, torch.ones_like(y), create_graph = True)[0]
In polar coordinates the two equilibrium equations of plane elasticity are
$$ \begin{align*} \frac{\partial \sigma_{rr}}{\partial r} + \frac{1}{r}\frac{\partial \sigma_{r\theta}}{\partial \theta} + \frac{\sigma_{rr}-\sigma_{\theta\theta}}{r} &= 0 \\ \\ \frac{\partial \sigma_{r\theta}}{\partial r} + \frac{1}{r}\frac{\partial \sigma_{\theta\theta}}{\partial \theta} + \frac{2\sigma_{r\theta}}{r} &= 0 \end{align*} $$
and, because the network predicts stresses rather than displacements, a third equation is needed to make the stress field derivable from a displacement: the compatibility condition, which for plane problems without body forces says that the trace $S=\sigma_{rr}+\sigma_{\theta\theta}$ is harmonic,
$$ \frac{\partial^2 S}{\partial r^2} + \frac{1}{r}\frac{\partial S}{\partial r} + \frac{1}{r^2}\frac{\partial^2 S}{\partial\theta^2} = 0 . $$
These three left-hand sides, evaluated at the collocation points by automatic differentiation, are the physics residuals.
def residuals(net, r, theta):
s_rr, s_tt, s_rt = stresses(net, r, theta)
eq_r = derivative(s_rr, r) + derivative(s_rt, theta)/r + (s_rr - s_tt)/r # equilibrium
eq_t = derivative(s_rt, r) + derivative(s_tt, theta)/r + 2*s_rt/r
S = s_rr + s_tt # compatibility
S_r = derivative(S, r)
S_theta = derivative(S, theta)
comp = derivative(S_r, r) + S_r/r + derivative(S_theta, theta)/r**2
return eq_r, eq_t, comp
The hole is traction free, $\sigma_{rr}=\sigma_{r\theta}=0$ at $r=a$, sampled at $256$ equally spaced angles. On the outer square the Kirsch stresses are prescribed, sampled at $64$ points per side with the corners left out. These points are the same for both models.
theta_hole = column(np.linspace(0, 2*np.pi, 256, endpoint = False))
r_hole = torch.ones_like(theta_hole)
s = np.linspace(-3, 3, 64)
x_outer = np.concatenate([-3*np.ones(64), 3*np.ones(64), s, s])
y_outer = np.concatenate([s, s, -3*np.ones(64), 3*np.ones(64)])
r_outer = column(np.sqrt(x_outer**2 + y_outer**2))
theta_outer = column(np.arctan2(y_outer, x_outer))
with torch.no_grad():
s_rr_outer, s_tt_outer, s_rt_outer = kirsch(r_outer, theta_outer)
2.1.4. Naive PINN¶
The loss adds the three physics residuals at the collocation points and the two boundary conditions at the boundary points, with weights,
$$ \mathcal{L} = \mathcal{L}_{\mathrm{pde}} + 10\,\mathcal{L}_{\mathrm{hole}} + 10\,\mathcal{L}_{\mathrm{outer}} . $$
The boundary terms carry a weight of $10$, because the boundary values are what fix the level of the solution and, as Regularization, MAP Estimation, and Loss Weighting showed, a boundary term with too little weight is simply ignored.
r_pde = column(np.sqrt(x_naive**2 + y_naive**2))
theta_pde = column(np.arctan2(y_naive, x_naive))
r_pde.requires_grad_(True)
theta_pde.requires_grad_(True)
net_naive = new_pinn()
optimizer = torch.optim.Adam(net_naive.parameters(), lr = 1e-3)
for k in range(30000):
optimizer.zero_grad()
eq_r, eq_t, comp = residuals(net_naive, r_pde, theta_pde)
loss_pde = torch.mean(eq_r**2) + torch.mean(eq_t**2) + torch.mean(comp**2)
s_rr, s_tt, s_rt = stresses(net_naive, r_hole, theta_hole)
loss_hole = torch.mean(s_rr**2) + torch.mean(s_rt**2)
s_rr, s_tt, s_rt = stresses(net_naive, r_outer, theta_outer)
loss_outer = torch.mean((s_rr - s_rr_outer)**2) + torch.mean((s_tt - s_tt_outer)**2) + torch.mean((s_rt - s_rt_outer)**2)
loss = loss_pde + 10*loss_hole + 10*loss_outer
loss.backward()
optimizer.step()
if (k + 1) % 5000 == 0:
print('Naive %6d | loss %.3e | pde %.3e | hole %.3e | outer %.3e' % (k + 1, loss.item(), loss_pde.item(), loss_hole.item(), loss_outer.item()))
The predicted von Mises field and its absolute error against the Kirsch solution, on the colour scales used for every model of this lab.
with torch.no_grad():
s_rr, s_tt, s_rt = stresses(net_naive, r_eval, theta_eval)
VM_naive = von_mises(s_rr, s_tt, s_rt).cpu().numpy().reshape(201, 201)
VM_naive[R < 1] = np.nan
ERR_naive = np.abs(VM_naive - VM_true)
plt.figure(figsize = (6, 10))
plt.subplot(2, 1, 1)
plt.contourf(X, Y, VM_naive, levels = np.linspace(0, 3, 101), cmap = 'jet')
plt.axis('equal')
plt.title('Naive PINN')
plt.subplot(2, 1, 2)
plt.contourf(X, Y, ERR_naive, levels = np.linspace(0, 0.15, 101), cmap = 'gray', extend = 'max')
plt.axis('equal')
plt.title('Naive PINN, Error')
plt.show()
The predicted field looks right. On the colour scale of the ground truth the two panels are hard to tell apart: the red concentration at the top and bottom of the hole, the blue lobes at its sides and the uniform far field are all there, and the loss ended small. The error map says where the agreement ends. Almost all of the error sits in a ring around the hole, with bright spots at the top and bottom of the hole's edge, where it amounts to several percent of the peak stress; the far field is nearly black, and the mean error in the annulus is several times the mean over the whole plate.
The pattern is the one the sampling predicts. The naive grid placed most of its points in the far field, so the averaged residual the optimizer minimized was dominated by the region where the solution is easy. The hole, where the solution is hard, was resolved by whatever points happened to fall there, and the error is largest exactly where the stress gradient is steepest.
2.1.5. Focused PINN¶
The same loop, the same starting weights, the same boundary points and the same number of iterations; only the collocation points are the focused set.
r_pde = column(np.sqrt(x_focused**2 + y_focused**2))
theta_pde = column(np.arctan2(y_focused, x_focused))
r_pde.requires_grad_(True)
theta_pde.requires_grad_(True)
net_focused = new_pinn()
optimizer = torch.optim.Adam(net_focused.parameters(), lr = 1e-3)
for k in range(30000):
optimizer.zero_grad()
eq_r, eq_t, comp = residuals(net_focused, r_pde, theta_pde)
loss_pde = torch.mean(eq_r**2) + torch.mean(eq_t**2) + torch.mean(comp**2)
s_rr, s_tt, s_rt = stresses(net_focused, r_hole, theta_hole)
loss_hole = torch.mean(s_rr**2) + torch.mean(s_rt**2)
s_rr, s_tt, s_rt = stresses(net_focused, r_outer, theta_outer)
loss_outer = torch.mean((s_rr - s_rr_outer)**2) + torch.mean((s_tt - s_tt_outer)**2) + torch.mean((s_rt - s_rt_outer)**2)
loss = loss_pde + 10*loss_hole + 10*loss_outer
loss.backward()
optimizer.step()
if (k + 1) % 5000 == 0:
print('Focused %6d | loss %.3e | pde %.3e | hole %.3e | outer %.3e' % (k + 1, loss.item(), loss_pde.item(), loss_hole.item(), loss_outer.item()))
The two predictions side by side with the ground truth, and their errors on a common scale.
with torch.no_grad():
s_rr, s_tt, s_rt = stresses(net_focused, r_eval, theta_eval)
VM_focused = von_mises(s_rr, s_tt, s_rt).cpu().numpy().reshape(201, 201)
VM_focused[R < 1] = np.nan
ERR_focused = np.abs(VM_focused - VM_true)
plt.figure(figsize = (12, 8))
plt.subplot(2, 3, 1)
plt.contourf(X, Y, VM_true, levels = np.linspace(0, 3, 101), cmap = 'jet')
plt.axis('equal')
plt.title('Ground Truth')
plt.subplot(2, 3, 2)
plt.contourf(X, Y, VM_naive, levels = np.linspace(0, 3, 101), cmap = 'jet')
plt.axis('equal')
plt.title('Naive PINN')
plt.subplot(2, 3, 3)
plt.contourf(X, Y, VM_focused, levels = np.linspace(0, 3, 101), cmap = 'jet')
plt.axis('equal')
plt.title('Focused PINN')
plt.subplot(2, 3, 5)
plt.contourf(X, Y, ERR_naive, levels = np.linspace(0, 0.15, 101), cmap = 'gray', extend = 'max')
plt.axis('equal')
plt.title('Naive PINN, Error')
plt.subplot(2, 3, 6)
plt.contourf(X, Y, ERR_focused, levels = np.linspace(0, 0.15, 101), cmap = 'gray', extend = 'max')
plt.axis('equal')
plt.title('Focused PINN, Error')
plt.show()
The error is averaged over the whole plate and, separately, over the annulus $a\le r\le 2a$ where the points were concentrated; the largest error anywhere is reported as well.
plate = R >= 1
near = (R >= 1) & (R <= 2)
print('Mean error, whole plate : naive %.3e focused %.3e' % (np.mean(ERR_naive[plate]), np.mean(ERR_focused[plate])))
print('Mean error, near the hole : naive %.3e focused %.3e' % (np.mean(ERR_naive[near]), np.mean(ERR_focused[near])))
print('Largest error : naive %.3e focused %.3e' % (np.max(ERR_naive[plate]), np.max(ERR_focused[plate])))
The higher final loss in the focused run does not indicate a worse solution, but rather reflects that the loss was measured in more challenging areas where the residual is hardest to reduce. The true performance is evidenced by the error relative to the exact solution, where the focused run significantly reduced both the mean error near the hole and the overall maximum error. Visually, the concentrated error "ring" found in the naive run was replaced by a faint, evenly spread residual. These results demonstrate that by redistributing the point budget from the far field to the stress-concentrated annulus, the model achieved higher precision without increasing the total budget or changing the network. Ultimately, this shows that where the residual is evaluated is more critical than the total number of points for achieving a physically accurate solution.
2.1.6. What the Lab Showed¶
Two models with identical capacity, identical boundary information, identical training and identical numbers of collocation points reached different accuracies, and the difference was decided by where the points were. The naive sample spent most of its budget on the far field, where the solution is nearly constant and almost any placement would do, and left the stress concentration to the few points that happened to fall near the hole. The focused sample put its effort where the solution varies, and it paid for this with nothing: the far field is so smooth that a coarse grid resolves it as well as a fine one.
Two conclusions generalize beyond the plate. A collocation set should be graded like a mesh, dense where the solution is hard and sparse where it is easy, and since the points carry no connectivity there is less excuse for a uniform sample than there is for a uniform mesh. And the loss a PINN reports is a statement about its points, never about the domain: a small averaged residual over a uniform sample says little about the one region that matters if that region holds a small fraction of the points.
Remark (when the hard region is not known in advance). In the previous experiment, the stress concentration was known to be located at the hole, allowing the refinement to be placed manually. However, when the location of the difficulty is not known in advance, the residual itself serves as the guide. The residual represents the degree to which the current neural network solution fails to satisfy the governing physical equations; a larger residual indicates a region where the model's prediction is least accurate and the physics are not yet well-captured. By evaluating this residual on a dense candidate set, collocation points can be added or moved to the areas where the residual is largest. This residual-adaptive sampling is the PINN counterpart of adaptive mesh refinement, enabling the model to automatically recover the focused allocation described above without being explicitly told where the hole or other high-difficulty regions are located.
A physics-informed neural network asks one network to represent the solution over the whole domain. For a smooth field that varies on a single scale this is a reasonable thing to ask, and the earlier treatments showed it working. Loss imbalance, in Regularization, MAP Estimation, and Loss Weighting, and sampling, in the previous chapter, were difficulties of the training: the terms of the loss competing for the parameters, and the collocation points being in the wrong places. This chapter deals with a difficulty of the representation. Some solutions are hard for a single smooth network to express at all, however well it is trained and however the points are placed, and the remedy is then to change what the network is asked to represent.
Three such structures recur in engineering problems. A solution may oscillate rapidly, so that it contains many wavelengths across the domain; it may vary violently in one small region while being smooth everywhere else, as a stress field does near a crack tip or a corner; or it may be continuous but kinked, with a gradient that jumps across a line where the material changes. Each defeats a plain network for a different reason, and each has a remedy that changes the representation in a different place: in the input, by feeding the network features that already oscillate; in the output, by adding a known singular function to it; or in the domain, by giving each region a network of its own and tying them together at the interface.
The three laboratories of this chapter show one failure and one remedy each. In every case the governing equation, the boundary conditions and the optimizer are the same for the failing model and the repaired one; only the representation differs, and that is the point.
A standard PINN uses a single fully connected network, with smooth activations, as the solution over the entire computational domain. Such a network is a very flexible function, but it is a particular kind of flexible function: it is smooth to all orders, it changes slowly unless its weights are large, and it treats every part of the domain with the same set of parameters. These are the right properties for a field that varies gently and on one scale. They are the wrong properties when the important features of the solution live on a very different scale from the domain, or are confined to a small part of it, or are not smooth at all.
This chapter considers three such cases.
Three solution structures that defeat a single smooth network. In each panel the exact solution is drawn against the prediction of a standard PINN: ten oscillations that the network replaces with a slow drift, a sharp peak that it rounds into a low bump, and a kink at a material interface that it smooths into a curve.
High frequency: the solution oscillates many times across the domain. The network must represent every oscillation, and gradient descent reaches the slow components long before the fast ones.
Singularity / sharp gradient: the solution, or its derivative, grows without bound or changes steeply at one point, while being smooth elsewhere. A smooth network spends its whole capacity trying to bend around that point.
Gradient discontinuity / interface: the solution is continuous but its slope jumps across a line, as it must where two materials meet. A differentiable network has no kink to offer and rounds the corner off.
The first of these is treated at some length, because the reason behind it, the spectral bias of neural networks, is a general fact about how networks learn and will come up again whenever a PINN is asked for fine detail.
Train a network to fit a target that contains both a slow component and a fast one, and watch what it learns first. It is not the whole target at once, and it is not the component with the larger amplitude. It is the slow component. The fast one appears later, often much later, and if training is stopped early it may not appear at all. This ordering is not an accident of one experiment; it is a property of gradient descent on a network, and it is called spectral bias: low-frequency components of a target are learned before high-frequency components, and the gap in learning speed widens as the frequency rises.
The reason can be stated without the theory that makes it precise. A network with smooth activations and weights of ordinary size is itself a slowly varying function, and a small change in its weights changes its output slowly across the input. The gradient of the loss with respect to the weights therefore points, for the most part, in directions that change the output smoothly, and a step of gradient descent corrects the smooth part of the error first. To produce a rapid oscillation the network needs large weights in its first layer, and large weights are reached only by many small steps. The fast component of the target is not forbidden; it is merely expensive, and the optimizer pays for the cheap things first.
A consequence worth stating now, because it will be the lesson of the lab in Section 3.3: a small training loss, or a prediction that looks reasonable at a glance, does not mean that the fine structure of the solution has been recovered. The coarse structure accounts for most of the loss, and it is learned first.
3.2.1. Progressive Frequency Learning¶
In the animation a network is trained on a target with several frequency components. The left panel is the prediction against the target in the spatial domain; the right panel is the Fourier spectrum of the prediction, which shows directly which frequencies have been recovered.
Progressive frequency learning. Left: the prediction against a multi-frequency target as training proceeds. Right: the Fourier amplitude of the prediction against that of the target. The low-frequency peak is reached early; the higher peaks rise later and more slowly.
At the start the prediction is nearly flat. The first thing to appear is the slow envelope of the target; the oscillations within it come later, and the fastest of them last. In the spectrum the same story is told by the peaks: the one at the lowest frequency rises first and reaches its target height early, while the peaks at higher frequencies rise later and more slowly. The network is recovering the target one frequency band at a time, from the bottom up.
3.2.2. Evolution of the Predicted Solution¶
The same run, frozen at a few epochs, makes the ordering easier to inspect.
The same run at three epochs. At epoch $0$ the prediction is almost a straight line, at epoch $2000$ it follows the slow envelope of the target, and only by epoch $4000$ does it carry the fast oscillations as well.
At the early epochs the prediction is a smooth curve through the middle of the target, a low-frequency average of it. As training proceeds, finer oscillations are added on top of that curve, and only at the end does the prediction follow the target through every wiggle. Note that the prediction at an intermediate epoch is not a bad approximation of the target in the usual sense; its error is spread evenly and its loss is modest. It is simply missing everything above a certain frequency.
3.2.3. Frequency-wise Convergence¶
The cleanest way to see the bias is to track each frequency component of the target separately and plot the error in that component against the epoch.