Update tutorials 1 through 7

This commit is contained in:
Matteo Bertocchi
2025-03-08 19:39:45 +01:00
committed by Nicola Demo
parent 7ef39f1e3b
commit 17792caa34
14 changed files with 675 additions and 288 deletions

View File

@@ -9,7 +9,7 @@
#
# First of all, some useful imports.
# In[1]:
# In[4]:
## routine needed to run the notebook on Google Colab
@@ -23,6 +23,8 @@ if IN_COLAB:
import torch
from torch.nn import Softplus
import matplotlib.pyplot as plt
import warnings
from pina.problem import SpatialProblem
from pina.operator import laplacian
@@ -31,9 +33,13 @@ from pina.solver import PINN
from pina.trainer import Trainer
from pina.domain import CartesianDomain
from pina.equation import Equation, FixedValue
from pina import Condition, LabelTensor#,Plotter
from pina import Condition, LabelTensor
from pina.callback import MetricTracker
from lightning.pytorch.loggers import TensorBoardLogger
warnings.filterwarnings('ignore')
# ## The problem definition
@@ -49,7 +55,7 @@ from pina.callback import MetricTracker
# The Poisson problem is written in **PINA** code as a class. The equations are written as *conditions* that should be satisfied in the corresponding domains. The *truth_solution*
# is the exact solution which will be compared with the predicted one.
# In[2]:
# In[5]:
class Poisson(SpatialProblem):
@@ -90,33 +96,68 @@ problem.discretise_domain(25, 'grid', domains=['bound_cond1', 'bound_cond2', 'bo
# After the problem, the feed-forward neural network is defined, through the class `FeedForward`. This neural network takes as input the coordinates (in this case $x$ and $y$) and provides the unkwown field of the Poisson problem. The residual of the equations are evaluated at several sampling points (which the user can manipulate using the method `CartesianDomain_pts`) and the loss minimized by the neural network is the sum of the residuals.
#
# In this tutorial, the neural network is composed by two hidden layers of 10 neurons each, and it is trained for 1000 epochs. We use the `MetricTracker` class to track the metrics during training.
# In this tutorial, the neural network is composed by two hidden layers of 10 neurons each, and it is trained for 1000 epochs with a learning rate of 0.006 and $l_2$ weight regularization set to $10^{-8}$. These parameters can be modified as desired.
# In[4]:
# In[6]:
# make model + solver + trainer
from pina.optim import TorchOptimizer
model = FeedForward(
layers=[10, 10],
func=Softplus,
output_dimensions=len(problem.output_variables),
input_dimensions=len(problem.input_variables)
)
pinn = PINN(problem, model)
trainer = Trainer(pinn, max_epochs=1000, callbacks=[MetricTracker()], accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
pinn = PINN(problem, model, optimizer=TorchOptimizer(torch.optim.Adam, lr=0.006,weight_decay=1e-8))
trainer = Trainer(pinn, max_epochs=1000, accelerator='cpu', enable_model_summary=False,
train_size=1.0,
val_size=0.0,
test_size=0.0,
logger=TensorBoardLogger("tutorial_logs")
) # we train on CPU and avoid model summary at beginning of training (optional)
# train
trainer.train()
# Now the `Plotter` class is used to plot the results.
# Now we plot the results using `matplotlib`.
# The solution predicted by the neural network is plotted on the left, the exact one is represented at the center and on the right the error between the exact and the predicted solutions is showed.
# In[5]:
# In[7]:
#plotter = Plotter()
#plotter.plot(solver=pinn)
@torch.no_grad()
def plot_solution(solver):
# get the problem
problem = solver.problem
# get spatial points
spatial_samples = problem.spatial_domain.sample(30, "grid")
# compute pinn solution, true solution and absolute difference
data = {
"PINN solution": solver(spatial_samples),
"True solution": problem.truth_solution(spatial_samples),
"Absolute Difference": torch.abs(
solver(spatial_samples) - problem.truth_solution(spatial_samples)
)
}
# plot the solution
for idx, (title, field) in enumerate(data.items()):
plt.subplot(1, 3, idx + 1)
plt.title(title)
plt.tricontourf( # convert to torch tensor + flatten
spatial_samples.extract("x").tensor.flatten(),
spatial_samples.extract("y").tensor.flatten(),
field.tensor.flatten(),
)
plt.colorbar(), plt.tight_layout()
# In[8]:
plt.figure(figsize=(12, 6))
plot_solution(solver=pinn)
# ## Solving the problem with extra-features PINNs
@@ -135,7 +176,7 @@ trainer.train()
#
# Finally, we perform the same training as before: the problem is `Poisson`, the network is composed by the same number of neurons and optimizer parameters are equal to previous test, the only change is the new extra feature.
# In[6]:
# In[9]:
class SinSin(torch.nn.Module):
@@ -170,8 +211,12 @@ model_feat = FeedForwardWithExtraFeatures(
layers=[10, 10],
extra_features=[SinSin()])
pinn_feat = PINN(problem, model_feat)
trainer_feat = Trainer(pinn_feat, max_epochs=1000, callbacks=[MetricTracker()], accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
pinn_feat = PINN(problem, model_feat, optimizer=TorchOptimizer(torch.optim.Adam, lr=0.006,weight_decay=1e-8))
trainer_feat = Trainer(pinn_feat, max_epochs=1000, accelerator='cpu', enable_model_summary=False,
train_size=1.0,
val_size=0.0,
test_size=0.0,
logger=TensorBoardLogger("tutorial_logs")) # we train on CPU and avoid model summary at beginning of training (optional)
trainer_feat.train()
@@ -179,10 +224,11 @@ trainer_feat.train()
# The predicted and exact solutions and the error between them are represented below.
# We can easily note that now our network, having almost the same condition as before, is able to reach additional order of magnitudes in accuracy.
# In[7]:
# In[10]:
#plotter.plot(solver=pinn_feat)
plt.figure(figsize=(12, 6))
plot_solution(solver=pinn_feat)
# ## Solving the problem with learnable extra-features PINNs
@@ -199,7 +245,7 @@ trainer_feat.train()
# where $\alpha$ and $\beta$ are the abovementioned parameters.
# Their implementation is quite trivial: by using the class `torch.nn.Parameter` we cam define all the learnable parameters we need, and they are managed by `autograd` module!
# In[8]:
# In[11]:
class SinSinAB(torch.nn.Module):
@@ -219,15 +265,19 @@ class SinSinAB(torch.nn.Module):
# make model + solver + trainer
model_lean = FeedForwardWithExtraFeatures(
model_learn = FeedForwardWithExtraFeatures(
input_dimensions=len(problem.input_variables) + 1, #we add one as also we consider the extra feature dimension
output_dimensions=len(problem.output_variables),
func=Softplus,
layers=[10, 10],
extra_features=[SinSinAB()])
pinn_lean = PINN(problem, model_lean)
trainer_learn = Trainer(pinn_lean, max_epochs=1000, accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
pinn_learn = PINN(problem, model_learn, optimizer=TorchOptimizer(torch.optim.Adam, lr=0.006,weight_decay=1e-8))
trainer_learn = Trainer(pinn_learn, max_epochs=1000, enable_model_summary=False,
train_size=1.0,
val_size=0.0,
test_size=0.0,
logger=TensorBoardLogger("tutorial_logs")) # we train on CPU and avoid model summary at beginning of training (optional)
# train
trainer_learn.train()
@@ -235,18 +285,22 @@ trainer_learn.train()
# Umh, the final loss is not appreciabily better than previous model (with static extra features), despite the usage of learnable parameters. This is mainly due to the over-parametrization of the network: there are many parameter to optimize during the training, and the model in unable to understand automatically that only the parameters of the extra feature (and not the weights/bias of the FFN) should be tuned in order to fit our problem. A longer training can be helpful, but in this case the faster way to reach machine precision for solving the Poisson problem is removing all the hidden layers in the `FeedForward`, keeping only the $\alpha$ and $\beta$ parameters of the extra feature.
# In[9]:
# In[12]:
# make model + solver + trainer
model_lean= FeedForwardWithExtraFeatures(
model_learn= FeedForwardWithExtraFeatures(
layers=[],
func=Softplus,
output_dimensions=len(problem.output_variables),
input_dimensions=len(problem.input_variables)+1,
extra_features=[SinSinAB()])
pinn_learn = PINN(problem, model_lean)
trainer_learn = Trainer(pinn_learn, max_epochs=1000, callbacks=[MetricTracker()], accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
pinn_learn = PINN(problem, model_learn, optimizer=TorchOptimizer(torch.optim.Adam, lr=0.006,weight_decay=1e-8))
trainer_learn = Trainer(pinn_learn, max_epochs=1000, accelerator='cpu', enable_model_summary=False,
train_size=1.0,
val_size=0.0,
test_size=0.0,
logger=TensorBoardLogger("tutorial_logs")) # we train on CPU and avoid model summary at beginning of training (optional)
# train
trainer_learn.train()
@@ -257,20 +311,14 @@ trainer_learn.train()
#
# We conclude here by showing the graphical comparison of the unknown field and the loss trend for all the test cases presented here: the standard PINN, PINN with extra features, and PINN with learnable extra features.
# In[10]:
#plotter.plot(solver=pinn_learn)
# Let us compare the training losses for the various types of training
# In[11]:
# In[13]:
#plotter.plot_loss(trainer, logy=True, label='Standard')
#plotter.plot_loss(trainer_feat, logy=True,label='Static Features')
#plotter.plot_loss(trainer_learn, logy=True, label='Learnable Features')
# Load the TensorBoard extension
get_ipython().run_line_magic('load_ext', 'tensorboard')
get_ipython().run_line_magic('tensorboard', "--logdir 'tutorial_logs'")
# ## What's next?