Skip to content

Commit 4ea6df6

Browse files
committed
Update tutorials 1 through 7
1 parent 69a37a7 commit 4ea6df6

File tree

15 files changed

+478
-244
lines changed

15 files changed

+478
-244
lines changed

tutorials/tutorial1/tutorial.ipynb

Lines changed: 174 additions & 34 deletions
Large diffs are not rendered by default.

tutorials/tutorial1/tutorial.py

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ class TimeSpaceODE(SpatialProblem, TimeDependentProblem):
8787

8888
# ### Write the problem class
8989
#
90-
# Once the `Problem` class is initialized, we need to represent the differential equation in **PINA**. In order to do this, we need to load the **PINA** operators from `pina.operators` module. Again, we'll consider Equation (1) and represent it in **PINA**:
90+
# Once the `Problem` class is initialized, we need to represent the differential equation in **PINA**. In order to do this, we need to load the **PINA** operators from `pina.operator` module. Again, we'll consider Equation (1) and represent it in **PINA**:
9191

9292
# In[2]:
9393

@@ -99,7 +99,7 @@ class TimeSpaceODE(SpatialProblem, TimeDependentProblem):
9999
from pina.equation import Equation, FixedValue
100100

101101
import torch
102-
102+
import matplotlib.pyplot as plt
103103

104104
class SimpleODE(SpatialProblem):
105105

@@ -185,7 +185,6 @@ def truth_solution(self, pts):
185185
# In[6]:
186186

187187

188-
import matplotlib.pyplot as plt
189188
variables=problem.spatial_variables
190189
fig = plt.figure()
191190
proj = "3d" if len(variables) == 3 else None
@@ -197,15 +196,15 @@ def truth_solution(self, pts):
197196

198197
# ## Perform a small training
199198

200-
# Once we have defined the problem and generated the data we can start the modelling. Here we will choose a `FeedForward` neural network available in `pina.model`, and we will train using the `PINN` solver from `pina.solver`. We highlight that this training is fairly simple, for more advanced stuff consider the tutorials in the ***Physics Informed Neural Networks*** section of ***Tutorials***. For training we use the `Trainer` class from `pina.trainer`. Here we show a very short training and some method for plotting the results. Notice that by default all relevant metrics (e.g. MSE error during training) are going to be tracked using a `lightning` logger, by default `CSVLogger`. If you want to track the metric by yourself without a logger, use `pina.callbacks.MetricTracker`.
199+
# Once we have defined the problem and generated the data we can start the modelling. Here we will choose a `FeedForward` neural network available in `pina.model`, and we will train using the `PINN` solver from `pina.solver`. We highlight that this training is fairly simple, for more advanced stuff consider the tutorials in the ***Physics Informed Neural Networks*** section of ***Tutorials***. For training we use the `Trainer` class from `pina.trainer`. Here we show a very short training and some method for plotting the results. Notice that by default all relevant metrics (e.g. MSE error during training) are going to be tracked using a `lightning` logger, by default `CSVLogger`. If you want to track the metric by yourself without a logger, use `pina.callback.MetricTracker`.
201200

202201
# In[7]:
203202

204203

205204
from pina import Trainer
206205
from pina.solver import PINN
207206
from pina.model import FeedForward
208-
from pina.callback import MetricTracker
207+
from lightning.pytorch.loggers import TensorBoardLogger
209208

210209

211210
# build the model
@@ -220,13 +219,13 @@ def truth_solution(self, pts):
220219
pinn = PINN(problem, model)
221220

