Update tutorials (#463)
--------- Co-authored-by: Dario Coscia <93731561+dario-coscia@users.noreply.github.com>
This commit is contained in:
committed by
FilippoOlivo
parent
8b797d589a
commit
bd9b49530a
132
tutorials/tutorial9/tutorial.ipynb
vendored
132
tutorials/tutorial9/tutorial.ipynb
vendored
File diff suppressed because one or more lines are too long
58
tutorials/tutorial9/tutorial.py
vendored
58
tutorials/tutorial9/tutorial.py
vendored
@@ -28,17 +28,20 @@ if IN_COLAB:
|
||||
|
||||
import torch
|
||||
import matplotlib.pyplot as plt
|
||||
plt.style.use('tableau-colorblind10')
|
||||
from pina import Condition, Plotter
|
||||
import warnings
|
||||
|
||||
from pina import Condition
|
||||
from pina.problem import SpatialProblem
|
||||
from pina.operators import laplacian
|
||||
from pina.operator import laplacian
|
||||
from pina.model import FeedForward
|
||||
from pina.model.layers import PeriodicBoundaryEmbedding # The PBC module
|
||||
from pina.solvers import PINN
|
||||
from pina.model.block import PeriodicBoundaryEmbedding # The PBC module
|
||||
from pina.solver import PINN
|
||||
from pina.trainer import Trainer
|
||||
from pina.domain import CartesianDomain
|
||||
from pina.equation import Equation
|
||||
|
||||
warnings.filterwarnings('ignore')
|
||||
|
||||
|
||||
# ## The problem definition
|
||||
#
|
||||
@@ -63,7 +66,7 @@ from pina.equation import Equation
|
||||
# and $f(x)=-6\pi^2\sin(3\pi x)\cos(\pi x)$ which give a solution that can be
|
||||
# computed analytically $u(x) = \sin(\pi x)\cos(3\pi x)$.
|
||||
|
||||
# In[ ]:
|
||||
# In[2]:
|
||||
|
||||
|
||||
class Helmholtz(SpatialProblem):
|
||||
@@ -139,23 +142,52 @@ model = torch.nn.Sequential(PeriodicBoundaryEmbedding(input_dimension=1,
|
||||
# for all dimensions using a dictionary, e.g. `periods={'x':2, 'y':3, ...}`
|
||||
# would indicate a periodicity of $2$ in $x$, $3$ in $y$, and so on...
|
||||
#
|
||||
# We will now solve the problem as usually with the `PINN` and `Trainer` class.
|
||||
# We will now solve the problem as usually with the `PINN` and `Trainer` class, then we will look at the losses using the `MetricTracker` callback from `pina.callback`.
|
||||
|
||||
# In[ ]:
|
||||
# In[4]:
|
||||
|
||||
|
||||
pinn = PINN(problem=problem, model=model)
|
||||
trainer = Trainer(pinn, max_epochs=5000, accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
|
||||
from pina.callback import MetricTracker
|
||||
from pina.optim import TorchOptimizer
|
||||
|
||||
pinn = PINN(problem=problem, model=model, optimizer=TorchOptimizer(torch.optim.Adam, lr=0.001))
|
||||
trainer = Trainer(pinn, max_epochs=5000, accelerator='cpu', enable_model_summary=False, # we train on CPU and avoid model summary at beginning of training (optional)
|
||||
logger=True,
|
||||
callbacks=[MetricTracker()],
|
||||
train_size=1.0,
|
||||
val_size=0.0,
|
||||
test_size=0.0)
|
||||
trainer.train()
|
||||
|
||||
|
||||
# In[5]:
|
||||
|
||||
|
||||
#plot loss
|
||||
trainer_metrics = trainer.callbacks[0].metrics
|
||||
print(trainer.callbacks[0].metrics)
|
||||
loss = trainer_metrics['train_loss']
|
||||
epochs = range(len(loss))
|
||||
plt.plot(epochs, loss.cpu())
|
||||
# plotting
|
||||
plt.xlabel('epoch')
|
||||
plt.ylabel('loss')
|
||||
plt.yscale('log')
|
||||
|
||||
|
||||
# We are going to plot the solution now!
|
||||
|
||||
# In[6]:
|
||||
|
||||
|
||||
pl = Plotter()
|
||||
pl.plot(pinn)
|
||||
pts = pinn.problem.spatial_domain.sample(256, 'grid', variables='x')
|
||||
predicted_output = pinn.forward(pts).extract('u').as_subclass(torch.Tensor).cpu().detach()
|
||||
true_output = pinn.problem.truth_solution(pts).cpu().detach()
|
||||
pts = pts.cpu()
|
||||
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 8))
|
||||
ax.plot(pts.extract(['x']), predicted_output, label='Neural Network solution')
|
||||
ax.plot(pts.extract(['x']), true_output, label='True solution')
|
||||
plt.legend()
|
||||
|
||||
|
||||
# Great, they overlap perfectly! This seems a good result, considering the simple neural network used to some this (complex) problem. We will now test the neural network on the domain $[-4, 4]$ without retraining. In principle the periodicity should be present since the $v$ function ensures the periodicity in $(-\infty, \infty)$.
|
||||
@@ -201,5 +233,3 @@ with torch.no_grad():
|
||||
# 3. Exploit extrafeature training ?
|
||||
#
|
||||
# 4. Many more...
|
||||
|
||||
#
|
||||
|
||||
Reference in New Issue
Block a user