222221
# create the trainer
223-
trainer = Trainer(solver=pinn, max_epochs=1500, callbacks=[MetricTracker()], accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
222+
trainer = Trainer(solver=pinn, max_epochs=1500, logger=TensorBoardLogger('tutorial_logs'), accelerator='cpu', enable_model_summary=False) # we train on CPU and avoid model summary at beginning of training (optional)
224223

225224
# train
226225
trainer.train()
227226

228227

229-
# After the training we can inspect trainer logged metrics (by default **PINA** logs mean square error residual loss). The logged metrics can be accessed online using one of the `Lightinig` loggers. The final loss can be accessed by `trainer.logged_metrics`
228+
# After the training we can inspect trainer logged metrics (by default **PINA** logs mean square error residual loss). The logged metrics can be accessed online using one of the `Lightning` loggers. The final loss can be accessed by `trainer.logged_metrics`
230229

231230
# In[8]:
232231

@@ -250,24 +249,19 @@ def truth_solution(self, pts):
250249
plt.legend()
251250

252251

253-
# The solution is overlapped with the actual one, and they are barely indistinguishable. We can also plot easily the loss:
252+
# The solution is overlapped with the actual one, and they are barely indistinguishable. We can also take a look at the loss using `TensorBoard`:
254253

255254
# In[10]:
256255

257256

258-
list_ = [
259-
idx for idx, s in enumerate(trainer.callbacks)
260-
if isinstance(s, MetricTracker)
261-
]
262-
trainer_metrics = trainer.callbacks[list_[0]].metrics
257+
# Load the TensorBoard extension
258+
get_ipython().run_line_magic('load_ext', 'tensorboard')
259+
260+
# In[12]:
261+
263262

264-
loss = trainer_metrics['val_loss']
265-
epochs = range(len(loss))
266-
plt.plot(epochs, loss.cpu())
267-
# plotting
268-
plt.xlabel('epoch')
269-
plt.ylabel('loss')
270-
plt.yscale('log')
263+
# Show saved losses
264+
get_ipython().run_line_magic('tensorboard', "--logdir 'tutorial_logs'")
271265

272266

273267
# As we can see the loss has not reached a minimum, suggesting that we could train for longer

tutorials/tutorial2/tutorial.ipynb

Lines changed: 137 additions & 77 deletions
Large diffs are not rendered by default.

tutorials/tutorial2/tutorial.py

Lines changed: 86 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323

2424
import torch
2525
from torch.nn import Softplus
26+
import matplotlib.pyplot as plt
27+
import warnings
2628

2729
from pina.problem import SpatialProblem
2830
from pina.operator import laplacian
@@ -31,9 +33,13 @@
3133
from pina.trainer import Trainer
3234
from pina.domain import CartesianDomain
3335
from pina.equation import Equation, FixedValue
34-
from pina import Condition, LabelTensor#,Plotter
36+
from pina import Condition, LabelTensor
3537
from pina.callback import MetricTracker
3638

39+
from lightning.pytorch.loggers import TensorBoardLogger
40+
41+
warnings.filterwarnings('ignore')
42+
3743

3844
# ## The problem definition
3945

@@ -90,9 +96,9 @@ def poisson_sol(self, pts):
9096

9197
# 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.
9298
#
93-
# 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.
99+
# 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.
94100

95-
# In[4]:
101+
# In[ ]:
96102

97103

98104
# make model + solver + trainer
@@ -102,21 +108,58 @@ def poisson_sol(self, pts):
102108
output_dimensions=len(problem.output_variables),
103109
input_dimensions=len(problem.input_variables)
104110
)
111+
kwargs= {'lr':0.006, 'weight_decay':1e-8}
105112
pinn = PINN(problem, model)
106-
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)
113+
trainer = Trainer(pinn, max_epochs=1000, accelerator='cpu', enable_model_summary=False,
114+
train_size=1.0,
115+
val_size=0.0,
116+
test_size=0.0,
117+
logger=TensorBoardLogger("tutorial_logs"),
118+
enable_progress_bar=False,
119+
**kwargs
120+
) # we train on CPU and avoid model summary at beginning of training (optional)
107121

108122
# train
109123
trainer.train()
110124

111125

112-
# Now the `Plotter` class is used to plot the results.
126+
# Now we plot the results using `matplotlib`.
113127
# 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.
114128

115-
# In[5]:
129+
# In[ ]:
130+
131+
132+
@torch.no_grad()
133+
def plot_solution(solver):
134+
# get the problem
135+
problem = solver.problem
136+
# get spatial points
137+
spatial_samples = problem.spatial_domain.sample(30, "grid")
138+
# compute pinn solution, true solution and absolute difference
139+
data = {
140+
"PINN solution": solver(spatial_samples),
141+
"True solution": problem.truth_solution(spatial_samples),
142+
"Absolute Difference": torch.abs(
143+
solver(spatial_samples) - problem.truth_solution(spatial_samples)
144+
)
145+
}
146+
# plot the solution
147+
for idx, (title, field) in enumerate(data.items()):
148+
plt.subplot(1, 3, idx + 1)
149+
plt.title(title)
150+
plt.tricontourf( # convert to torch tensor + flatten
151+
spatial_samples.extract("x").tensor.flatten(),
152+
spatial_samples.extract("y").tensor.flatten(),
153+
field.tensor.flatten(),
154+
)
155+
plt.colorbar(), plt.tight_layout()
156+
116157

158+
# In[ ]:
117159

118-
#plotter = Plotter()
119-
#plotter.plot(solver=pinn)
160+
161+
plt.figure(figsize=(12, 6))
162+
plot_solution(solver=pinn)
120163

121164

122165
# ## Solving the problem with extra-features PINNs
@@ -135,7 +178,7 @@ def poisson_sol(self, pts):
135178
#
136179
# 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.
137180

138-
# In[6]:
181+
# In[ ]:
139182

140183

141184
class SinSin(torch.nn.Module):
@@ -171,18 +214,25 @@ def forward(self, x):
171214
extra_features=[SinSin()])
172215

173216
pinn_feat = PINN(problem, model_feat)
174-
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)
217+
trainer_feat = Trainer(pinn_feat, max_epochs=1000, accelerator='cpu', enable_model_summary=False,
218+
lr=0.006, weight_decay=1e-8,
219+
train_size=1.0,
220+
val_size=0.0,
221+
test_size=0.0,
222+
logger=TensorBoardLogger("tutorial_logs"),
223+
enable_progress_bar=False,) # we train on CPU and avoid model summary at beginning of training (optional)
175224

176225
trainer_feat.train()
177226

178227

179228
# The predicted and exact solutions and the error between them are represented below.
180229
# 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.
181230

182-
# In[7]:
231+
# In[ ]:
183232

184233

185-
#plotter.plot(solver=pinn_feat)
234+
plt.figure(figsize=(12, 6))
235+
plot_solution(solver=pinn_feat)
186236

187237

188238
# ## Solving the problem with learnable extra-features PINNs
@@ -199,7 +249,7 @@ def forward(self, x):
199249
# where $\alpha$ and $\beta$ are the abovementioned parameters.
200250
# 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!
201251

202-
# In[8]:
252+
# In[ ]:
203253

204254

205255
class SinSinAB(torch.nn.Module):
@@ -219,34 +269,46 @@ def forward(self, x):
219269

220270

221271
# make model + solver + trainer
222-
model_lean = FeedForwardWithExtraFeatures(
272+
model_learn = FeedForwardWithExtraFeatures(
223273
input_dimensions=len(problem.input_variables) + 1, #we add one as also we consider the extra feature dimension
224274
output_dimensions=len(problem.output_variables),
225275
func=Softplus,
226276
layers=[10, 10],
227277
extra_features=[SinSinAB()])
228278

229-
pinn_lean = PINN(problem, model_lean)
230-
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)
279+
pinn_learn = PINN(problem, model_learn)
280+
trainer_learn = Trainer(pinn_learn, max_epochs=1000, enable_model_summary=False,
281+
lr=0.006, weight_decay=1e-8,
282+
train_size=1.0,
283+
val_size=0.0,
284+
test_size=0.0,
285+
logger=TensorBoardLogger("tutorial_logs"),
286+
enable_progress_bar=False) # we train on CPU and avoid model summary at beginning of training (optional)
231287

232288
# train
233289
trainer_learn.train()
234290

235291

236292
# 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.
237293

238-
# In[9]:
294+
# In[ ]:
239295

240296

241297
# make model + solver + trainer
242-
model_lean= FeedForwardWithExtraFeatures(
298+
model_learn= FeedForwardWithExtraFeatures(
243299
layers=[],
244300
func=Softplus,
245301
output_dimensions=len(problem.output_variables),
246302
input_dimensions=len(problem.input_variables)+1,
247303
extra_features=[SinSinAB()])
248-
pinn_learn = PINN(problem, model_lean)
249-
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)
304+
pinn_learn = PINN(problem, model_learn)
305+
trainer_learn = Trainer(pinn_learn, max_epochs=1000, accelerator='cpu', enable_model_summary=False,
306+
lr=0.006, weight_decay=1e-8,
307+
train_size=1.0,
308+
val_size=0.0,
309+
test_size=0.0,
310+
logger=TensorBoardLogger("tutorial_logs"),
311+
enable_progress_bar=False) # we train on CPU and avoid model summary at beginning of training (optional)
250312

251313
# train
252314
trainer_learn.train()
@@ -257,20 +319,14 @@ def forward(self, x):
257319
#
258320
# 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.
259321

260-
# In[10]:
261-
262-
263-
#plotter.plot(solver=pinn_learn)
264-
265-
266322
# Let us compare the training losses for the various types of training
267323

268-
# In[11]:
324+
# In[ ]:
269325

270326

271-
#plotter.plot_loss(trainer, logy=True, label='Standard')
272-
#plotter.plot_loss(trainer_feat, logy=True,label='Static Features')
273-
#plotter.plot_loss(trainer_learn, logy=True, label='Learnable Features')
327+
# Load the TensorBoard extension
328+
get_ipython().run_line_magic('load_ext', 'tensorboard')
329+
get_ipython().run_line_magic('tensorboard', "--logdir 'tutorial_logs'")
274330

275331

276332
# ## What's next?

tutorials/tutorial4/tutorial.ipynb

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,14 +44,13 @@
4444
"\n",
4545
"import torch \n",
4646
"import matplotlib.pyplot as plt \n",
47-
"plt.style.use('tableau-colorblind10')\n",
47+
"import torchvision # for MNIST dataset\n",
4848
"\n",
4949
"from pina.problem import AbstractProblem\n",
5050
"from pina.solver import SupervisedSolver\n",
5151
"from pina.trainer import Trainer\n",
5252
"from pina import Condition, LabelTensor\n",
5353
"from pina.model.block import ContinuousConvBlock \n",
54-
"import torchvision # for MNIST dataset\n",
5554
"from pina.model import FeedForward # for building AE and MNIST classification"
5655
]
5756
},
@@ -928,7 +927,7 @@
928927
"name": "python",
929928
"nbconvert_exporter": "python",
930929
"pygments_lexer": "ipython3",
931-
"version": "3.12.7"
930+
"version": "3.12.3"
932931
}
933932
},
934933
"nbformat": 4,

0 commit comments

Comments
 (0)